Merging in the new codegen branch
[ghc-hetmet.git] / compiler / codeGen / StgCmm.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Stg to C-- code generation
4 --
5 -- (c) The University of Glasgow 2004-2006
6 --
7 -----------------------------------------------------------------------------
8
9 module StgCmm ( codeGen ) where
10
11 #define FAST_STRING_NOT_NEEDED
12 #include "HsVersions.h"
13
14 import StgCmmProf
15 import StgCmmMonad
16 import StgCmmEnv
17 import StgCmmBind
18 import StgCmmCon
19 import StgCmmLayout
20 import StgCmmHeap
21 import StgCmmUtils
22 import StgCmmClosure
23 import StgCmmHpc
24 import StgCmmTicky
25
26 import MkZipCfgCmm
27 import Cmm
28 import CmmUtils
29 import CLabel
30 import PprCmm
31
32 import StgSyn
33 import PrelNames
34 import DynFlags
35 import StaticFlags
36
37 import HscTypes
38 import CostCentre
39 import Id
40 import IdInfo
41 import Type
42 import DataCon
43 import Name
44 import OccName
45 import TyCon
46 import Module
47 import ErrUtils
48 import Outputable
49
50 codeGen :: DynFlags
51          -> Module
52          -> [TyCon]
53          -> [Module]                    -- Directly-imported modules
54          -> CollectedCCs                -- (Local/global) cost-centres needing declaring/registering.
55          -> [(StgBinding,[(Id,[Id])])]  -- Bindings to convert, with SRTs
56          -> HpcInfo
57          -> IO [CmmZ]           -- Output
58
59 codeGen dflags this_mod data_tycons imported_mods 
60         cost_centre_info stg_binds hpc_info
61   = do  { showPass dflags "New CodeGen"
62         ; let way = buildTag dflags
63               main_mod = mainModIs dflags
64
65 -- Why?
66 --   ; mapM_ (\x -> seq x (return ())) data_tycons
67
68         ; code_stuff <- initC dflags this_mod $ do 
69                 { cmm_binds  <- mapM (getCmm . cgTopBinding dflags) stg_binds
70                 ; cmm_tycons <- mapM cgTyCon data_tycons
71                 ; cmm_init   <- getCmm (mkModuleInit way cost_centre_info 
72                                              this_mod main_mod
73                                              imported_mods hpc_info)
74                 ; return (cmm_binds ++ concat cmm_tycons ++ [cmm_init])
75                 }
76                 -- Put datatype_stuff after code_stuff, because the
77                 -- datatype closure table (for enumeration types) to
78                 -- (say) PrelBase_True_closure, which is defined in
79                 -- code_stuff
80
81                 -- N.B. returning '[Cmm]' and not 'Cmm' here makes it
82                 -- possible for object splitting to split up the
83                 -- pieces later.
84
85         ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "New Cmm" (pprCmms code_stuff)
86
87         ; return code_stuff }
88
89
90 ---------------------------------------------------------------
91 --      Top-level bindings
92 ---------------------------------------------------------------
93
94 {- 'cgTopBinding' is only used for top-level bindings, since they need
95 to be allocated statically (not in the heap) and need to be labelled.
96 No unboxed bindings can happen at top level.
97
98 In the code below, the static bindings are accumulated in the
99 @MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
100 This is so that we can write the top level processing in a compositional
101 style, with the increasing static environment being plumbed as a state
102 variable. -}
103
104 cgTopBinding :: DynFlags -> (StgBinding,[(Id,[Id])]) -> FCode ()
105 cgTopBinding dflags (StgNonRec id rhs, _srts)
106   = do  { id' <- maybeExternaliseId dflags id
107         --; mapM_ (mkSRT [id']) srts
108         ; (id,info) <- cgTopRhs id' rhs
109         ; addBindC id info      -- Add the *un-externalised* Id to the envt,
110                                 -- so we find it when we look up occurrences
111         }
112
113 cgTopBinding dflags (StgRec pairs, _srts)
114   = do  { let (bndrs, rhss) = unzip pairs
115         ; bndrs' <- mapFCs (maybeExternaliseId dflags) bndrs
116         ; let pairs' = zip bndrs' rhss
117         --; mapM_ (mkSRT bndrs')  srts
118         ; fixC (\ new_binds -> do 
119                 { addBindsC new_binds
120                 ; mapFCs ( \ (b,e) -> cgTopRhs b e ) pairs' })
121         ; return () }
122
123 --mkSRT :: [Id] -> (Id,[Id]) -> FCode ()
124 --mkSRT these (id,ids)
125 --  | null ids = nopC
126 --  | otherwise
127 --  = do        { ids <- mapFCs remap ids
128 --      ; id  <- remap id
129 --      ; emitRODataLits (mkSRTLabel (idName id) (idCafInfo id))
130 --                       (map (\id -> CmmLabel $ mkClosureLabel (idName id) (idCafInfo id)) ids)
131 --      }
132 --  where
133 --      -- Sigh, better map all the ids against the environment in 
134 --      -- case they've been externalised (see maybeExternaliseId below).
135 --    remap id = case filter (==id) these of
136 --              (id':_) -> returnFC id'
137 --              [] -> do { info <- getCgIdInfo id; return (cgIdInfoId info) }
138
139 -- Urgh!  I tried moving the forkStatics call from the rhss of cgTopRhs
140 -- to enclose the listFCs in cgTopBinding, but that tickled the
141 -- statics "error" call in initC.  I DON'T UNDERSTAND WHY!
142
143 cgTopRhs :: Id -> StgRhs -> FCode (Id, CgIdInfo)
144         -- The Id is passed along for setting up a binding...
145         -- It's already been externalised if necessary
146
147 cgTopRhs bndr (StgRhsCon _cc con args)
148   = forkStatics (cgTopRhsCon bndr con args)
149
150 cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag srt args body)
151   = ASSERT(null fvs)    -- There should be no free variables
152     setSRTLabel (mkSRTLabel (idName bndr) (idCafInfo bndr)) $
153     forkStatics (cgTopRhsClosure bndr cc bi upd_flag srt args body)
154
155
156
157 ---------------------------------------------------------------
158 --      Module initialisation code
159 ---------------------------------------------------------------
160
161 {- The module initialisation code looks like this, roughly:
162
163         FN(__stginit_Foo) {
164           JMP_(__stginit_Foo_1_p)
165         }
166
167         FN(__stginit_Foo_1_p) {
168         ...
169         }
170
171    We have one version of the init code with a module version and the
172    'way' attached to it.  The version number helps to catch cases
173    where modules are not compiled in dependency order before being
174    linked: if a module has been compiled since any modules which depend on
175    it, then the latter modules will refer to a different version in their
176    init blocks and a link error will ensue.
177
178    The 'way' suffix helps to catch cases where modules compiled in different
179    ways are linked together (eg. profiled and non-profiled).
180
181    We provide a plain, unadorned, version of the module init code
182    which just jumps to the version with the label and way attached.  The
183    reason for this is that when using foreign exports, the caller of
184    startupHaskell() must supply the name of the init function for the "top"
185    module in the program, and we don't want to require that this name
186    has the version and way info appended to it.
187
188 We initialise the module tree by keeping a work-stack, 
189         * pointed to by Sp
190         * that grows downward
191         * Sp points to the last occupied slot
192 -}
193
194 mkModuleInit 
195         :: String               -- the "way"
196         -> CollectedCCs         -- cost centre info
197         -> Module
198         -> Module               -- name of the Main module
199         -> [Module]
200         -> HpcInfo
201         -> FCode ()
202 mkModuleInit way cost_centre_info this_mod main_mod imported_mods hpc_info
203   = do  { -- Allocate the static boolean that records if this
204           -- module has been registered already
205           emitData Data [CmmDataLabel moduleRegdLabel, 
206                          CmmStaticLit zeroCLit]
207
208         ; init_hpc  <- initHpc this_mod hpc_info
209         ; init_prof <- initCostCentres cost_centre_info
210
211           -- We emit a recursive descent module search for all modules
212           -- and *choose* to chase it in :Main, below.
213           -- In this way, Hpc enabled modules can interact seamlessly with
214           -- not Hpc enabled moduled, provided Main is compiled with Hpc.
215
216         ; emitSimpleProc real_init_lbl $ withFreshLabel "ret_block" $ \retId -> catAGraphs
217                 [ check_already_done retId
218                 , init_prof
219                 , init_hpc
220                 , catAGraphs $ map (registerImport way) all_imported_mods
221                 , mkBranch retId ]
222             -- Make the "plain" procedure jump to the "real" init procedure
223         ; emitSimpleProc plain_init_lbl jump_to_init
224
225         -- When compiling the module in which the 'main' function lives,
226         -- (that is, this_mod == main_mod)
227         -- we inject an extra stg_init procedure for stg_init_ZCMain, for the 
228         -- RTS to invoke.  We must consult the -main-is flag in case the
229         -- user specified a different function to Main.main
230  
231         -- Notice that the recursive descent is optional, depending on what options
232         -- are enabled.
233
234
235         ; whenC (this_mod == main_mod)
236                 (emitSimpleProc plain_main_init_lbl rec_descent_init)
237     }
238   where
239     plain_init_lbl = mkPlainModuleInitLabel this_mod
240     real_init_lbl  = mkModuleInitLabel this_mod way
241     plain_main_init_lbl = mkPlainModuleInitLabel rOOT_MAIN
242
243     jump_to_init = mkJump (mkLblExpr real_init_lbl) []
244
245
246     -- Main refers to GHC.TopHandler.runIO, so make sure we call the
247     -- init function for GHC.TopHandler.
248     extra_imported_mods
249         | this_mod == main_mod = [gHC_TOP_HANDLER]
250         | otherwise            = []
251     all_imported_mods = imported_mods ++ extra_imported_mods
252
253     mod_reg_val = CmmLoad (mkLblExpr moduleRegdLabel) bWord
254     check_already_done retId
255      = mkCmmIfThenElse (cmmNeWord (CmmLit zeroCLit) mod_reg_val)
256                        (mkLabel retId Nothing <*> mkReturn []) mkNop
257         <*>     -- Set mod_reg to 1 to record that we've been here
258             mkStore (mkLblExpr moduleRegdLabel) (CmmLit (mkIntCLit 1))
259
260                     -- The return-code pops the work stack by 
261                     -- incrementing Sp, and then jumpd to the popped item
262     ret_code = mkAssign spReg (cmmRegOffW spReg 1)
263                <*> mkJump (CmmLoad (cmmRegOffW spReg (-1)) bWord) []
264
265     rec_descent_init = if opt_SccProfilingOn || isHpcUsed hpc_info
266                        then jump_to_init
267                        else ret_code
268
269 -----------------------
270 registerImport :: String -> Module -> CmmAGraph
271 registerImport way mod
272   | mod == gHC_PRIM
273   = mkNop
274   | otherwise   -- Push the init procedure onto the work stack
275   = mkCmmCall init_lbl [] [] NoC_SRT
276   where
277     init_lbl = mkLblExpr $ mkModuleInitLabel mod way
278
279
280
281 ---------------------------------------------------------------
282 --      Generating static stuff for algebraic data types
283 ---------------------------------------------------------------
284
285 {-      [These comments are rather out of date]
286
287 Macro                        Kind of constructor
288 CONST_INFO_TABLE@       Zero arity (no info -- compiler uses static closure)
289 CHARLIKE_INFO_TABLE     Charlike   (no info -- compiler indexes fixed array)
290 INTLIKE_INFO_TABLE      Intlike; the one macro generates both info tbls
291 SPEC_INFO_TABLE         SPECish, and bigger than or equal to MIN_UPD_SIZE
292 GEN_INFO_TABLE          GENish (hence bigger than or equal to MIN_UPD_SIZE@)
293
294 Possible info tables for constructor con:
295
296 * _con_info:
297   Used for dynamically let(rec)-bound occurrences of
298   the constructor, and for updates.  For constructors
299   which are int-like, char-like or nullary, when GC occurs,
300   the closure tries to get rid of itself.
301
302 * _static_info:
303   Static occurrences of the constructor macro: STATIC_INFO_TABLE.
304
305 For zero-arity constructors, \tr{con}, we NO LONGER generate a static closure;
306 it's place is taken by the top level defn of the constructor.
307
308 For charlike and intlike closures there is a fixed array of static
309 closures predeclared.
310 -}
311
312 cgTyCon :: TyCon -> FCode [CmmZ]  -- All constructors merged together
313 cgTyCon tycon
314   = do  { constrs <- mapM (getCmm . cgDataCon) (tyConDataCons tycon)
315
316             -- Generate a table of static closures for an enumeration type
317             -- Put the table after the data constructor decls, because the
318             -- datatype closure table (for enumeration types)
319             -- to (say) PrelBase_$wTrue_closure, which is defined in code_stuff
320             -- Note that the closure pointers are tagged.
321
322             -- N.B. comment says to put table after constructor decls, but
323             -- code puts it before --- NR 16 Aug 2007
324         ; extra <- cgEnumerationTyCon tycon
325
326         ; return (extra ++ constrs)
327         }
328
329 cgEnumerationTyCon :: TyCon -> FCode [CmmZ]
330 cgEnumerationTyCon tycon
331   | isEnumerationTyCon tycon
332   = do  { tbl <- getCmm $ 
333                  emitRODataLits (mkLocalClosureTableLabel (tyConName tycon) NoCafRefs)
334                    [ CmmLabelOff (mkLocalClosureLabel (dataConName con) NoCafRefs) 
335                                  (tagForCon con)
336                    | con <- tyConDataCons tycon]
337         ; return [tbl] }
338   | otherwise
339   = return []
340
341 cgDataCon :: DataCon -> FCode ()
342 -- Generate the entry code, info tables, and (for niladic constructor)
343 -- the static closure, for a constructor.
344 cgDataCon data_con
345   = do  { let
346             -- To allow the debuggers, interpreters, etc to cope with
347             -- static data structures (ie those built at compile
348             -- time), we take care that info-table contains the
349             -- information we need.
350             (static_cl_info, _) = layOutStaticConstr data_con arg_reps
351             (dyn_cl_info, arg_things) = layOutDynConstr data_con arg_reps
352
353             emit_info cl_info ticky_code
354                 = do { code_blks <- getCode (mk_code ticky_code)
355                      ; emitClosureCodeAndInfoTable cl_info [] code_blks }
356
357             mk_code ticky_code
358               =         -- NB: We don't set CC when entering data (WDP 94/06)
359                 do { ticky_code
360                    ; ldvEnter (CmmReg nodeReg)
361                    ; tickyReturnOldCon (length arg_things)
362                    ; emitReturn [cmmOffsetB (CmmReg nodeReg)
363                                             (tagForCon data_con)] }
364                         -- The case continuation code expects a tagged pointer
365
366             arg_reps :: [(PrimRep, Type)]
367             arg_reps = [(typePrimRep ty, ty) | ty <- dataConRepArgTys data_con]
368
369             -- Dynamic closure code for non-nullary constructors only
370         ; whenC (not (isNullaryRepDataCon data_con))
371                 (emit_info dyn_cl_info tickyEnterDynCon)
372
373                 -- Dynamic-Closure first, to reduce forward references
374         ; emit_info static_cl_info tickyEnterStaticCon }
375
376
377 ---------------------------------------------------------------
378 --      Stuff to support splitting
379 ---------------------------------------------------------------
380
381 -- If we're splitting the object, we need to externalise all the
382 -- top-level names (and then make sure we only use the externalised
383 -- one in any C label we use which refers to this name).
384
385 maybeExternaliseId :: DynFlags -> Id -> FCode Id
386 maybeExternaliseId dflags id
387   | dopt Opt_SplitObjs dflags,  -- Externalise the name for -split-objs
388     isInternalName name = do { mod <- getModuleName
389                              ; returnFC (setIdName id (externalise mod)) }
390   | otherwise           = returnFC id
391   where
392     externalise mod = mkExternalName uniq mod new_occ loc
393     name    = idName id
394     uniq    = nameUnique name
395     new_occ = mkLocalOcc uniq (nameOccName name)
396     loc     = nameSrcSpan name
397         -- We want to conjure up a name that can't clash with any
398         -- existing name.  So we generate
399         --      Mod_$L243foo
400         -- where 243 is the unique.