a649ebd28d9f55658e2e1483b4335b7760f04416
[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(..), dopt )
43 import StaticFlags      ( 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
92                         ++ if opt_SccProfilingOn 
93 #if defined(mingw32_HOST_OS)
94                               || True
95 #endif
96                             then [cmm_init] 
97                             else [])
98                 }
99                 -- Put datatype_stuff after code_stuff, because the
100                 -- datatype closure table (for enumeration types) to
101                 -- (say) PrelBase_True_closure, which is defined in
102                 -- code_stuff
103
104   ; dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms code_stuff)
105
106   ; return code_stuff }
107 \end{code}
108
109 %************************************************************************
110 %*                                                                      *
111 \subsection[codegen-init]{Module initialisation code}
112 %*                                                                      *
113 %************************************************************************
114
115 /* -----------------------------------------------------------------------------
116    Module initialisation
117
118    The module initialisation code looks like this, roughly:
119
120         FN(__stginit_Foo) {
121           JMP_(__stginit_Foo_1_p)
122         }
123
124         FN(__stginit_Foo_1_p) {
125         ...
126         }
127
128    We have one version of the init code with a module version and the
129    'way' attached to it.  The version number helps to catch cases
130    where modules are not compiled in dependency order before being
131    linked: if a module has been compiled since any modules which depend on
132    it, then the latter modules will refer to a different version in their
133    init blocks and a link error will ensue.
134
135    The 'way' suffix helps to catch cases where modules compiled in different
136    ways are linked together (eg. profiled and non-profiled).
137
138    We provide a plain, unadorned, version of the module init code
139    which just jumps to the version with the label and way attached.  The
140    reason for this is that when using foreign exports, the caller of
141    startupHaskell() must supply the name of the init function for the "top"
142    module in the program, and we don't want to require that this name
143    has the version and way info appended to it.
144    --------------------------------------------------------------------------  */
145
146 We initialise the module tree by keeping a work-stack, 
147         * pointed to by Sp
148         * that grows downward
149         * Sp points to the last occupied slot
150
151
152 \begin{code}
153 mkModuleInit 
154         :: DynFlags
155         -> String               -- the "way"
156         -> CollectedCCs         -- cost centre info
157         -> Module
158         -> Maybe String         -- Just m ==> we have flag: -main-is Foo.baz 
159         -> ForeignStubs
160         -> [Module]
161         -> Code
162 mkModuleInit dflags way cost_centre_info this_mod mb_main_mod foreign_stubs imported_mods
163   = do  {       
164
165         -- Allocate the static boolean that records if this
166         -- module has been registered already
167         ; emitData Data [CmmDataLabel moduleRegdLabel, 
168                          CmmStaticLit zeroCLit]
169
170         ; emitSimpleProc real_init_lbl $ do
171             {   -- The return-code pops the work stack by 
172                 -- incrementing Sp, and then jumpd to the popped item
173               ret_blk <- forkLabelledCode $ stmtsC
174                         [ CmmAssign spReg (cmmRegOffW spReg 1)
175                         , CmmJump (CmmLoad (cmmRegOffW spReg (-1)) wordRep) [] ]
176
177             ; init_blk <- forkLabelledCode $ do
178                             { mod_init_code; stmtC (CmmBranch ret_blk) }
179                         
180             ; stmtC (CmmCondBranch (cmmNeWord (CmmLit zeroCLit) mod_reg_val)
181                         ret_blk)
182             ; stmtC (CmmBranch init_blk)            
183             }
184
185
186             -- Make the "plain" procedure jump to the "real" init procedure
187         ; emitSimpleProc plain_init_lbl jump_to_init
188
189         -- When compiling the module in which the 'main' function lives,
190         -- (that is, this_mod == main_mod)
191         -- we inject an extra stg_init procedure for stg_init_ZCMain, for the 
192         -- RTS to invoke.  We must consult the -main-is flag in case the
193         -- user specified a different function to Main.main
194         ; whenC (this_mod == main_mod)
195                 (emitSimpleProc plain_main_init_lbl jump_to_init)
196     }
197   where
198     plain_init_lbl = mkPlainModuleInitLabel dflags this_mod
199     real_init_lbl  = mkModuleInitLabel dflags this_mod way
200     plain_main_init_lbl = mkPlainModuleInitLabel dflags rOOT_MAIN
201
202     jump_to_init = stmtC (CmmJump (mkLblExpr real_init_lbl) [])
203
204     mod_reg_val = CmmLoad (mkLblExpr moduleRegdLabel) wordRep
205
206     main_mod = case mb_main_mod of
207                         Just mod_name -> mkModule mod_name
208                         Nothing       -> mAIN
209
210     -- Main refers to GHC.TopHandler.runIO, so make sure we call the
211     -- init function for GHC.TopHandler.
212     extra_imported_mods
213         | this_mod == main_mod = [pREL_TOP_HANDLER]
214         | otherwise            = []
215
216     mod_init_code = do
217         {       -- Set mod_reg to 1 to record that we've been here
218           stmtC (CmmStore (mkLblExpr moduleRegdLabel) (CmmLit (mkIntCLit 1)))
219
220                 -- Now do local stuff
221 #if defined(mingw32_HOST_OS)
222         ; registerForeignExports foreign_stubs
223 #endif
224         ; initCostCentres cost_centre_info
225         ; mapCs (registerModuleImport dflags way) 
226                 (imported_mods++extra_imported_mods)
227         } 
228
229
230 -----------------------
231 registerModuleImport :: DynFlags -> String -> Module -> Code
232 registerModuleImport dflags way mod 
233   | mod == gHC_PRIM
234   = nopC 
235   | otherwise   -- Push the init procedure onto the work stack
236   = stmtsC [ CmmAssign spReg (cmmRegOffW spReg (-1))
237            , CmmStore (CmmReg spReg) (mkLblExpr (mkModuleInitLabel dflags mod way)) ]
238
239 -----------------------
240 registerForeignExports :: ForeignStubs -> Code
241 registerForeignExports NoStubs 
242   = nopC
243 registerForeignExports (ForeignStubs _ _ _ fe_bndrs)
244   = mapM_ mk_export_register fe_bndrs
245   where
246         mk_export_register bndr
247           = emitRtsCall SLIT("getStablePtr") 
248                 [ (CmmLit (CmmLabel (mkLocalClosureLabel (idName bndr))), 
249                    PtrHint) ]
250 \end{code}
251
252
253
254 Cost-centre profiling: Besides the usual stuff, we must produce
255 declarations for the cost-centres defined in this module;
256
257 (The local cost-centres involved in this are passed into the
258 code-generator.)
259
260 \begin{code}
261 initCostCentres :: CollectedCCs -> Code
262 -- Emit the declarations, and return code to register them
263 initCostCentres (local_CCs, ___extern_CCs, singleton_CCSs)
264   | not opt_SccProfilingOn = nopC
265   | otherwise
266   = do  { mapM_ emitCostCentreDecl       local_CCs
267         ; mapM_ emitCostCentreStackDecl  singleton_CCSs
268         ; mapM_ emitRegisterCC           local_CCs
269         ; mapM_ emitRegisterCCS          singleton_CCSs
270         }
271 \end{code}
272
273 %************************************************************************
274 %*                                                                      *
275 \subsection[codegen-top-bindings]{Converting top-level STG bindings}
276 %*                                                                      *
277 %************************************************************************
278
279 @cgTopBinding@ is only used for top-level bindings, since they need
280 to be allocated statically (not in the heap) and need to be labelled.
281 No unboxed bindings can happen at top level.
282
283 In the code below, the static bindings are accumulated in the
284 @MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
285 This is so that we can write the top level processing in a compositional
286 style, with the increasing static environment being plumbed as a state
287 variable.
288
289 \begin{code}
290 cgTopBinding :: DynFlags -> (StgBinding,[(Id,[Id])]) -> Code
291 cgTopBinding dflags (StgNonRec id rhs, srts)
292   = do  { id' <- maybeExternaliseId dflags id
293         ; mapM_ (mkSRT dflags [id']) srts
294         ; (id,info) <- cgTopRhs id' rhs
295         ; addBindC id info      -- Add the *un-externalised* Id to the envt,
296                                 -- so we find it when we look up occurrences
297         }
298
299 cgTopBinding dflags (StgRec pairs, srts)
300   = do  { let (bndrs, rhss) = unzip pairs
301         ; bndrs' <- mapFCs (maybeExternaliseId dflags) bndrs
302         ; let pairs' = zip bndrs' rhss
303         ; mapM_ (mkSRT dflags bndrs')  srts
304         ; _new_binds <- fixC (\ new_binds -> do 
305                 { addBindsC new_binds
306                 ; mapFCs ( \ (b,e) -> cgTopRhs b e ) pairs' })
307         ; nopC }
308
309 mkSRT :: DynFlags -> [Id] -> (Id,[Id]) -> Code
310 mkSRT dflags these (id,[])  = nopC
311 mkSRT dflags these (id,ids)
312   = do  { ids <- mapFCs remap ids
313         ; id  <- remap id
314         ; emitRODataLits (mkSRTLabel (idName id)) 
315                        (map (CmmLabel . mkClosureLabel dflags . idName) ids)
316         }
317   where
318         -- Sigh, better map all the ids against the environment in 
319         -- case they've been externalised (see maybeExternaliseId below).
320     remap id = case filter (==id) these of
321                 (id':_) -> returnFC id'
322                 [] -> do { info <- getCgIdInfo id; return (cgIdInfoId info) }
323
324 -- Urgh!  I tried moving the forkStatics call from the rhss of cgTopRhs
325 -- to enclose the listFCs in cgTopBinding, but that tickled the
326 -- statics "error" call in initC.  I DON'T UNDERSTAND WHY!
327
328 cgTopRhs :: Id -> StgRhs -> FCode (Id, CgIdInfo)
329         -- The Id is passed along for setting up a binding...
330         -- It's already been externalised if necessary
331
332 cgTopRhs bndr (StgRhsCon cc con args)
333   = forkStatics (cgTopRhsCon bndr con args)
334
335 cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag srt args body)
336   = ASSERT(null fvs)    -- There should be no free variables
337     setSRTLabel (mkSRTLabel (idName bndr)) $ 
338     forkStatics (cgTopRhsClosure bndr cc bi srt upd_flag args body)
339 \end{code}
340
341
342 %************************************************************************
343 %*                                                                      *
344 \subsection{Stuff to support splitting}
345 %*                                                                      *
346 %************************************************************************
347
348 If we're splitting the object, we need to externalise all the top-level names
349 (and then make sure we only use the externalised one in any C label we use
350 which refers to this name).
351
352 \begin{code}
353 maybeExternaliseId :: DynFlags -> Id -> FCode Id
354 maybeExternaliseId dflags id
355   | dopt Opt_SplitObjs dflags,  -- Externalise the name for -split-objs
356     isInternalName name = do { mod <- moduleName
357                              ; returnFC (setIdName id (externalise mod)) }
358   | otherwise           = returnFC id
359   where
360     externalise mod = mkExternalName uniq mod new_occ Nothing loc
361     name    = idName id
362     uniq    = nameUnique name
363     new_occ = mkLocalOcc uniq (nameOccName name)
364     loc     = nameSrcLoc name
365         -- We want to conjure up a name that can't clash with any
366         -- existing name.  So we generate
367         --      Mod_$L243foo
368         -- where 243 is the unique.
369 \end{code}