2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
13 , hscNormalIface, hscWriteIface, hscOneShot
16 , hscStmt, hscTcExpr, hscKcType
19 , hscCompileOneShot -- :: Compiler HscStatus
20 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
21 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
22 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
24 , InteractiveStatus (..)
29 , typecheckRenameModule
36 import CodeOutput ( outputForeignStubs )
37 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
38 import Linker ( HValue, linkExpr )
39 import CoreTidy ( tidyExpr )
40 import CorePrep ( corePrepExpr )
41 import Desugar ( deSugarExpr )
42 import SimplCore ( simplifyExpr )
43 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
45 import PrelNames ( iNTERACTIVE )
46 import {- Kind parts of -} Type ( Kind )
47 import CoreLint ( lintUnfolding )
48 import DsMeta ( templateHaskellNames )
49 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan, noSrcSpan )
51 import VarEnv ( emptyTidyEnv )
55 import Module ( emptyModuleEnv, ModLocation(..), Module )
59 import SrcLoc ( Located(..) )
63 import SrcLoc ( mkSrcLoc )
64 import TcRnDriver ( tcRnModule )
65 import TcIface ( typecheckIface )
66 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
67 import IfaceEnv ( initNameCache )
68 import LoadIface ( ifaceStats, initExternalPackageState )
69 import PrelInfo ( wiredInThings, basicKnownKeyNames )
71 import Desugar ( deSugar )
72 import SimplCore ( core2core )
74 import CorePrep ( corePrepPgm )
75 import CoreToStg ( coreToStg )
78 import TyCon ( isDataTyCon )
79 import Name ( Name, NamedThing(..) )
80 import SimplStg ( stg2stg )
81 import CodeGen ( codeGen )
83 import CmmParse ( parseCmmFile )
87 import OptimizationFuel ( initOptFuelState )
91 import CodeOutput ( codeOutput )
92 import NameEnv ( emptyNameEnv )
96 import UniqSupply ( mkSplitUniqSupply )
99 import HscStats ( ppSourceStats )
101 import MkExternalCore ( emitExternalCore )
103 import LazyUniqFM ( emptyUFM )
104 import UniqSupply ( initUs_ )
105 import Bag ( unitBag, emptyBag, unionBags )
113 #include "HsVersions.h"
116 %************************************************************************
120 %************************************************************************
123 newHscEnv :: DynFlags -> IO HscEnv
125 = do { eps_var <- newIORef initExternalPackageState
126 ; us <- mkSplitUniqSupply 'r'
127 ; nc_var <- newIORef (initNameCache us knownKeyNames)
128 ; fc_var <- newIORef emptyUFM
129 ; mlc_var <- newIORef emptyModuleEnv
130 ; optFuel <- initOptFuelState
131 ; return (HscEnv { hsc_dflags = dflags,
134 hsc_IC = emptyInteractiveContext,
135 hsc_HPT = emptyHomePackageTable,
140 hsc_OptFuel = optFuel,
141 hsc_type_env_var = Nothing,
142 hsc_global_rdr_env = emptyGlobalRdrEnv,
143 hsc_global_type_env = emptyNameEnv } ) }
146 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
147 -- where templateHaskellNames are defined
148 knownKeyNames = map getName wiredInThings
149 ++ basicKnownKeyNames
151 ++ templateHaskellNames
157 -- | parse a file, returning the abstract syntax
158 parseFile :: GhcMonad m => HscEnv -> ModSummary -> m (Located (HsModule RdrName))
159 parseFile hsc_env mod_summary = do
160 ((warns,errs), maybe_parsed) <- liftIO $ myParseModule dflags hspp_file hspp_buf
163 Nothing -> liftIO $ throwIO (mkSrcErr errs)
167 dflags = hsc_dflags hsc_env
168 hspp_file = ms_hspp_file mod_summary
169 hspp_buf = ms_hspp_buf mod_summary
171 -- | Rename and typecheck a module
172 typecheckModule' :: GhcMonad m =>
173 HscEnv -> ModSummary -> Located (HsModule RdrName)
175 typecheckModule' hsc_env mod_summary rdr_module = do
176 r <- {-# SCC "Typecheck-Rename" #-}
177 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
180 -- XXX: should this really be a Maybe X? Check under which circumstances this
181 -- can become a Nothing and decide whether this should instead throw an
182 -- exception/signal an error.
184 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
185 Maybe (HsDoc Name), HaddockModInfo Name))
187 -- | Rename and typecheck a module, additionally returning the renamed syntax
188 typecheckRenameModule
190 HscEnv -> ModSummary -> Located (HsModule RdrName)
191 -> m (TcGblEnv, RenamedStuff)
192 typecheckRenameModule hsc_env mod_summary rdr_module = do
194 <- {-# SCC "Typecheck-Rename" #-}
195 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
197 let rn_info = do decl <- tcg_rn_decls tc_result
198 imports <- tcg_rn_imports tc_result
199 let exports = tcg_rn_exports tc_result
200 let doc = tcg_doc tc_result
201 let hmi = tcg_hmi tc_result
202 return (decl,imports,exports,doc,hmi)
204 return (tc_result, rn_info)
206 -- | Convert a typechecked module to Core
207 deSugarModule :: GhcMonad m => HscEnv -> ModSummary -> TcGblEnv -> m ModGuts
208 deSugarModule hsc_env mod_summary tc_result = do
209 ioMsgMaybe $ deSugar hsc_env (ms_location mod_summary) tc_result
211 -- | Make a 'ModIface' from the results of typechecking. Used when
212 -- not optimising, and the interface doesn't need to contain any
213 -- unfoldings or other cross-module optimisation info.
214 -- ToDo: the old interface is only needed to get the version numbers,
215 -- we should use fingerprint versions instead.
216 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
217 -> IO (ModIface,Bool)
218 makeSimpleIface hsc_env maybe_old_iface tc_result details = do
219 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
221 -- | Make a 'ModDetails' from the results of typechecking. Used when
222 -- typechecking only, as opposed to full compilation.
223 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
224 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
226 -- deSugarModule :: HscEnv -> TcGblEnv -> IO Core
229 %************************************************************************
231 The main compiler pipeline
233 %************************************************************************
235 --------------------------------
236 The compilation proper
237 --------------------------------
240 It's the task of the compilation proper to compile Haskell, hs-boot and
241 core files to either byte-code, hard-code (C, asm, Java, ect) or to
242 nothing at all (the module is still parsed and type-checked. This
243 feature is mostly used by IDE's and the likes).
244 Compilation can happen in either 'one-shot', 'batch', 'nothing',
245 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
246 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
248 The modes are kept separate because of their different types and meanings.
249 In 'one-shot' mode, we're only compiling a single file and can therefore
250 discard the new ModIface and ModDetails. This is also the reason it only
251 targets hard-code; compiling to byte-code or nothing doesn't make sense
252 when we discard the result.
253 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
254 and ModDetails. 'Batch' mode doesn't target byte-code since that require
255 us to return the newly compiled byte-code.
256 'Nothing' mode has exactly the same type as 'batch' mode but they're still
257 kept separate. This is because compiling to nothing is fairly special: We
258 don't output any interface files, we don't run the simplifier and we don't
260 'Interactive' mode is similar to 'batch' mode except that we return the
261 compiled byte-code together with the ModIface and ModDetails.
263 Trying to compile a hs-boot file to byte-code will result in a run-time
264 error. This is the only thing that isn't caught by the type-system.
268 -- Status of a compilation to hard-code or nothing.
271 | HscRecomp Bool -- Has stub files.
272 -- This is a hack. We can't compile C files here
273 -- since it's done in DriverPipeline. For now we
274 -- just return True if we want the caller to compile
277 -- Status of a compilation to byte-code.
278 data InteractiveStatus
279 = InteractiveNoRecomp
280 | InteractiveRecomp Bool -- Same as HscStatus
285 -- I want Control.Monad.State! --Lemmih 03/07/2006
286 newtype Comp a = Comp {runComp :: CompState -> IORef Messages -> IO (a, CompState)}
288 instance Monad Comp where
289 g >>= fn = Comp $ \s r -> runComp g s r >>= \(a,s') -> runComp (fn a) s' r
290 return a = Comp $ \s _ -> return (a,s)
293 evalComp :: Comp a -> CompState -> IO (Messages, a)
294 evalComp comp st = do r <- newIORef emptyMessages
295 (val,_st') <- runComp comp st r
299 logMsgs :: Messages -> Comp ()
300 logMsgs (warns', errs') = Comp $ \s r -> do
301 (warns, errs) <- readIORef r
302 writeIORef r $! ( warns' `unionBags` warns
303 , errs' `unionBags` errs )
308 { compHscEnv :: HscEnv
309 , compModSummary :: ModSummary
310 , compOldIface :: Maybe ModIface
313 get :: Comp CompState
314 get = Comp $ \s _ -> return (s,s)
316 modify :: (CompState -> CompState) -> Comp ()
317 modify f = Comp $ \s _ -> return ((), f s)
319 gets :: (CompState -> a) -> Comp a
320 gets getter = do st <- get
323 instance MonadIO Comp where
324 liftIO ioA = Comp $ \s _ -> do a <- ioA; return (a,s)
326 type NoRecomp result = ModIface -> Comp result
328 -- FIXME: The old interface and module index are only using in 'batch' and
329 -- 'interactive' mode. They should be removed from 'oneshot' mode.
330 type Compiler result = GhcMonad m =>
333 -> Bool -- True <=> source unchanged
334 -> Maybe ModIface -- Old interface, if available
335 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
338 --------------------------------------------------------------
340 --------------------------------------------------------------
342 -- Compile Haskell, boot and extCore in OneShot mode.
343 hscCompileOneShot :: Compiler HscStatus
344 hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
346 -- One-shot mode needs a knot-tying mutable variable for interface files.
347 -- See TcRnTypes.TcGblEnv.tcg_type_env_var.
348 type_env_var <- liftIO $ newIORef emptyNameEnv
350 mod = ms_mod mod_summary
351 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
353 hscCompilerOneShot' hsc_env' mod_summary src_changed mb_old_iface mb_i_of_n
355 hscCompilerOneShot' :: Compiler HscStatus
357 = hscCompiler norecompOneShot oneShotMsg (genComp backend boot_backend)
359 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
360 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (Just (HscRecomp False))
362 -- Compile Haskell, boot and extCore in batch mode.
363 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
365 = hscCompiler norecompBatch batchMsg (genComp backend boot_backend)
367 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
368 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
370 -- Compile Haskell, extCore to bytecode.
371 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
372 hscCompileInteractive
373 = hscCompiler norecompInteractive batchMsg (genComp backend boot_backend)
375 backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
376 boot_backend _ = panic "hscCompileInteractive: HsBootFile"
378 -- Type-check Haskell and .hs-boot only (no external core)
379 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
381 = hscCompiler norecompBatch batchMsg comp
383 backend tc = hscSimpleIface tc >>= hscIgnoreIface >>= hscNothing
385 comp = do -- genComp doesn't fit here, because we want to omit
386 -- desugaring and for the backend to take a TcGblEnv
387 mod_summary <- gets compModSummary
388 case ms_hsc_src mod_summary of
389 ExtCoreFile -> panic "hscCompileNothing: cannot do external core"
391 mb_tc <- hscFileFrontEnd
393 Nothing -> return Nothing
394 Just tc_result -> backend tc_result
397 :: NoRecomp result -- No recomp necessary
398 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
399 -> Comp (Maybe result)
401 hscCompiler norecomp messenger recomp hsc_env mod_summary
402 source_unchanged mbOldIface mbModIndex
404 flip evalComp (CompState hsc_env mod_summary mbOldIface) $
405 do (recomp_reqd, mbCheckedIface)
406 <- {-# SCC "checkOldIface" #-}
407 liftIO $ checkOldIface hsc_env mod_summary
408 source_unchanged mbOldIface
409 -- save the interface that comes back from checkOldIface.
410 -- In one-shot mode we don't have the old iface until this
411 -- point, when checkOldIface reads it from the disk.
412 modify (\s -> s{ compOldIface = mbCheckedIface })
413 case mbCheckedIface of
414 Just iface | not recomp_reqd
415 -> do messenger mbModIndex False
416 result <- norecomp iface
419 -> do messenger mbModIndex True
422 -- the usual way to build the Comp (Maybe result) to pass to hscCompiler
423 genComp :: (ModGuts -> Comp (Maybe a))
424 -> (TcGblEnv -> Comp (Maybe a))
426 genComp backend boot_backend = do
427 mod_summary <- gets compModSummary
428 case ms_hsc_src mod_summary of
430 panic "GHC does not currently support reading External Core files"
432 mb_tc <- hscFileFrontEnd
434 Nothing -> return Nothing
436 case ms_hsc_src mod_summary of
437 HsBootFile -> boot_backend tc_result
439 mb_guts <- hscDesugar tc_result
441 Nothing -> return Nothing
442 Just guts -> backend guts
444 --------------------------------------------------------------
446 --------------------------------------------------------------
448 norecompOneShot :: NoRecomp HscStatus
449 norecompOneShot _old_iface
450 = do hsc_env <- gets compHscEnv
452 dumpIfaceStats hsc_env
455 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
456 norecompBatch = norecompWorker HscNoRecomp False
458 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
459 norecompInteractive = norecompWorker InteractiveNoRecomp True
461 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
462 norecompWorker a _isInterp old_iface
463 = do hsc_env <- gets compHscEnv
465 new_details <- {-# SCC "tcRnIface" #-}
466 initIfaceCheck hsc_env $
467 typecheckIface old_iface
468 dumpIfaceStats hsc_env
469 return (a, old_iface, new_details)
471 --------------------------------------------------------------
472 -- Progress displayers.
473 --------------------------------------------------------------
475 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
476 oneShotMsg _mb_mod_index recomp
477 = do hsc_env <- gets compHscEnv
481 else compilationProgressMsg (hsc_dflags hsc_env) $
482 "compilation IS NOT required"
484 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
485 batchMsg mb_mod_index recomp
486 = do hsc_env <- gets compHscEnv
487 mod_summary <- gets compModSummary
488 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
489 (showModuleIndex mb_mod_index ++
490 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
493 then showMsg "Compiling "
494 else if verbosity (hsc_dflags hsc_env) >= 2
495 then showMsg "Skipping "
498 --------------------------------------------------------------
500 --------------------------------------------------------------
501 hscFileFrontEnd :: Comp (Maybe TcGblEnv)
503 do hsc_env <- gets compHscEnv
504 mod_summary <- gets compModSummary
509 let dflags = hsc_dflags hsc_env
510 hspp_file = ms_hspp_file mod_summary
511 hspp_buf = ms_hspp_buf mod_summary
512 (ms@(warns,_), maybe_parsed)
513 <- liftIO $ myParseModule dflags hspp_file hspp_buf
520 -- RENAME and TYPECHECK
522 -> do logMsgs (warns, emptyBag)
523 (tc_msgs, maybe_tc_result)
524 <- {-# SCC "Typecheck-Rename" #-}
525 liftIO $ tcRnModule hsc_env (ms_hsc_src mod_summary)
528 return maybe_tc_result
530 --------------------------------------------------------------
532 --------------------------------------------------------------
534 hscDesugar :: TcGblEnv -> Comp (Maybe ModGuts)
536 = do mod_summary <- gets compModSummary
537 hsc_env <- gets compHscEnv
543 <- {-# SCC "DeSugar" #-}
544 liftIO $ deSugar hsc_env (ms_location mod_summary) tc_result
548 --------------------------------------------------------------
550 --------------------------------------------------------------
552 hscSimplify :: ModGuts -> Comp ModGuts
553 hscSimplify ds_result
554 = do hsc_env <- gets compHscEnv
559 simpl_result <- {-# SCC "Core2Core" #-}
560 core2core hsc_env ds_result
563 --------------------------------------------------------------
564 -- Interface generators
565 --------------------------------------------------------------
567 -- HACK: we return ModGuts even though we know it's not gonna be used.
568 -- We do this because the type signature needs to be identical
569 -- in structure to the type of 'hscNormalIface'.
570 hscSimpleIface :: TcGblEnv -> Comp (ModIface, Bool, ModDetails, TcGblEnv)
571 hscSimpleIface tc_result
572 = do hsc_env <- gets compHscEnv
573 maybe_old_iface <- gets compOldIface
575 details <- mkBootModDetailsTc hsc_env tc_result
576 (new_iface, no_change)
577 <- {-# SCC "MkFinalIface" #-}
578 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
579 -- And the answer is ...
580 dumpIfaceStats hsc_env
581 return (new_iface, no_change, details, tc_result)
583 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
584 hscNormalIface simpl_result
585 = do hsc_env <- gets compHscEnv
586 _mod_summary <- gets compModSummary
587 maybe_old_iface <- gets compOldIface
592 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
593 tidyProgram hsc_env simpl_result
596 -- BUILD THE NEW ModIface and ModDetails
597 -- and emit external core if necessary
598 -- This has to happen *after* code gen so that the back-end
599 -- info has been set. Not yet clear if it matters waiting
600 -- until after code output
601 (new_iface, no_change)
602 <- {-# SCC "MkFinalIface" #-}
603 mkIface hsc_env (fmap mi_iface_hash maybe_old_iface)
605 -- Emit external core
606 -- This should definitely be here and not after CorePrep,
607 -- because CorePrep produces unqualified constructor wrapper declarations,
608 -- so its output isn't valid External Core (without some preprocessing).
609 emitExternalCore (hsc_dflags hsc_env) cg_guts
610 dumpIfaceStats hsc_env
613 -- Return the prepared code.
614 return (new_iface, no_change, details, cg_guts)
616 --------------------------------------------------------------
617 -- BackEnd combinators
618 --------------------------------------------------------------
620 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
621 hscWriteIface (iface, no_change, details, a)
622 = do mod_summary <- gets compModSummary
623 hsc_env <- gets compHscEnv
624 let dflags = hsc_dflags hsc_env
627 $ writeIfaceFile dflags (ms_location mod_summary) iface
628 return (iface, details, a)
630 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
631 hscIgnoreIface (iface, _no_change, details, a)
632 = return (iface, details, a)
634 -- Don't output any code.
635 hscNothing :: (ModIface, ModDetails, a) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
636 hscNothing (iface, details, _)
637 = return (Just (HscRecomp False, iface, details))
639 -- Generate code and return both the new ModIface and the ModDetails.
640 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
641 hscBatch (iface, details, cgguts)
642 = do hasStub <- hscCompile cgguts
643 return (Just (HscRecomp hasStub, iface, details))
645 -- Here we don't need the ModIface and ModDetails anymore.
646 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe HscStatus)
647 hscOneShot (_, _, cgguts)
648 = do hasStub <- hscCompile cgguts
649 return (Just (HscRecomp hasStub))
651 -- Compile to hard-code.
652 hscCompile :: CgGuts -> Comp Bool
654 = do hsc_env <- gets compHscEnv
655 mod_summary <- gets compModSummary
657 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
658 -- From now on, we just use the bits we need.
659 cg_module = this_mod,
660 cg_binds = core_binds,
662 cg_dir_imps = dir_imps,
663 cg_foreign = foreign_stubs,
664 cg_dep_pkgs = dependencies,
665 cg_hpc_info = hpc_info } = cgguts
666 dflags = hsc_dflags hsc_env
667 location = ms_location mod_summary
668 data_tycons = filter isDataTyCon tycons
669 -- cg_tycons includes newtypes, for the benefit of External Core,
670 -- but we don't generate any code for newtypes
673 -- PREPARE FOR CODE GENERATION
674 -- Do saturation and convert to A-normal form
675 prepd_binds <- {-# SCC "CorePrep" #-}
676 corePrepPgm dflags core_binds data_tycons ;
677 ----------------- Convert to STG ------------------
678 (stg_binds, cost_centre_info)
679 <- {-# SCC "CoreToStg" #-}
680 myCoreToStg dflags this_mod prepd_binds
681 ------------------ Code generation ------------------
682 cmms <- {-# SCC "CodeGen" #-}
683 codeGen dflags this_mod data_tycons
684 dir_imps cost_centre_info
686 --- Optionally run experimental Cmm transformations ---
687 cmms <- optionallyConvertAndOrCPS hsc_env cmms
688 -- unless certain dflags are on, the identity function
689 ------------------ Code output -----------------------
690 rawcmms <- cmmToRawCmm cmms
691 (_stub_h_exists, stub_c_exists)
692 <- codeOutput dflags this_mod location foreign_stubs
696 hscInteractive :: (ModIface, ModDetails, CgGuts)
697 -> Comp (Maybe (InteractiveStatus, ModIface, ModDetails))
699 hscInteractive (iface, details, cgguts)
700 = do hsc_env <- gets compHscEnv
701 mod_summary <- gets compModSummary
703 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
704 -- From now on, we just use the bits we need.
705 cg_module = this_mod,
706 cg_binds = core_binds,
708 cg_foreign = foreign_stubs,
709 cg_modBreaks = mod_breaks } = cgguts
710 dflags = hsc_dflags hsc_env
711 location = ms_location mod_summary
712 data_tycons = filter isDataTyCon tycons
713 -- cg_tycons includes newtypes, for the benefit of External Core,
714 -- but we don't generate any code for newtypes
717 -- PREPARE FOR CODE GENERATION
718 -- Do saturation and convert to A-normal form
719 prepd_binds <- {-# SCC "CorePrep" #-}
720 corePrepPgm dflags core_binds data_tycons ;
721 ----------------- Generate byte code ------------------
722 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
723 ------------------ Create f-x-dynamic C-side stuff ---
724 (_istub_h_exists, istub_c_exists)
725 <- outputForeignStubs dflags this_mod location foreign_stubs
726 return (Just (InteractiveRecomp istub_c_exists comp_bc mod_breaks, iface, details))
728 hscInteractive _ = panic "GHC not compiled with interpreter"
731 ------------------------------
733 hscCmmFile :: GhcMonad m => HscEnv -> FilePath -> m ()
734 hscCmmFile hsc_env filename = do
735 dflags <- return $ hsc_dflags hsc_env
737 parseCmmFile dflags filename
738 cmms <- liftIO $ optionallyConvertAndOrCPS hsc_env [cmm]
739 rawCmms <- liftIO $ cmmToRawCmm cmms
740 liftIO $ codeOutput dflags no_mod no_loc NoStubs [] rawCmms
743 no_mod = panic "hscCmmFile: no_mod"
744 no_loc = ModLocation{ ml_hs_file = Just filename,
745 ml_hi_file = panic "hscCmmFile: no hi file",
746 ml_obj_file = panic "hscCmmFile: no obj file" }
748 optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
749 optionallyConvertAndOrCPS hsc_env cmms =
750 do let dflags = hsc_dflags hsc_env
751 -------- Optionally convert to and from zipper ------
752 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
753 then mapM (testCmmConversion hsc_env) cmms
755 --------- Optionally convert to CPS (MDA) -----------
756 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
757 dopt Opt_RunCPSZ dflags
758 then cmmCPS dflags cmms
763 testCmmConversion :: HscEnv -> Cmm -> IO Cmm
764 testCmmConversion hsc_env cmm =
765 do let dflags = hsc_dflags hsc_env
766 showPass dflags "CmmToCmm"
767 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
768 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
769 us <- mkSplitUniqSupply 'C'
770 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
771 let cvtm = do g <- cmmToZgraph cmm
773 let zgraph = initUs_ us cvtm
774 cps_zgraph <- protoCmmCPSZ hsc_env zgraph
775 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
776 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
777 showPass dflags "Convert from Z back to Cmm"
778 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
779 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
781 -- return cmm -- don't use the conversion
783 myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
784 -> IO (Messages, Maybe (Located (HsModule RdrName)))
785 myParseModule dflags src_filename maybe_src_buf =
786 -------------------------- Parser ----------------
787 showPass dflags "Parser" >>
788 {-# SCC "Parser" #-} do
790 -- sometimes we already have the buffer in memory, perhaps
791 -- because we needed to parse the imports out of it, or get the
793 buf <- case maybe_src_buf of
795 Nothing -> hGetStringBuffer src_filename
797 let loc = mkSrcLoc (mkFastString src_filename) 1 0
799 case unP parseModule (mkPState buf loc dflags) of
801 return ((emptyBag, unitBag (mkPlainErrMsg span err)), Nothing);
803 POk pst rdr_module -> do
804 let ms = getMessages pst
805 if errorsFound dflags ms then
808 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
809 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
810 (ppSourceStats False rdr_module) ;
811 return (ms, Just rdr_module)
812 -- ToDo: free the string buffer later.
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