2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
8 module HscMain ( HscResult(..), hscMain,
12 initPersistentCompilerState ) where
14 #include "HsVersions.h"
17 import ByteCodeGen ( byteCodeGen )
18 import CoreTidy ( tidyCoreExpr )
19 import CorePrep ( corePrepExpr )
20 import Rename ( renameStmt )
21 import RdrHsSyn ( RdrNameStmt )
23 import Id ( Id, idName, setGlobalIdDetails )
24 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
25 import HscTypes ( InteractiveContext(..), TyThing(..) )
26 import PrelNames ( iNTERACTIVE )
27 import StringBuffer ( stringToStringBuffer )
33 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
34 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
36 import Lex ( PState(..), ParseResult(..) )
37 import SrcLoc ( mkSrcLoc )
38 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
39 import Rules ( emptyRuleBase )
40 import PrelInfo ( wiredInThingEnv, wiredInThings )
41 import PrelNames ( vanillaSyntaxMap, knownKeyNames )
42 import MkIface ( mkFinalIface )
44 import InstEnv ( emptyInstEnv )
47 import CoreUtils ( coreBindsSize )
48 import CoreTidy ( tidyCorePgm )
49 import CorePrep ( corePrepPgm )
51 import CoreToStg ( coreToStg )
52 import SimplStg ( stg2stg )
53 import CodeGen ( codeGen )
54 import CodeOutput ( codeOutput )
56 import Module ( ModuleName, moduleName, mkHomeModule,
59 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
60 import Util ( unJust )
61 import UniqSupply ( mkSplitUniqSupply )
63 import Bag ( emptyBag )
66 import CmStaticInfo ( GhciMode(..) )
67 import HscStats ( ppSourceStats )
69 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
70 import OccName ( OccName )
71 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
72 import NameEnv ( emptyNameEnv, mkNameEnv )
73 import Module ( Module, lookupModuleEnvByName )
74 import Maybes ( orElse )
76 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
79 import Maybe ( isJust )
84 %************************************************************************
86 \subsection{The main compiler pipeline}
88 %************************************************************************
93 = HscFail PersistentCompilerState -- updated PCS
94 -- concluded that it wasn't necessary
95 | HscNoRecomp PersistentCompilerState -- updated PCS
96 ModDetails -- new details (HomeSymbolTable additions)
97 ModIface -- new iface (if any compilation was done)
99 | HscRecomp PersistentCompilerState -- updated PCS
100 ModDetails -- new details (HomeSymbolTable additions)
101 ModIface -- new iface (if any compilation was done)
102 Bool -- stub_h exists
103 Bool -- stub_c exists
104 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
107 -- no errors or warnings; the individual passes
108 -- (parse/rename/typecheck) print messages themselves
114 -> ModuleLocation -- location info
115 -> Bool -- True <=> source unchanged
116 -> Bool -- True <=> have an object file (for msgs only)
117 -> Maybe ModIface -- old interface, if available
118 -> HomeSymbolTable -- for home module ModDetails
120 -> PersistentCompilerState -- IN: persistent compiler state
123 hscMain ghci_mode dflags mod location source_unchanged have_object
124 maybe_old_iface hst hit pcs
126 showPass dflags ("Checking old interface for hs = "
127 ++ show (ml_hs_file location)
128 ++ ", hspp = " ++ show (ml_hspp_file location));
130 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
131 <- checkOldIface ghci_mode dflags hit hst pcs
132 (unJust "hscMain" (ml_hi_file location))
133 source_unchanged maybe_old_iface;
136 return (HscFail pcs_ch)
139 let no_old_iface = not (isJust maybe_checked_iface)
140 what_next | recomp_reqd || no_old_iface = hscRecomp
141 | otherwise = hscNoRecomp
143 what_next ghci_mode dflags have_object mod location
144 maybe_checked_iface hst hit pcs_ch
148 -- we definitely expect to have the old interface available
149 hscNoRecomp ghci_mode dflags have_object
150 mod location (Just old_iface) hst hit pcs_ch
151 | ghci_mode == OneShot
153 hPutStrLn stderr "compilation IS NOT required";
154 let { bomb = panic "hscNoRecomp:OneShot" };
155 return (HscNoRecomp pcs_ch bomb bomb)
159 when (verbosity dflags >= 1) $
160 hPutStrLn stderr ("Skipping " ++
161 compMsg have_object mod location);
164 (pcs_cl, closure_errs, cl_hs_decls)
165 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
167 return (HscFail pcs_cl)
172 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
174 case maybe_tc_result of {
175 Nothing -> return (HscFail pcs_cl);
176 Just (pcs_tc, new_details) ->
178 return (HscNoRecomp pcs_tc new_details old_iface)
181 compMsg use_object mod location =
182 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
183 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
185 then unJust "hscRecomp" (ml_obj_file location)
188 where mod_str = moduleUserString mod
191 hscRecomp ghci_mode dflags have_object
192 mod location maybe_checked_iface hst hit pcs_ch
194 -- what target are we shooting for?
195 ; let toInterp = dopt_HscLang dflags == HscInterpreted
197 ; when (verbosity dflags >= 1) $
198 hPutStrLn stderr ("Compiling " ++
199 compMsg (not toInterp) mod location);
204 ; maybe_parsed <- myParseModule dflags
205 (unJust "hscRecomp:hspp" (ml_hspp_file location))
206 ; case maybe_parsed of {
207 Nothing -> return (HscFail pcs_ch);
208 Just rdr_module -> do {
209 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
214 ; (pcs_rn, print_unqualified, maybe_rn_result)
216 renameModule dflags hit hst pcs_ch this_mod rdr_module
217 ; case maybe_rn_result of {
218 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
219 Just (is_exported, new_iface, rn_hs_decls) -> do {
221 -- In interactive mode, we don't want to discard any top-level entities at
222 -- all (eg. do not inline them away during simplification), and retain them
223 -- all in the TypeEnv so they are available from the command line.
225 -- isGlobalName separates the user-defined top-level names from those
226 -- introduced by the type checker.
227 ; let dont_discard | ghci_mode == Interactive = isGlobalName
228 | otherwise = is_exported
234 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
235 print_unqualified rn_hs_decls
236 ; case maybe_tc_result of {
237 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
238 Just (pcs_tc, tc_result) -> do {
243 ; (ds_details, foreign_stuff)
245 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
252 core2core dflags pcs_tc hst dont_discard ds_details
257 ; cg_info_ref <- newIORef Nothing ;
258 ; let cg_info :: CgInfoEnv
259 cg_info = unsafePerformIO $ do {
260 maybe_cg_env <- readIORef cg_info_ref ;
262 Just env -> return env
263 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
264 return emptyNameEnv } }
265 -- cg_info_ref will be filled in just after restOfCodeGeneration
266 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
268 ; (pcs_simpl, tidy_details)
269 <- tidyCorePgm dflags this_mod pcs_tc cg_info simpl_details
272 -- PREPARE FOR CODE GENERATION
274 -- Do saturation and convert to A-normal form
275 ; prepd_details <- corePrepPgm dflags tidy_details
278 -- CONVERT TO STG and COMPLETE CODE GENERATION
281 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
283 local_tycons = typeEnvTyCons env_tc
284 local_classes = typeEnvClasses env_tc
286 imported_module_names = map ideclName (hsModuleImports rdr_module)
287 imported_modules = map mod_name_to_Module imported_module_names
289 (h_code,c_code,fe_binders) = foreign_stuff
291 pit = pcs_PIT pcs_simpl
293 mod_name_to_Module :: ModuleName -> Module
294 mod_name_to_Module nm
295 = let str_mi = lookupModuleEnvByName hit nm `orElse`
296 lookupModuleEnvByName pit nm `orElse`
297 pprPanic "mod_name_to_Module: no hst or pst mapping for"
301 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
304 ----------------- Generate byte code ------------------
305 (bcos,itbl_env) <- byteCodeGen dflags binds
306 local_tycons local_classes
308 -- Fill in the code-gen info
309 writeIORef cg_info_ref (Just emptyNameEnv)
311 ------------------ BUILD THE NEW ModIface ------------
312 final_iface <- _scc_ "MkFinalIface"
313 mkFinalIface ghci_mode dflags location
314 maybe_checked_iface new_iface tidy_details
316 return ( False, False, Just (bcos,itbl_env), final_iface )
319 ----------------- Convert to STG ------------------
320 (stg_binds, cost_centre_info, stg_back_end_info)
322 myCoreToStg dflags this_mod binds
324 -- Fill in the code-gen info for the earlier tidyCorePgm
325 writeIORef cg_info_ref (Just stg_back_end_info)
327 ------------------ BUILD THE NEW ModIface ------------
328 final_iface <- _scc_ "MkFinalIface"
329 mkFinalIface ghci_mode dflags location
330 maybe_checked_iface new_iface tidy_details
332 ------------------ Code generation ------------------
333 abstractC <- _scc_ "CodeGen"
334 codeGen dflags this_mod imported_modules
335 cost_centre_info fe_binders
336 local_tycons stg_binds
338 ------------------ Code output -----------------------
339 (stub_h_exists, stub_c_exists)
340 <- codeOutput dflags this_mod local_tycons
342 c_code h_code abstractC
344 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
346 ; let final_details = tidy_details {md_binds = []}
349 -- and the answer is ...
350 ; return (HscRecomp pcs_simpl
353 stub_h_exists stub_c_exists
357 myParseModule dflags src_filename
358 = do -------------------------- Parser ----------------
359 showPass dflags "Parser"
362 buf <- hGetStringBuffer True{-expand tabs-} src_filename
364 let glaexts | dopt Opt_GlasgowExts dflags = 1#
367 case parseModule buf PState{ bol = 0#, atbol = 1#,
368 context = [], glasgow_exts = glaexts,
369 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
371 PFailed err -> do { hPutStrLn stderr (showSDoc err);
372 freeStringBuffer buf;
375 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
377 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
379 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
380 (ppSourceStats False rdr_module) ;
382 return (Just rdr_module)
383 -- ToDo: free the string buffer later.
387 myCoreToStg dflags this_mod tidy_binds
389 () <- coreBindsSize tidy_binds `seq` return ()
390 -- TEMP: the above call zaps some space usage allocated by the
391 -- simplifier, which for reasons I don't understand, persists
392 -- thoroughout code generation
394 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
396 (stg_binds2, cost_centre_info)
397 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
399 let env_rhs :: CgInfoEnv
400 env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
401 | (bind,_) <- stg_binds2,
403 | stgBindHasCafRefs bind = MayHaveCafRefs
404 | otherwise = NoCafRefs,
405 (bndr,rhs) <- stgBindPairs bind ]
407 return (stg_binds2, cost_centre_info, env_rhs)
409 stgBindPairs (StgNonRec _ b r) = [(b,r)]
410 stgBindPairs (StgRec _ prs) = prs
414 %************************************************************************
416 \subsection{Compiling a do-statement}
418 %************************************************************************
426 -> PersistentCompilerState -- IN: persistent compiler state
427 -> InteractiveContext -- Context for compiling
428 -> String -- The statement
429 -> Bool -- just treat it as an expression
430 -> IO ( PersistentCompilerState,
436 When the UnlinkedBCOExpr is linked you get an HValue of type
438 When you run it you get a list of HValues that should be
439 the same length as the list of names; add them to the ClosureEnv.
441 A naked expression returns a singleton Name [it].
443 What you type The IO [HValue] that hscStmt returns
444 ------------- ------------------------------------
445 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
448 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
451 expr (of IO type) ==> expr >>= \ v -> return [v]
452 [NB: result not printed] bindings: [it]
455 expr (of non-IO type,
456 result showable) ==> let v = expr in print v >> return [v]
459 expr (of non-IO type,
460 result not showable) ==> error
463 hscStmt dflags hst hit pcs0 icontext stmt just_expr
467 ic_type_env = type_env,
468 ic_module = scope_mod } = icontext
470 do { maybe_stmt <- hscParseStmt dflags stmt
472 Nothing -> return (pcs0, Nothing)
473 Just parsed_stmt -> do {
475 let { notExprStmt (ExprStmt _ _) = False;
479 if (just_expr && notExprStmt parsed_stmt)
480 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
481 return (pcs0, Nothing)
485 (pcs1, print_unqual, maybe_renamed_stmt)
486 <- renameStmt dflags hit hst pcs0 scope_mod
487 iNTERACTIVE rn_env parsed_stmt
489 ; case maybe_renamed_stmt of
490 Nothing -> return (pcs0, Nothing)
491 Just (bound_names, rn_stmt) -> do {
496 then case rn_stmt of { (syn, ExprStmt e _, decls) ->
497 typecheckExpr dflags pcs1 hst type_env
498 print_unqual iNTERACTIVE (syn,e,decls) }
499 else typecheckStmt dflags pcs1 hst type_env
500 print_unqual iNTERACTIVE bound_names rn_stmt
502 ; case maybe_tc_return of
503 Nothing -> return (pcs0, Nothing)
504 Just (pcs2, tc_expr, bound_ids, ty) -> do {
507 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
510 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
512 -- Tidy it (temporary, until coreSat does cloning)
513 ; tidy_expr <- tidyCoreExpr simpl_expr
515 -- Prepare for codegen
516 ; prepd_expr <- corePrepExpr dflags tidy_expr
519 ; bcos <- coreExprToBCOs dflags prepd_expr
522 -- Make all the bound ids "global" ids, now that
523 -- they're notionally top-level bindings. This is
524 -- important: otherwise when we come to compile an expression
525 -- using these ids later, the byte code generator will consider
526 -- the occurrences to be free rather than global.
527 global_bound_ids = map globaliseId bound_ids;
528 globaliseId id = setGlobalIdDetails id VanillaGlobal
530 ; return (pcs2, Just (global_bound_ids, ty, bcos))
534 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
535 hscParseStmt dflags str
536 = do -------------------------- Parser ----------------
537 showPass dflags "Parser"
540 buf <- stringToStringBuffer str
542 let glaexts | dopt Opt_GlasgowExts dflags = 1#
545 case parseStmt buf PState{ bol = 0#, atbol = 1#,
546 context = [], glasgow_exts = glaexts,
547 loc = mkSrcLoc SLIT("<no file>") 0 } of {
549 PFailed err -> do { hPutStrLn stderr (showSDoc err);
550 -- Not yet implemented in <4.11 freeStringBuffer buf;
553 -- no stmt: the line consisted of just space or comments
554 POk _ Nothing -> return Nothing;
556 POk _ (Just rdr_stmt) -> do {
558 --ToDo: can't free the string buffer until we've finished this
559 -- compilation sweep and all the identifiers have gone away.
560 --freeStringBuffer buf;
561 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
562 return (Just rdr_stmt)
567 %************************************************************************
569 \subsection{Initial persistent state}
571 %************************************************************************
574 initPersistentCompilerState :: IO PersistentCompilerState
575 initPersistentCompilerState
576 = do prs <- initPersistentRenamerState
578 PCS { pcs_PIT = emptyIfaceTable,
579 pcs_PTE = wiredInThingEnv,
580 pcs_insts = emptyInstEnv,
581 pcs_rules = emptyRuleBase,
586 initPersistentRenamerState :: IO PersistentRenamerState
587 = do us <- mkSplitUniqSupply 'r'
589 PRS { prsOrig = NameSupply { nsUniqs = us,
590 nsNames = initOrigNames,
592 prsDecls = (emptyNameEnv, 0),
593 prsInsts = (emptyBag, 0),
594 prsRules = (emptyBag, 0),
599 initOrigNames :: FiniteMap (ModuleName,OccName) Name
601 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
603 grab names = foldl add emptyFM names
605 = addToFM env (moduleName (nameModule name), nameOccName name) name
608 initRules :: PackageRuleBase
609 initRules = emptyRuleBase
611 foldl add emptyVarEnv builtinRules
614 = extendRuleBase env name rule