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