5 import Control.Monad.State
9 data StackIL = Dup | Ld Addr Type | Add Type | Store Addr Type deriving Show
11 type Target = (Int,Type)
12 type Source = (Int,Type)
16 data RegIL = RMov Target Source | RAdd Target Source Source
17 | RStore Addr Source | RLoad Source Addr deriving Show
19 data Type = Int | Bottom deriving (Show,Eq)
21 type StackElem = (Int,Type)
23 type Stack = [StackElem]
26 dup = modify (\(top@(i,t):xs) -> (i+1,t) : top : xs)
28 push :: Type -> State Stack Int
29 push t = do tos <- get
31 top@(i,_):xs -> put ((i + 1, t) : top : xs) >> return i
32 [] -> put [(0,t)] >> return 0
34 pop :: State Stack StackElem
39 nextElem :: State Stack Int
40 nextElem = fmap ((+ 1) . fst . head) get
42 aInterpret' :: StackIL -> State Stack [RegIL]
43 aInterpret' Dup = dup >> return []
44 aInterpret' (Ld addr t) = do s <- push t
45 return [RLoad (s,t) addr]
46 aInterpret' (Store addr t) = do (xA,tA) <- pop
47 return [RStore addr (xA,tA)]
48 aInterpret' (Add t) = do (iA,ta) <- pop
51 if ta /= t || tb /=t then error "type mismatch in add"
52 else return [ RAdd (tmpReg,ta) (iA,ta) (iB,tb),
53 RMov (iB,tb) (tmpReg,ta)]
55 aInterpret :: [StackIL] -> State Stack [RegIL]
56 aInterpret = foldr (liftM2 (++) . aInterpret') (return [])
58 generateRegisterIR :: [StackIL] -> [RegIL]
59 generateRegisterIR = (`evalState` []) . aInterpret
61 --data StackIL = Dup | Ld Addr Type | Add Type | Store Addr Type
62 testCase1 = [ Ld 0 Int, Ld 1 Int, Dup , Add Int, Add Int, Store 0 Int]
64 bench = concat . replicate 100000
68 data Expr = VarE Var | AddE Var Var | Lit Int | CLe Expr Expr
71 Label :: TLabel -> Node C O
72 Assign :: Var -> Expr -> Node O O
73 If :: Expr -> TLabel -> TLabel -> Node O C
76 Branch :: TLabel -> Node C C
78 {-testProgram = [ Assign "x" (Lit 3),
80 If (CLe (VarE "x") (VarE "y")) 1 2,