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