2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
12 , hscNormalIface, hscWriteIface, hscGenHardCode
14 , hscStmt, hscTcExpr, hscKcType
17 , hscCompileOneShot -- :: Compiler HscStatus
18 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
19 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
20 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
22 , InteractiveStatus, NothingStatus, OneShotStatus, BatchStatus
34 import CodeOutput ( outputForeignStubs )
35 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
36 import Linker ( HValue, linkExpr )
37 import CoreTidy ( tidyExpr )
38 import CorePrep ( corePrepExpr )
39 import Desugar ( deSugarExpr )
40 import SimplCore ( simplifyExpr )
41 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
43 import PrelNames ( iNTERACTIVE )
44 import {- Kind parts of -} Type ( Kind )
45 import CoreLint ( lintUnfolding )
46 import DsMeta ( templateHaskellNames )
47 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan, noSrcSpan )
49 import VarEnv ( emptyTidyEnv )
53 import Module ( emptyModuleEnv, ModLocation(..), Module )
57 import SrcLoc ( Located(..) )
61 import SrcLoc ( mkSrcLoc )
62 import TcRnDriver ( tcRnModule )
63 import TcIface ( typecheckIface )
64 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
65 import IfaceEnv ( initNameCache )
66 import LoadIface ( ifaceStats, initExternalPackageState )
67 import PrelInfo ( wiredInThings, basicKnownKeyNames )
69 import Desugar ( deSugar )
70 import SimplCore ( core2core )
72 import CorePrep ( corePrepPgm )
73 import CoreToStg ( coreToStg )
74 import qualified StgCmm ( codeGen )
77 import TyCon ( TyCon, isDataTyCon )
78 import Name ( Name, NamedThing(..) )
79 import SimplStg ( stg2stg )
80 import CodeGen ( codeGen )
82 import PprCmm ( pprCmms )
83 import CmmParse ( parseCmmFile )
87 import OptimizationFuel ( initOptFuelState )
91 import CodeOutput ( codeOutput )
92 import NameEnv ( emptyNameEnv )
93 import Fingerprint ( Fingerprint )
97 import UniqSupply ( mkSplitUniqSupply )
100 import HscStats ( ppSourceStats )
102 import MkExternalCore ( emitExternalCore )
104 import LazyUniqFM ( emptyUFM )
105 import UniqSupply ( initUs_ )
106 import Bag ( unitBag )
114 #include "HsVersions.h"
117 %************************************************************************
121 %************************************************************************
124 newHscEnv :: DynFlags -> IO HscEnv
126 = do { eps_var <- newIORef initExternalPackageState
127 ; us <- mkSplitUniqSupply 'r'
128 ; nc_var <- newIORef (initNameCache us knownKeyNames)
129 ; fc_var <- newIORef emptyUFM
130 ; mlc_var <- newIORef emptyModuleEnv
131 ; optFuel <- initOptFuelState
132 ; return (HscEnv { hsc_dflags = dflags,
135 hsc_IC = emptyInteractiveContext,
136 hsc_HPT = emptyHomePackageTable,
141 hsc_OptFuel = optFuel,
142 hsc_type_env_var = Nothing,
143 hsc_global_rdr_env = emptyGlobalRdrEnv,
144 hsc_global_type_env = emptyNameEnv } ) }
147 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
148 -- where templateHaskellNames are defined
149 knownKeyNames = map getName wiredInThings
150 ++ basicKnownKeyNames
152 ++ templateHaskellNames
158 -- | parse a file, returning the abstract syntax
159 hscParse :: GhcMonad m =>
161 -> m (Located (HsModule RdrName))
162 hscParse mod_summary = do
163 hsc_env <- getSession
164 let dflags = hsc_dflags hsc_env
165 src_filename = ms_hspp_file mod_summary
166 maybe_src_buf = ms_hspp_buf mod_summary
167 -------------------------- Parser ----------------
168 liftIO $ showPass dflags "Parser"
169 {-# SCC "Parser" #-} do
171 -- sometimes we already have the buffer in memory, perhaps
172 -- because we needed to parse the imports out of it, or get the
174 buf <- case maybe_src_buf of
176 Nothing -> liftIO $ hGetStringBuffer src_filename
178 let loc = mkSrcLoc (mkFastString src_filename) 1 0
180 case unP parseModule (mkPState buf loc dflags) of
182 throwOneError (mkPlainErrMsg span err)
184 POk pst rdr_module -> do
185 let ms@(warns,errs) = getMessages pst
187 if errorsFound dflags ms then
188 liftIO $ throwIO $ mkSrcErr errs
190 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
191 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
192 (ppSourceStats False rdr_module) ;
194 -- ToDo: free the string buffer later.
196 -- | Rename and typecheck a module
197 hscTypecheck :: GhcMonad m =>
198 ModSummary -> Located (HsModule RdrName)
200 hscTypecheck mod_summary rdr_module = do
201 hsc_env <- getSession
202 r <- {-# SCC "Typecheck-Rename" #-}
203 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
206 -- XXX: should this really be a Maybe X? Check under which circumstances this
207 -- can become a Nothing and decide whether this should instead throw an
208 -- exception/signal an error.
210 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
211 Maybe (HsDoc Name), HaddockModInfo Name))
213 -- | Rename and typecheck a module, additionally returning the renamed syntax
214 hscTypecheckRename ::
216 ModSummary -> Located (HsModule RdrName)
217 -> m (TcGblEnv, RenamedStuff)
218 hscTypecheckRename mod_summary rdr_module = do
219 hsc_env <- getSession
221 <- {-# SCC "Typecheck-Rename" #-}
222 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
224 let rn_info = do decl <- tcg_rn_decls tc_result
225 imports <- tcg_rn_imports tc_result
226 let exports = tcg_rn_exports tc_result
227 let doc = tcg_doc tc_result
228 let hmi = tcg_hmi tc_result
229 return (decl,imports,exports,doc,hmi)
231 return (tc_result, rn_info)
233 -- | Convert a typechecked module to Core
234 hscDesugar :: GhcMonad m => ModSummary -> TcGblEnv -> m ModGuts
235 hscDesugar mod_summary tc_result =
236 withSession $ \hsc_env ->
237 ioMsgMaybe $ deSugar hsc_env (ms_location mod_summary) tc_result
239 -- | Make a 'ModIface' from the results of typechecking. Used when
240 -- not optimising, and the interface doesn't need to contain any
241 -- unfoldings or other cross-module optimisation info.
242 -- ToDo: the old interface is only needed to get the version numbers,
243 -- we should use fingerprint versions instead.
244 makeSimpleIface :: GhcMonad m =>
245 Maybe ModIface -> TcGblEnv -> ModDetails
247 makeSimpleIface maybe_old_iface tc_result details =
248 withSession $ \hsc_env ->
249 ioMsgMaybe $ mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
251 -- | Make a 'ModDetails' from the results of typechecking. Used when
252 -- typechecking only, as opposed to full compilation.
253 makeSimpleDetails :: GhcMonad m => TcGblEnv -> m ModDetails
254 makeSimpleDetails tc_result =
255 withSession $ \hsc_env -> liftIO $ mkBootModDetailsTc hsc_env tc_result
258 %************************************************************************
260 The main compiler pipeline
262 %************************************************************************
264 --------------------------------
265 The compilation proper
266 --------------------------------
269 It's the task of the compilation proper to compile Haskell, hs-boot and
270 core files to either byte-code, hard-code (C, asm, Java, ect) or to
271 nothing at all (the module is still parsed and type-checked. This
272 feature is mostly used by IDE's and the likes).
273 Compilation can happen in either 'one-shot', 'batch', 'nothing',
274 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
275 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
277 The modes are kept separate because of their different types and meanings.
278 In 'one-shot' mode, we're only compiling a single file and can therefore
279 discard the new ModIface and ModDetails. This is also the reason it only
280 targets hard-code; compiling to byte-code or nothing doesn't make sense
281 when we discard the result.
282 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
283 and ModDetails. 'Batch' mode doesn't target byte-code since that require
284 us to return the newly compiled byte-code.
285 'Nothing' mode has exactly the same type as 'batch' mode but they're still
286 kept separate. This is because compiling to nothing is fairly special: We
287 don't output any interface files, we don't run the simplifier and we don't
289 'Interactive' mode is similar to 'batch' mode except that we return the
290 compiled byte-code together with the ModIface and ModDetails.
292 Trying to compile a hs-boot file to byte-code will result in a run-time
293 error. This is the only thing that isn't caught by the type-system.
297 -- Status of a compilation to hard-code or nothing.
301 Bool -- Has stub files. This is a hack. We can't compile C files here
302 -- since it's done in DriverPipeline. For now we just return True
303 -- if we want the caller to compile them for us.
306 -- This is a bit ugly. Since we use a typeclass below and would like to avoid
307 -- functional dependencies, we have to parameterise the typeclass over the
308 -- result type. Therefore we need to artificially distinguish some types. We
309 -- do this by adding type tags which will simply be ignored by the caller.
310 data HscOneShotTag = HscOneShotTag
311 data HscNothingTag = HscNothingTag
313 type OneShotStatus = HscStatus' HscOneShotTag
314 type BatchStatus = HscStatus' ()
315 type InteractiveStatus = HscStatus' (CompiledByteCode, ModBreaks)
316 type NothingStatus = HscStatus' HscNothingTag
318 type OneShotResult = OneShotStatus
319 type BatchResult = (BatchStatus, ModIface, ModDetails)
320 type NothingResult = (NothingStatus, ModIface, ModDetails)
321 type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
323 -- FIXME: The old interface and module index are only using in 'batch' and
324 -- 'interactive' mode. They should be removed from 'oneshot' mode.
325 type Compiler result = GhcMonad m =>
328 -> Bool -- True <=> source unchanged
329 -> Maybe ModIface -- Old interface, if available
330 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
333 class HsCompiler a where
334 -- | The main interface.
335 hscCompile :: GhcMonad m =>
336 HscEnv -> ModSummary -> Bool
337 -> Maybe ModIface -> Maybe (Int, Int)
340 -- | Called when no recompilation is necessary.
341 hscNoRecomp :: GhcMonad m =>
344 -- | Called to recompile the module.
345 hscRecompile :: GhcMonad m =>
346 ModSummary -> Maybe Fingerprint -> m a
348 -- | Code generation for Boot modules.
349 hscGenBootOutput :: GhcMonad m =>
350 TcGblEnv -> ModSummary -> Maybe Fingerprint -> m a
352 -- | Code generation for normal modules.
353 hscGenOutput :: GhcMonad m =>
354 ModGuts -> ModSummary -> Maybe Fingerprint -> m a
357 genericHscCompile :: (HsCompiler a, GhcMonad m) =>
358 (Maybe (Int,Int) -> Bool -> ModSummary -> m ())
359 -> HscEnv -> ModSummary -> Bool
360 -> Maybe ModIface -> Maybe (Int, Int)
362 genericHscCompile hscMessage
363 hsc_env mod_summary source_unchanged
364 mb_old_iface0 mb_mod_index =
365 withTempSession (\_ -> hsc_env) $ do
366 (recomp_reqd, mb_checked_iface)
367 <- {-# SCC "checkOldIface" #-}
368 liftIO $ checkOldIface hsc_env mod_summary
369 source_unchanged mb_old_iface0
370 -- save the interface that comes back from checkOldIface.
371 -- In one-shot mode we don't have the old iface until this
372 -- point, when checkOldIface reads it from the disk.
373 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
374 case mb_checked_iface of
375 Just iface | not recomp_reqd
376 -> do hscMessage mb_mod_index False mod_summary
379 -> do hscMessage mb_mod_index True mod_summary
380 hscRecompile mod_summary mb_old_hash
382 genericHscRecompile :: (HsCompiler a, GhcMonad m) =>
383 ModSummary -> Maybe Fingerprint
385 genericHscRecompile mod_summary mb_old_hash
386 | ExtCoreFile <- ms_hsc_src mod_summary =
387 panic "GHC does not currently support reading External Core files"
389 tc_result <- hscFileFrontEnd mod_summary
390 case ms_hsc_src mod_summary of
392 hscGenBootOutput tc_result mod_summary mb_old_hash
394 guts <- hscDesugar mod_summary tc_result
395 hscGenOutput guts mod_summary mb_old_hash
397 --------------------------------------------------------------
399 --------------------------------------------------------------
401 instance HsCompiler OneShotResult where
403 hscCompile hsc_env mod_summary src_changed mb_old_iface mb_i_of_n = do
404 -- One-shot mode needs a knot-tying mutable variable for interface files.
405 -- See TcRnTypes.TcGblEnv.tcg_type_env_var.
406 type_env_var <- liftIO $ newIORef emptyNameEnv
408 mod = ms_mod mod_summary
409 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
411 genericHscCompile oneShotMsg hsc_env' mod_summary src_changed
412 mb_old_iface mb_i_of_n
414 hscNoRecomp _old_iface = do
415 withSession (liftIO . dumpIfaceStats)
418 hscRecompile = genericHscRecompile
420 hscGenBootOutput tc_result mod_summary mb_old_iface = do
421 (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
422 hscWriteIface iface changed mod_summary
423 return (HscRecomp False HscOneShotTag)
425 hscGenOutput guts0 mod_summary mb_old_iface = do
426 guts <- hscSimplify guts0
427 (iface, changed, _details, cgguts)
428 <- hscNormalIface guts mb_old_iface
429 hscWriteIface iface changed mod_summary
430 hasStub <- hscGenHardCode cgguts mod_summary
431 return (HscRecomp hasStub HscOneShotTag)
433 -- Compile Haskell, boot and extCore in OneShot mode.
434 hscCompileOneShot :: Compiler OneShotStatus
435 hscCompileOneShot = hscCompile
437 --------------------------------------------------------------
439 instance HsCompiler BatchResult where
441 hscCompile = genericHscCompile batchMsg
443 hscNoRecomp iface = do
444 details <- genModDetails iface
445 return (HscNoRecomp, iface, details)
447 hscRecompile = genericHscRecompile
449 hscGenBootOutput tc_result mod_summary mb_old_iface = do
450 (iface, changed, details)
451 <- hscSimpleIface tc_result mb_old_iface
452 hscWriteIface iface changed mod_summary
453 return (HscRecomp False (), iface, details)
455 hscGenOutput guts0 mod_summary mb_old_iface = do
456 guts <- hscSimplify guts0
457 (iface, changed, details, cgguts)
458 <- hscNormalIface guts mb_old_iface
459 hscWriteIface iface changed mod_summary
460 hasStub <- hscGenHardCode cgguts mod_summary
461 return (HscRecomp hasStub (), iface, details)
463 -- Compile Haskell, boot and extCore in batch mode.
464 hscCompileBatch :: Compiler (BatchStatus, ModIface, ModDetails)
465 hscCompileBatch = hscCompile
467 --------------------------------------------------------------
469 instance HsCompiler InteractiveResult where
471 hscCompile = genericHscCompile batchMsg
473 hscNoRecomp iface = do
474 details <- genModDetails iface
475 return (HscNoRecomp, iface, details)
477 hscRecompile = genericHscRecompile
479 hscGenBootOutput _ _ _ = panic "hscCompileInteractive: HsBootFile"
481 hscGenOutput guts0 mod_summary mb_old_iface = do
482 guts <- hscSimplify guts0
483 (iface, _changed, details, cgguts)
484 <- hscNormalIface guts mb_old_iface
485 hscInteractive (iface, details, cgguts) mod_summary
487 -- Compile Haskell, extCore to bytecode.
488 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
489 hscCompileInteractive = hscCompile
491 --------------------------------------------------------------
493 instance HsCompiler NothingResult where
495 hscCompile = genericHscCompile batchMsg
497 hscNoRecomp iface = do
498 details <- genModDetails iface
499 return (HscNoRecomp, iface, details)
501 hscRecompile mod_summary mb_old_hash
502 | ExtCoreFile <- ms_hsc_src mod_summary =
503 panic "hscCompileNothing: cannot do external core"
505 tc_result <- hscFileFrontEnd mod_summary
506 hscGenBootOutput tc_result mod_summary mb_old_hash
508 hscGenBootOutput tc_result _mod_summary mb_old_iface = do
509 (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
510 return (HscRecomp False HscNothingTag, iface, details)
513 panic "hscCompileNothing: hscGenOutput should not be called"
515 -- Type-check Haskell and .hs-boot only (no external core)
516 hscCompileNothing :: Compiler (NothingStatus, ModIface, ModDetails)
517 hscCompileNothing = hscCompile
519 --------------------------------------------------------------
521 --------------------------------------------------------------
523 genModDetails :: GhcMonad m => ModIface -> m ModDetails
524 genModDetails old_iface =
525 withSession $ \hsc_env -> liftIO $ do
526 new_details <- {-# SCC "tcRnIface" #-}
527 initIfaceCheck hsc_env $
528 typecheckIface old_iface
529 dumpIfaceStats hsc_env
532 --------------------------------------------------------------
533 -- Progress displayers.
534 --------------------------------------------------------------
536 oneShotMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
537 oneShotMsg _mb_mod_index recomp _mod_summary
538 = do hsc_env <- getSession
542 else compilationProgressMsg (hsc_dflags hsc_env) $
543 "compilation IS NOT required"
545 batchMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
546 batchMsg mb_mod_index recomp mod_summary
547 = do hsc_env <- getSession
548 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
549 (showModuleIndex mb_mod_index ++
550 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
553 then showMsg "Compiling "
554 else if verbosity (hsc_dflags hsc_env) >= 2
555 then showMsg "Skipping "
558 --------------------------------------------------------------
560 --------------------------------------------------------------
561 hscFileFrontEnd :: GhcMonad m => ModSummary -> m TcGblEnv
562 hscFileFrontEnd mod_summary =
563 do rdr_module <- hscParse mod_summary
564 hscTypecheck mod_summary rdr_module
566 --------------------------------------------------------------
568 --------------------------------------------------------------
570 hscSimplify :: GhcMonad m => ModGuts -> m ModGuts
571 hscSimplify ds_result
572 = do hsc_env <- getSession
573 simpl_result <- {-# SCC "Core2Core" #-}
574 liftIO $ core2core hsc_env ds_result
577 --------------------------------------------------------------
578 -- Interface generators
579 --------------------------------------------------------------
581 hscSimpleIface :: GhcMonad m =>
584 -> m (ModIface, Bool, ModDetails)
585 hscSimpleIface tc_result mb_old_iface
586 = do hsc_env <- getSession
587 details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
588 (new_iface, no_change)
589 <- {-# SCC "MkFinalIface" #-}
590 ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface details tc_result
591 -- And the answer is ...
592 liftIO $ dumpIfaceStats hsc_env
593 return (new_iface, no_change, details)
595 hscNormalIface :: GhcMonad m =>
598 -> m (ModIface, Bool, ModDetails, CgGuts)
599 hscNormalIface simpl_result mb_old_iface
600 = do hsc_env <- getSession
602 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
603 liftIO $ tidyProgram hsc_env simpl_result
605 -- BUILD THE NEW ModIface and ModDetails
606 -- and emit external core if necessary
607 -- This has to happen *after* code gen so that the back-end
608 -- info has been set. Not yet clear if it matters waiting
609 -- until after code output
610 (new_iface, no_change)
611 <- {-# SCC "MkFinalIface" #-}
612 ioMsgMaybe $ mkIface hsc_env mb_old_iface
614 -- Emit external core
615 -- This should definitely be here and not after CorePrep,
616 -- because CorePrep produces unqualified constructor wrapper declarations,
617 -- so its output isn't valid External Core (without some preprocessing).
618 liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
619 liftIO $ dumpIfaceStats hsc_env
621 -- Return the prepared code.
622 return (new_iface, no_change, details, cg_guts)
624 --------------------------------------------------------------
625 -- BackEnd combinators
626 --------------------------------------------------------------
628 hscWriteIface :: GhcMonad m =>
632 hscWriteIface iface no_change mod_summary
633 = do hsc_env <- getSession
634 let dflags = hsc_dflags hsc_env
637 $ writeIfaceFile dflags (ms_location mod_summary) iface
639 -- | Compile to hard-code.
640 hscGenHardCode :: GhcMonad m =>
642 -> m Bool -- ^ @True@ <=> stub.c exists
643 hscGenHardCode cgguts mod_summary
644 = withSession $ \hsc_env -> liftIO $ do
645 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
646 -- From now on, we just use the bits we need.
647 cg_module = this_mod,
648 cg_binds = core_binds,
650 cg_dir_imps = dir_imps,
651 cg_foreign = foreign_stubs,
652 cg_dep_pkgs = dependencies,
653 cg_hpc_info = hpc_info } = cgguts
654 dflags = hsc_dflags hsc_env
655 location = ms_location mod_summary
656 data_tycons = filter isDataTyCon tycons
657 -- cg_tycons includes newtypes, for the benefit of External Core,
658 -- but we don't generate any code for newtypes
661 -- PREPARE FOR CODE GENERATION
662 -- Do saturation and convert to A-normal form
663 prepd_binds <- {-# SCC "CorePrep" #-}
664 corePrepPgm dflags core_binds data_tycons ;
665 ----------------- Convert to STG ------------------
666 (stg_binds, cost_centre_info)
667 <- {-# SCC "CoreToStg" #-}
668 myCoreToStg dflags this_mod prepd_binds
670 ------------------ Try new code gen route ----------
671 cmms <- tryNewCodeGen hsc_env this_mod data_tycons
672 dir_imps cost_centre_info
675 ------------------ Code generation ------------------
676 cmms <- if dopt Opt_TryNewCodeGen (hsc_dflags hsc_env)
677 then pprTrace "cmms" (ppr cmms) $ return cmms
678 else {-# SCC "CodeGen" #-}
679 codeGen dflags this_mod data_tycons
680 dir_imps cost_centre_info
683 --- Optionally run experimental Cmm transformations ---
684 cmms <- optionallyConvertAndOrCPS hsc_env cmms
685 -- unless certain dflags are on, the identity function
686 ------------------ Code output -----------------------
687 rawcmms <- cmmToRawCmm cmms
688 (_stub_h_exists, stub_c_exists)
689 <- codeOutput dflags this_mod location foreign_stubs
693 hscInteractive :: GhcMonad m =>
694 (ModIface, ModDetails, CgGuts)
696 -> m (InteractiveStatus, ModIface, ModDetails)
698 hscInteractive (iface, details, cgguts) mod_summary
699 = do hsc_env <- getSession
701 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
702 -- From now on, we just use the bits we need.
703 cg_module = this_mod,
704 cg_binds = core_binds,
706 cg_foreign = foreign_stubs,
707 cg_modBreaks = mod_breaks } = cgguts
708 dflags = hsc_dflags hsc_env
709 location = ms_location mod_summary
710 data_tycons = filter isDataTyCon tycons
711 -- cg_tycons includes newtypes, for the benefit of External Core,
712 -- but we don't generate any code for newtypes
715 -- PREPARE FOR CODE GENERATION
716 -- Do saturation and convert to A-normal form
717 prepd_binds <- {-# SCC "CorePrep" #-}
718 corePrepPgm dflags core_binds data_tycons ;
719 ----------------- Generate byte code ------------------
720 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
721 ------------------ Create f-x-dynamic C-side stuff ---
722 (_istub_h_exists, istub_c_exists)
723 <- outputForeignStubs dflags this_mod location foreign_stubs
724 return (HscRecomp istub_c_exists (comp_bc, mod_breaks), iface, details)
726 hscInteractive _ _ = panic "GHC not compiled with interpreter"
729 ------------------------------
731 hscCmmFile :: GhcMonad m => HscEnv -> FilePath -> m ()
732 hscCmmFile hsc_env filename = do
733 dflags <- return $ hsc_dflags hsc_env
735 parseCmmFile dflags filename
736 cmms <- liftIO $ optionallyConvertAndOrCPS hsc_env [cmm]
737 rawCmms <- liftIO $ cmmToRawCmm cmms
738 liftIO $ codeOutput dflags no_mod no_loc NoStubs [] rawCmms
741 no_mod = panic "hscCmmFile: no_mod"
742 no_loc = ModLocation{ ml_hs_file = Just filename,
743 ml_hi_file = panic "hscCmmFile: no hi file",
744 ml_obj_file = panic "hscCmmFile: no obj file" }
746 -------------------- Stuff for new code gen ---------------------
748 tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> [Module]
750 -> [(StgBinding,[(Id,[Id])])]
753 tryNewCodeGen hsc_env this_mod data_tycons imported_mods
754 cost_centre_info stg_binds hpc_info
755 | not (dopt Opt_TryNewCodeGen (hsc_dflags hsc_env))
758 = do { let dflags = hsc_dflags hsc_env
759 ; prog <- StgCmm.codeGen dflags this_mod data_tycons imported_mods
760 cost_centre_info stg_binds hpc_info
761 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen"
764 ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) prog
765 -- Control flow optimisation
767 ; prog <- mapM (protoCmmCPSZ hsc_env) prog
768 -- The main CPS conversion
770 ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) prog
771 -- Control flow optimisation, again
773 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "New Cmm"
776 ; return $ map cmmOfZgraph prog }
779 optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
780 optionallyConvertAndOrCPS hsc_env cmms =
781 do let dflags = hsc_dflags hsc_env
782 -------- Optionally convert to and from zipper ------
783 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
784 then mapM (testCmmConversion hsc_env) cmms
786 --------- Optionally convert to CPS (MDA) -----------
787 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
788 dopt Opt_RunCPS dflags
789 then cmmCPS dflags cmms
794 testCmmConversion :: HscEnv -> Cmm -> IO Cmm
795 testCmmConversion hsc_env cmm =
796 do let dflags = hsc_dflags hsc_env
797 showPass dflags "CmmToCmm"
798 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
799 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
800 us <- mkSplitUniqSupply 'C'
801 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
802 let cvtm = do g <- cmmToZgraph cmm
804 let zgraph = initUs_ us cvtm
805 cps_zgraph <- protoCmmCPSZ hsc_env zgraph
806 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
807 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
808 showPass dflags "Convert from Z back to Cmm"
809 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
810 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
812 -- return cmm -- don't use the conversion
814 myCoreToStg :: DynFlags -> Module -> [CoreBind]
815 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
816 , CollectedCCs) -- cost centre info (declared and used)
818 myCoreToStg dflags this_mod prepd_binds
820 stg_binds <- {-# SCC "Core2Stg" #-}
821 coreToStg (thisPackage dflags) prepd_binds
823 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
824 stg2stg dflags this_mod stg_binds
826 return (stg_binds2, cost_centre_info)
830 %************************************************************************
832 \subsection{Compiling a do-statement}
834 %************************************************************************
836 When the UnlinkedBCOExpr is linked you get an HValue of type
838 When you run it you get a list of HValues that should be
839 the same length as the list of names; add them to the ClosureEnv.
841 A naked expression returns a singleton Name [it].
843 What you type The IO [HValue] that hscStmt returns
844 ------------- ------------------------------------
845 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
848 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
851 expr (of IO type) ==> expr >>= \ v -> return [v]
852 [NB: result not printed] bindings: [it]
855 expr (of non-IO type,
856 result showable) ==> let v = expr in print v >> return [v]
859 expr (of non-IO type,
860 result not showable) ==> error
864 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
867 -> String -- The statement
868 -> m (Maybe ([Id], HValue))
869 -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
870 hscStmt hsc_env stmt = do
871 maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
873 Nothing -> return Nothing
874 Just parsed_stmt -> do -- The real stuff
876 -- Rename and typecheck it
877 let icontext = hsc_IC hsc_env
878 (ids, tc_expr) <- ioMsgMaybe $ tcRnStmt hsc_env icontext parsed_stmt
880 let rdr_env = ic_rn_gbl_env icontext
881 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
882 ds_expr <- ioMsgMaybe $
883 deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
885 -- Then desugar, code gen, and link it
886 let src_span = srcLocSpan interactiveSrcLoc
887 hval <- liftIO $ compileExpr hsc_env src_span ds_expr
889 return $ Just (ids, hval)
892 hscTcExpr -- Typecheck an expression (but don't run it)
895 -> String -- The expression
898 hscTcExpr hsc_env expr = do
899 maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
900 let icontext = hsc_IC hsc_env
902 Just (L _ (ExprStmt expr _ _)) -> do
903 ty <- ioMsgMaybe $ tcRnExpr hsc_env icontext expr
905 _ -> do throw $ mkSrcErr $ unitBag $ mkPlainErrMsg
907 (text "not an expression:" <+> quotes (text expr))
909 -- | Find the kind of a type
913 -> String -- ^ The type
916 hscKcType hsc_env str = do
917 ty <- hscParseType (hsc_dflags hsc_env) str
918 let icontext = hsc_IC hsc_env
919 ioMsgMaybe $ tcRnType hsc_env icontext ty
926 hscParseStmt :: GhcMonad m => DynFlags -> String -> m (Maybe (LStmt RdrName))
927 hscParseStmt = hscParseThing parseStmt
929 hscParseType :: GhcMonad m => DynFlags -> String -> m (LHsType RdrName)
930 hscParseType = hscParseThing parseType
933 hscParseIdentifier :: GhcMonad m => DynFlags -> String -> m (Located RdrName)
934 hscParseIdentifier = hscParseThing parseIdentifier
936 hscParseThing :: (Outputable thing, GhcMonad m)
938 -> DynFlags -> String
940 -- Nothing => Parse error (message already printed)
942 hscParseThing parser dflags str
943 = (liftIO $ showPass dflags "Parser") >>
944 {-# SCC "Parser" #-} do
946 buf <- liftIO $ stringToStringBuffer str
948 let loc = mkSrcLoc (fsLit "<interactive>") 1 0
950 case unP parser (mkPState buf loc dflags) of
952 PFailed span err -> do
953 let msg = mkPlainErrMsg span err
954 throw (mkSrcErr (unitBag msg))
958 let ms@(warns, errs) = getMessages pst
960 when (errorsFound dflags ms) $ -- handle -Werror
961 throw (mkSrcErr errs)
963 --ToDo: can't free the string buffer until we've finished this
964 -- compilation sweep and all the identifiers have gone away.
965 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
969 %************************************************************************
971 Desugar, simplify, convert to bytecode, and link an expression
973 %************************************************************************
977 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
979 compileExpr hsc_env srcspan ds_expr
980 = do { let { dflags = hsc_dflags hsc_env ;
981 lint_on = dopt Opt_DoCoreLinting dflags }
984 ; simpl_expr <- simplifyExpr dflags ds_expr
986 -- Tidy it (temporary, until coreSat does cloning)
987 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
989 -- Prepare for codegen
990 ; prepd_expr <- corePrepExpr dflags tidy_expr
993 -- ToDo: improve SrcLoc
995 let ictxt = hsc_IC hsc_env
996 tyvars = varSetElems (ic_tyvars ictxt)
998 case lintUnfolding noSrcLoc tyvars prepd_expr of
999 Just err -> pprPanic "compileExpr" err
1000 Nothing -> return ()
1005 ; bcos <- coreExprToBCOs dflags prepd_expr
1008 ; hval <- linkExpr hsc_env srcspan bcos
1016 %************************************************************************
1018 Statistics on reading interfaces
1020 %************************************************************************
1023 dumpIfaceStats :: HscEnv -> IO ()
1024 dumpIfaceStats hsc_env
1025 = do { eps <- readIORef (hsc_EPS hsc_env)
1026 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1027 "Interface statistics"
1030 dflags = hsc_dflags hsc_env
1031 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1032 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1035 %************************************************************************
1037 Progress Messages: Module i of n
1039 %************************************************************************
1042 showModuleIndex :: Maybe (Int, Int) -> String
1043 showModuleIndex Nothing = ""
1044 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1048 padded = replicate (length n_str - length i_str) ' ' ++ i_str