------------------------------------------------------------------------------ -- An implementation of the maximal munch algorithm ------------------------------------------------------------------------------ import IRTree -- Translate statements munchStm :: Stm -> [String] munchStm (MOVEM (BINOP PLUS e1 (CONST i)) e2) = munchExp e1 ++ munchExp e2 ++ codegen "STORE" munchStm (MOVEM (BINOP PLUS (CONST i) e1) e2) = munchExp e1 ++ munchExp e2 ++ codegen "STORE" munchStm (MOVEM e1 (MEM e2)) = munchExp e1 ++ munchExp e2 ++ codegen "MEMMOVE" munchStm (MOVEM (CONST i) e) = munchExp e ++ codegen "STORE" munchStm (MOVET r (BINOP PLUS e (CONST i))) = munchExp e ++ codegen "LOAD" munchStm (MOVET r (BINOP PLUS (CONST i) e)) = munchExp e ++ codegen "LOAD" munchStm (MOVET r (CONST i)) = codegen "ADDI" munchStm (MOVET r e) = munchExp e ++ codegen "ADDI" -- Translate expressions munchExp :: Exp -> [String] munchExp (MEM (BINOP PLUS e (CONST i))) = munchExp e ++ codegen "LOAD" munchExp (MEM (BINOP PLUS (CONST i) e)) = munchExp e ++ codegen "LOAD" munchExp (MEM (CONST i)) = codegen "LOAD" munchExp (MEM e) = munchExp e ++ codegen "LOAD" munchExp (BINOP PLUS e (CONST i)) = munchExp e ++ codegen "ADDI" munchExp (BINOP PLUS (CONST i) e) = munchExp e ++ codegen "ADDI" munchExp (BINOP PLUS e1 e2) = munchExp e1 ++ munchExp e2 ++ codegen "ADD" munchExp (BINOP MUL e1 e2) = munchExp e1 ++ munchExp e2 ++ codegen "MUL" munchExp (CONST i) = codegen "ADDI" munchExp (TEMP t) = [] codegen :: String -> [String] codegen c = [c] -- a bit simplified (missing: registers) ------------------------------------------------------------------------------ -- Example: intermediate code of translating "a[i] := x": exTree :: Stm exTree = MOVEM (BINOP PLUS (MEM (BINOP PLUS (TEMP ra) (CONST off_a))) (BINOP MUL (TEMP ri) (CONST 4))) (MEM (BINOP PLUS (TEMP ra) (CONST off_x))) -- Register holding current value of i: ri = Temp "Ri" -- offset of x: off_x = 16 -- offset of a: off_a = 12 -- Standard register holding RA: ra = Temp "RA" -- Generate machince code of example via maximal munch: transExample :: [String] transExample = munchStm exTree ------------------------------------------------------------------------------