Big collection of patches for the new codegen branch.
[ghc-hetmet.git] / compiler / cmm / CmmCvt.hs
1 {-# LANGUAGE PatternGuards #-}
2
3 module CmmCvt
4   ( cmmToZgraph, cmmOfZgraph )
5 where
6
7 import BlockId
8 import Cmm
9 import CmmExpr
10 import MkZipCfgCmm hiding (CmmGraph)
11 import ZipCfg       -- imported for reverse conversion
12 import ZipCfgCmmRep -- imported for reverse conversion
13 import CmmZipUtil
14 import PprCmm()
15 import qualified ZipCfg as G
16
17 import FastString
18 import Monad
19 import Outputable
20 import Panic
21 import UniqSupply
22
23 import Maybe
24
25 cmmToZgraph :: GenCmm d h (ListGraph CmmStmt) -> UniqSM (GenCmm d h CmmGraph)
26 cmmOfZgraph :: GenCmm d h (CmmGraph)          ->         GenCmm d h (ListGraph CmmStmt)
27
28 cmmToZgraph (Cmm tops) = liftM Cmm $ mapM mapTop tops
29   where mapTop (CmmProc h l args g) =
30           toZgraph (showSDoc $ ppr l) args g >>= return . CmmProc h l args
31         mapTop (CmmData s ds) = return $ CmmData s ds
32 cmmOfZgraph = cmmMapGraph ofZgraph
33
34 toZgraph :: String -> CmmFormals -> ListGraph CmmStmt -> UniqSM CmmGraph
35 toZgraph _ _ (ListGraph []) = lgraphOfAGraph 0 emptyAGraph
36 toZgraph fun_name args g@(ListGraph (BasicBlock id ss : other_blocks)) = 
37            let (offset, entry) = mkEntry id Native args in
38            labelAGraph id offset $
39               entry <*> mkStmts ss <*> foldr addBlock emptyAGraph other_blocks
40   where addBlock (BasicBlock id ss) g =
41           mkLabel id emptyStackInfo <*> mkStmts ss <*> g
42         updfr_sz = panic "upd frame size lost in cmm conversion"
43         mkStmts (CmmNop        : ss)  = mkNop        <*> mkStmts ss 
44         mkStmts (CmmComment s  : ss)  = mkComment s  <*> mkStmts ss
45         mkStmts (CmmAssign l r : ss)  = mkAssign l r <*> mkStmts ss
46         mkStmts (CmmStore  l r : ss)  = mkStore  l r <*> mkStmts ss
47         mkStmts (CmmCall (CmmCallee f conv) res args (CmmSafe srt) CmmMayReturn : ss) =
48             mkCall f conv' (map hintlessCmm res) (map hintlessCmm args) updfr_sz
49             <*> mkStmts ss 
50               where conv' = Foreign (ForeignConvention conv [] []) -- JD: DUBIOUS
51         mkStmts (CmmCall (CmmPrim {}) _ _ (CmmSafe _) _ : _) =
52             panic "safe call to a primitive CmmPrim CallishMachOp"
53         mkStmts (CmmCall f res args CmmUnsafe CmmMayReturn : ss) =
54                       mkUnsafeCall (convert_target f res args)
55                         (strip_hints res) (strip_hints args)
56                       <*> mkStmts ss
57         mkStmts (CmmCondBranch e l : fbranch) =
58             mkCmmIfThenElse e (mkBranch l) (mkStmts fbranch)
59         mkStmts (last : []) = mkLast last
60         mkStmts []          = bad "fell off end"
61         mkStmts (_ : _ : _) = bad "last node not at end"
62         bad msg = pprPanic (msg ++ " in function " ++ fun_name) (ppr g)
63         mkLast (CmmCall (CmmCallee f conv) []     args _ CmmNeverReturns) =
64             mkFinalCall f conv (map hintlessCmm args) updfr_sz
65         mkLast (CmmCall (CmmPrim {}) _ _ _ CmmNeverReturns) =
66             panic "Call to CmmPrim never returns?!"
67         mkLast (CmmSwitch scrutinee table) = mkSwitch scrutinee table
68         -- SURELY, THESE HINTLESS ARGS ARE WRONG AND WILL BE FIXED WHEN CALLING
69         -- CONVENTIONS ARE HONORED?
70         mkLast (CmmJump tgt args)          = mkJump   tgt (map hintlessCmm args) updfr_sz
71         mkLast (CmmReturn ress)            =
72           mkReturnSimple (map hintlessCmm ress) updfr_sz
73         mkLast (CmmBranch tgt)             = mkBranch tgt
74         mkLast (CmmCall _f (_:_) _args _ CmmNeverReturns) =
75                    panic "Call never returns but has results?!"
76         mkLast _ = panic "fell off end of block"
77
78 strip_hints :: [CmmHinted a] -> [a]
79 strip_hints = map hintlessCmm
80
81 convert_target :: CmmCallTarget -> HintedCmmFormals -> HintedCmmActuals -> MidCallTarget
82 convert_target (CmmCallee e cc) ress  args  = ForeignTarget e (ForeignConvention cc (map cmmHint args) (map cmmHint ress))
83 convert_target (CmmPrim op)        _ress _args = PrimTarget op
84
85 add_hints :: Convention -> ValueDirection -> [a] -> [CmmHinted a]
86 add_hints conv vd args = zipWith CmmHinted args (get_hints conv vd)
87
88 get_hints :: Convention -> ValueDirection -> [ForeignHint]
89 get_hints (Foreign (ForeignConvention _ hints _)) Arguments = hints
90 get_hints (Foreign (ForeignConvention _ _ hints)) Results   = hints
91 get_hints _other_conv                             _vd       = repeat NoHint
92
93 get_conv :: MidCallTarget -> Convention
94 get_conv (PrimTarget _)       = Native
95 get_conv (ForeignTarget _ fc) = Foreign fc
96
97 cmm_target :: MidCallTarget -> CmmCallTarget
98 cmm_target (PrimTarget op) = CmmPrim op
99 cmm_target (ForeignTarget e (ForeignConvention cc _ _)) = CmmCallee e cc
100
101 ofZgraph :: CmmGraph -> ListGraph CmmStmt
102 ofZgraph g = ListGraph $ swallow blocks
103     where blocks = G.postorder_dfs g
104           -- | the next two functions are hooks on which to hang debugging info
105           extend_entry stmts = stmts
106           extend_block _id stmts = stmts
107           _extend_entry stmts = scomment showblocks : scomment cscomm : stmts
108           showblocks = "LGraph has " ++ show (length blocks) ++ " blocks:" ++
109                        concat (map (\(G.Block id _ _) -> " " ++ show id) blocks)
110           cscomm = "Call successors are" ++
111                    (concat $ map (\id -> " " ++ show id) $ blockSetToList call_succs)
112           swallow [] = []
113           swallow (G.Block id _ t : rest) = tail id [] t rest
114           tail id prev' (G.ZTail m t)             rest = tail id (mid m : prev') t rest
115           tail id prev' (G.ZLast G.LastExit)      rest = exit id prev' rest
116           tail id prev' (G.ZLast (G.LastOther l)) rest = last id prev' l rest
117           mid (MidComment s)  = CmmComment s
118           mid (MidAssign l r) = CmmAssign l r
119           mid (MidStore  l r) = CmmStore  l r
120           mid (MidForeignCall _ target ress args)
121                 = CmmCall (cmm_target target)
122                           (add_hints conv Results   ress) 
123                           (add_hints conv Arguments args) 
124                           CmmUnsafe CmmMayReturn
125                 where
126                   conv = get_conv target
127           block' id prev'
128               | id == G.lg_entry g = BasicBlock id $ extend_entry    (reverse prev')
129               | otherwise          = BasicBlock id $ extend_block id (reverse prev')
130           last id prev' l n =
131             let endblock stmt = block' id (stmt : prev') : swallow n in
132             case l of
133               LastBranch tgt ->
134                   case n of
135                     -- THIS OPT IS WRONG -- LABELS CAN SHOW UP ELSEWHERE IN THE GRAPH
136                     --G.Block id' _ t : bs
137                     --    | tgt == id', unique_pred id' 
138                     --    -> tail id prev' t bs -- optimize out redundant labels
139                     _ -> endblock (CmmBranch tgt)
140               LastCondBranch expr tid fid ->
141                   case n of
142                     G.Block id' _ t : bs
143                       -- It would be better to handle earlier, but we still must
144                       -- generate correct code here.
145                       | id' == fid, tid == fid, unique_pred id' ->
146                                  tail id prev' t bs
147                       | id' == fid, unique_pred id' ->
148                                  tail id (CmmCondBranch expr tid : prev') t bs
149                       | id' == tid, unique_pred id',
150                         Just e' <- maybeInvertCmmExpr expr ->
151                                  tail id (CmmCondBranch e'   fid : prev') t bs
152                     _ -> let instrs' = CmmBranch fid : CmmCondBranch expr tid : prev'
153                          in block' id instrs' : swallow n
154               LastSwitch arg ids   -> endblock $ CmmSwitch arg $ ids
155               LastCall e _ _ _ -> endblock $ CmmJump e []
156           exit id prev' n = -- highly irregular (assertion violation?)
157               let endblock stmt = block' id (stmt : prev') : swallow n in
158               case n of [] -> endblock (scomment "procedure falls off end")
159                         G.Block id' _ t : bs -> 
160                             if unique_pred id' then
161                                 tail id (scomment "went thru exit" : prev') t bs 
162                             else
163                                 endblock (CmmBranch id')
164           preds = zipPreds g
165           single_preds =
166               let add b single =
167                     let id = G.blockId b
168                     in  case lookupBlockEnv preds id of
169                           Nothing -> single
170                           Just s -> if sizeBlockSet s == 1 then
171                                         extendBlockSet single id
172                                     else single
173               in  G.fold_blocks add emptyBlockSet g
174           unique_pred id = elemBlockSet id single_preds
175           call_succs = 
176               let add b succs =
177                       case G.last (G.unzip b) of
178                         G.LastOther (LastCall _ (Just id) _ _) ->
179                           extendBlockSet succs id
180                         _ -> succs
181               in  G.fold_blocks add emptyBlockSet g
182           _is_call_succ id = elemBlockSet id call_succs
183
184 scomment :: String -> CmmStmt
185 scomment s = CmmComment $ mkFastString s