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