[project @ 2005-03-18 13:37:27 by simonmar]
[ghc-hetmet.git] / ghc / compiler / codeGen / CodeGen.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CodeGen]{@CodeGen@: main module of the code generator}
5
6 This module says how things get going at the top level.
7
8 @codeGen@ is the interface to the outside world.  The \tr{cgTop*}
9 functions drive the mangling of top-level bindings.
10
11 %************************************************************************
12 %*                                                                      *
13 \subsection[codeGen-outside-interface]{The code generator's offering to the world}
14 %*                                                                      *
15 %************************************************************************
16
17 \begin{code}
18 module CodeGen ( codeGen ) where
19
20 #include "HsVersions.h"
21
22 -- Kludge (??) so that CgExpr is reached via at least one non-SOURCE
23 -- import.  Before, that wasn't the case, and CM therefore didn't 
24 -- bother to compile it.
25 import CgExpr           ( {-NOTHING!-} )        -- DO NOT DELETE THIS IMPORT
26 import CgProf
27 import CgMonad
28 import CgBindery        ( CgIdInfo, addBindC, addBindsC, getCgIdInfo,
29                           cgIdInfoId )
30 import CgClosure        ( cgTopRhsClosure )
31 import CgCon            ( cgTopRhsCon, cgTyCon )
32 import CgUtils          ( cmmRegOffW, emitRODataLits, cmmNeWord, emitRtsCall )
33
34 import CLabel
35 import Cmm
36 import CmmUtils         ( zeroCLit, mkIntCLit, mkLblExpr )
37 import PprCmm           ( pprCmms )
38 import MachOp           ( wordRep, MachHint(..) )
39
40 import StgSyn
41 import PrelNames        ( gHC_PRIM, rOOT_MAIN, mAIN, pREL_TOP_HANDLER )
42 import DynFlags         ( DynFlags(..), DynFlag(..) )
43 import StaticFlags      ( opt_SplitObjs, opt_SccProfilingOn )
44
45 import HscTypes         ( ForeignStubs(..), TypeEnv, typeEnvTyCons )
46 import CostCentre       ( CollectedCCs )
47 import Id               ( Id, idName, setIdName )
48 import Name             ( nameSrcLoc, nameOccName, nameUnique, isInternalName, mkExternalName )
49 import OccName          ( mkLocalOcc )
50 import TyCon            ( isDataTyCon )
51 import Module           ( Module, mkModule )
52 import ErrUtils         ( dumpIfSet_dyn, showPass )
53 import Panic            ( assertPanic )
54
55 #ifdef DEBUG
56 import Outputable
57 #endif
58
59 import DATA_IOREF       ( readIORef )
60 \end{code}
61
62 \begin{code}
63 codeGen :: DynFlags
64         -> Module
65         -> TypeEnv
66         -> ForeignStubs
67         -> [Module]             -- directly-imported modules
68         -> CollectedCCs         -- (Local/global) cost-centres needing declaring/registering.
69         -> [(StgBinding,[(Id,[Id])])]   -- Bindings to convert, with SRTs
70         -> IO [Cmm]             -- Output
71
72 codeGen dflags this_mod type_env foreign_stubs imported_mods 
73         cost_centre_info stg_binds
74   = do  
75   { showPass dflags "CodeGen"
76   ; let way = buildTag dflags
77         mb_main_mod = mainModIs dflags
78
79   ; let     tycons      = typeEnvTyCons type_env
80             data_tycons = filter isDataTyCon tycons
81
82 -- Why?
83 --   ; mapM_ (\x -> seq x (return ())) data_tycons
84
85   ; code_stuff <- initC dflags this_mod $ do 
86                 { cmm_binds  <- mapM (getCmm . cgTopBinding dflags) stg_binds
87                 ; cmm_tycons <- mapM cgTyCon data_tycons
88                 ; cmm_init   <- getCmm (mkModuleInit dflags way cost_centre_info 
89                                              this_mod mb_main_mod
90                                              foreign_stubs imported_mods)
91                 ; return (cmm_binds ++ concat cmm_tycons ++ [cmm_init]) 
92                 }
93                 -- Put datatype_stuff after code_stuff, because the
94                 -- datatype closure table (for enumeration types) to
95                 -- (say) PrelBase_True_closure, which is defined in
96                 -- code_stuff
97
98   ; dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms code_stuff)
99
100   ; return code_stuff }
101 \end{code}
102
103 %************************************************************************
104 %*                                                                      *
105 \subsection[codegen-init]{Module initialisation code}
106 %*                                                                      *
107 %************************************************************************
108
109 /* -----------------------------------------------------------------------------
110    Module initialisation
111
112    The module initialisation code looks like this, roughly:
113
114         FN(__stginit_Foo) {
115           JMP_(__stginit_Foo_1_p)
116         }
117
118         FN(__stginit_Foo_1_p) {
119         ...
120         }
121
122    We have one version of the init code with a module version and the
123    'way' attached to it.  The version number helps to catch cases
124    where modules are not compiled in dependency order before being
125    linked: if a module has been compiled since any modules which depend on
126    it, then the latter modules will refer to a different version in their
127    init blocks and a link error will ensue.
128
129    The 'way' suffix helps to catch cases where modules compiled in different
130    ways are linked together (eg. profiled and non-profiled).
131
132    We provide a plain, unadorned, version of the module init code
133    which just jumps to the version with the label and way attached.  The
134    reason for this is that when using foreign exports, the caller of
135    startupHaskell() must supply the name of the init function for the "top"
136    module in the program, and we don't want to require that this name
137    has the version and way info appended to it.
138    -------------------------------------------------------------------------- */
139
140 We initialise the module tree by keeping a work-stack, 
141         * pointed to by Sp
142         * that grows downward
143         * Sp points to the last occupied slot
144
145
146 \begin{code}
147 mkModuleInit 
148         :: DynFlags
149         -> String               -- the "way"
150         -> CollectedCCs         -- cost centre info
151         -> Module
152         -> Maybe String         -- Just m ==> we have flag: -main-is Foo.baz 
153         -> ForeignStubs
154         -> [Module]
155         -> Code
156 mkModuleInit dflags way cost_centre_info this_mod mb_main_mod foreign_stubs imported_mods
157   = do  {       
158
159         -- Allocate the static boolean that records if this
160         -- module has been registered already
161         ; emitData Data [CmmDataLabel moduleRegdLabel, 
162                          CmmStaticLit zeroCLit]
163
164         ; emitSimpleProc real_init_lbl $ do
165             {   -- The return-code pops the work stack by 
166                 -- incrementing Sp, and then jumpd to the popped item
167               ret_blk <- forkLabelledCode $ stmtsC
168                         [ CmmAssign spReg (cmmRegOffW spReg 1)
169                         , CmmJump (CmmLoad (cmmRegOffW spReg (-1)) wordRep) [] ]
170
171             ; init_blk <- forkLabelledCode $ do
172                             { mod_init_code; stmtC (CmmBranch ret_blk) }
173                         
174             ; stmtC (CmmCondBranch (cmmNeWord (CmmLit zeroCLit) mod_reg_val)
175                         ret_blk)
176             ; stmtC (CmmBranch init_blk)            
177             }
178
179
180             -- Make the "plain" procedure jump to the "real" init procedure
181         ; emitSimpleProc plain_init_lbl jump_to_init
182
183         -- When compiling the module in which the 'main' function lives,
184         -- (that is, this_mod == main_mod)
185         -- we inject an extra stg_init procedure for stg_init_ZCMain, for the 
186         -- RTS to invoke.  We must consult the -main-is flag in case the
187         -- user specified a different function to Main.main
188         ; whenC (this_mod == main_mod)
189                 (emitSimpleProc plain_main_init_lbl jump_to_init)
190     }
191   where
192     plain_init_lbl = mkPlainModuleInitLabel dflags this_mod
193     real_init_lbl  = mkModuleInitLabel dflags this_mod way
194     plain_main_init_lbl = mkPlainModuleInitLabel dflags rOOT_MAIN
195
196     jump_to_init = stmtC (CmmJump (mkLblExpr real_init_lbl) [])
197
198     mod_reg_val = CmmLoad (mkLblExpr moduleRegdLabel) wordRep
199
200     main_mod = case mb_main_mod of
201                         Just mod_name -> mkModule mod_name
202                         Nothing       -> mAIN
203
204     -- Main refers to GHC.TopHandler.runIO, so make sure we call the
205     -- init function for GHC.TopHandler.
206     extra_imported_mods
207         | this_mod == main_mod = [pREL_TOP_HANDLER]
208         | otherwise            = []
209
210     mod_init_code = do
211         {       -- Set mod_reg to 1 to record that we've been here
212           stmtC (CmmStore (mkLblExpr moduleRegdLabel) (CmmLit (mkIntCLit 1)))
213
214                 -- Now do local stuff
215         ; registerForeignExports foreign_stubs
216         ; initCostCentres cost_centre_info
217         ; mapCs (registerModuleImport dflags way) 
218                 (imported_mods++extra_imported_mods)
219         } 
220
221
222 -----------------------
223 registerModuleImport :: DynFlags -> String -> Module -> Code
224 registerModuleImport dflags way mod 
225   | mod == gHC_PRIM
226   = nopC 
227   | otherwise   -- Push the init procedure onto the work stack
228   = stmtsC [ CmmAssign spReg (cmmRegOffW spReg (-1))
229            , CmmStore (CmmReg spReg) (mkLblExpr (mkModuleInitLabel dflags mod way)) ]
230
231 -----------------------
232 registerForeignExports :: ForeignStubs -> Code
233 registerForeignExports NoStubs 
234   = nopC
235 registerForeignExports (ForeignStubs _ _ _ fe_bndrs)
236   = mapM_ mk_export_register fe_bndrs
237   where
238         mk_export_register bndr
239           = emitRtsCall SLIT("getStablePtr") 
240                 [ (CmmLit (CmmLabel (mkLocalClosureLabel (idName bndr))), 
241                    PtrHint) ]
242 \end{code}
243
244
245
246 Cost-centre profiling: Besides the usual stuff, we must produce
247 declarations for the cost-centres defined in this module;
248
249 (The local cost-centres involved in this are passed into the
250 code-generator.)
251
252 \begin{code}
253 initCostCentres :: CollectedCCs -> Code
254 -- Emit the declarations, and return code to register them
255 initCostCentres (local_CCs, ___extern_CCs, singleton_CCSs)
256   | not opt_SccProfilingOn = nopC
257   | otherwise
258   = do  { mapM_ emitCostCentreDecl       local_CCs
259         ; mapM_ emitCostCentreStackDecl  singleton_CCSs
260         ; mapM_ emitRegisterCC           local_CCs
261         ; mapM_ emitRegisterCCS          singleton_CCSs
262         }
263 \end{code}
264
265 %************************************************************************
266 %*                                                                      *
267 \subsection[codegen-top-bindings]{Converting top-level STG bindings}
268 %*                                                                      *
269 %************************************************************************
270
271 @cgTopBinding@ is only used for top-level bindings, since they need
272 to be allocated statically (not in the heap) and need to be labelled.
273 No unboxed bindings can happen at top level.
274
275 In the code below, the static bindings are accumulated in the
276 @MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
277 This is so that we can write the top level processing in a compositional
278 style, with the increasing static environment being plumbed as a state
279 variable.
280
281 \begin{code}
282 cgTopBinding :: DynFlags -> (StgBinding,[(Id,[Id])]) -> Code
283 cgTopBinding dflags (StgNonRec id rhs, srts)
284   = do  { id' <- maybeExternaliseId id
285         ; mapM_ (mkSRT dflags [id']) srts
286         ; (id,info) <- cgTopRhs id' rhs
287         ; addBindC id info      -- Add the *un-externalised* Id to the envt,
288                                 -- so we find it when we look up occurrences
289         }
290
291 cgTopBinding dflags (StgRec pairs, srts)
292   = do  { let (bndrs, rhss) = unzip pairs
293         ; bndrs' <- mapFCs maybeExternaliseId bndrs
294         ; let pairs' = zip bndrs' rhss
295         ; mapM_ (mkSRT dflags bndrs')  srts
296         ; _new_binds <- fixC (\ new_binds -> do 
297                 { addBindsC new_binds
298                 ; mapFCs ( \ (b,e) -> cgTopRhs b e ) pairs' })
299         ; nopC }
300
301 mkSRT :: DynFlags -> [Id] -> (Id,[Id]) -> Code
302 mkSRT dflags these (id,[])  = nopC
303 mkSRT dflags these (id,ids)
304   = do  { ids <- mapFCs remap ids
305         ; id  <- remap id
306         ; emitRODataLits (mkSRTLabel (idName id)) 
307                        (map (CmmLabel . mkClosureLabel dflags . idName) ids)
308         }
309   where
310         -- Sigh, better map all the ids against the environment in 
311         -- case they've been externalised (see maybeExternaliseId below).
312     remap id = case filter (==id) these of
313                 (id':_) -> returnFC id'
314                 [] -> do { info <- getCgIdInfo id; return (cgIdInfoId info) }
315
316 -- Urgh!  I tried moving the forkStatics call from the rhss of cgTopRhs
317 -- to enclose the listFCs in cgTopBinding, but that tickled the
318 -- statics "error" call in initC.  I DON'T UNDERSTAND WHY!
319
320 cgTopRhs :: Id -> StgRhs -> FCode (Id, CgIdInfo)
321         -- The Id is passed along for setting up a binding...
322         -- It's already been externalised if necessary
323
324 cgTopRhs bndr (StgRhsCon cc con args)
325   = forkStatics (cgTopRhsCon bndr con args)
326
327 cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag srt args body)
328   = ASSERT(null fvs)    -- There should be no free variables
329     setSRTLabel (mkSRTLabel (idName bndr)) $ 
330     forkStatics (cgTopRhsClosure bndr cc bi srt upd_flag args body)
331 \end{code}
332
333
334 %************************************************************************
335 %*                                                                      *
336 \subsection{Stuff to support splitting}
337 %*                                                                      *
338 %************************************************************************
339
340 If we're splitting the object, we need to externalise all the top-level names
341 (and then make sure we only use the externalised one in any C label we use
342 which refers to this name).
343
344 \begin{code}
345 maybeExternaliseId :: Id -> FCode Id
346 maybeExternaliseId id
347   | opt_SplitObjs,      -- Externalise the name for -split-objs
348     isInternalName name = do { mod <- moduleName
349                              ; returnFC (setIdName id (externalise mod)) }
350   | otherwise           = returnFC id
351   where
352     externalise mod = mkExternalName uniq mod new_occ Nothing loc
353     name    = idName id
354     uniq    = nameUnique name
355     new_occ = mkLocalOcc uniq (nameOccName name)
356     loc     = nameSrcLoc name
357         -- We want to conjure up a name that can't clash with any
358         -- existing name.  So we generate
359         --      Mod_$L243foo
360         -- where 243 is the unique.
361 \end{code}