Optimiz.hs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module Optimiz where
  2. import Data.List
  3. import Data.List.Split
  4. repl_pair pos (val, val') list =
  5. take pos list ++ val : val' : drop (pos+2) list
  6. drop_pair pos list =
  7. take pos list ++ drop (pos+2) list
  8. pair x = (head lst, last lst)
  9. where
  10. lst = splitOn " " x
  11. commut_opt :: String -> [String] -> [String] -> Int -> [String]
  12. commut_opt _ (x:[]) code _ = code
  13. commut_opt oper (x:x':xs) code num =
  14. if op == "LOAD" && op' == oper && x' `notElem` xs
  15. then commut_opt oper (x':xs) n_code (num+1)
  16. else commut_opt oper (x':xs) code (num+1)
  17. where
  18. (op, name) = pair x
  19. (op', name') = pair x'
  20. new = (op ++ ' ': name', oper ++ ' ': name)
  21. n_code = repl_pair num new code
  22. sl_opt :: [String] -> [String] -> Int -> [String]
  23. sl_opt (x:[]) code _ = code
  24. sl_opt (x:x':xs) code num =
  25. if op == "STORE" && op' == "LOAD" && name == name'
  26. && (and $ map (notElem name) (map (splitOn " ") xs))
  27. then sl_opt (xs) n_code num
  28. else sl_opt (x':xs) code (num+1)
  29. where
  30. (op, name) = pair x
  31. (op', name') = pair x'
  32. n_code = drop_pair num code
  33. ls_opt :: [String] -> [String] -> Int -> [String]
  34. ls_opt (_:_:[]) code _ = code
  35. ls_opt (x:x':x'':xs) code num =
  36. if op == "LOAD" && op' == "STORE" && op'' == "LOAD"
  37. then ls_opt (x'':xs) n_code num
  38. else ls_opt (x':x'':xs) code (num+1)
  39. where
  40. (op, name) = pair x
  41. (op', name') = pair x'
  42. (op'', _) = pair x''
  43. code' = take num code
  44. code'' = map (repl_name_if name' name) (x'':xs)
  45. n_code = code' ++ code''
  46. repl_name_if pattern subst x =
  47. if name == pattern
  48. then op ++ ' ':subst
  49. else x
  50. where
  51. (op, name) = pair x
  52. optimiz :: [String] -> [String]
  53. optimiz code = res
  54. where
  55. a = commut_opt "ADD" code code 0
  56. b = commut_opt "MPY" a a 0
  57. c = sl_opt b b 0
  58. res = ls_opt c c 0