2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 -- | Main API for compiling plain Haskell source code.
7 -- This module implements compilation of a Haskell source. It is
8 -- /not/ concerned with preprocessing of source files; this is handled
9 -- in "DriverPipeline".
11 -- There are various entry points depending on what mode we're in:
12 -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
13 -- "interactive" mode (GHCi). There are also entry points for
14 -- individual passes: parsing, typechecking/renaming, desugaring, and
17 -- All the functions here take an 'HscEnv' as a parameter, but none of
18 -- them return a new one: 'HscEnv' is treated as an immutable value
19 -- from here on in (although it has mutable components, for the
22 -- Warning messages are dealt with consistently throughout this API:
23 -- during compilation warnings are collected, and before any function
24 -- in @HscMain@ returns, the warnings are either printed, or turned
25 -- into a real compialtion error if the @-Werror@ flag is enabled.
32 -- * Compiling complete source files
35 , InteractiveStatus, HscStatus
39 , hscCompileInteractive
43 -- * Running passes separately
49 , hscSimplify -- ToDo, shouldn't really export this
52 , hscOneShotBackendOnly
54 , hscNothingBackendOnly
55 , hscInteractiveBackendOnly
57 -- * Support for interactive evaluation
64 , hscTcRnLookupRdrName
65 , hscStmt, hscTcExpr, hscImport, hscKcType
72 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
73 import Linker ( HValue, linkExpr )
74 import CoreTidy ( tidyExpr )
76 import TcType ( tyVarsOfTypes )
77 import PrelNames ( iNTERACTIVE )
78 import {- Kind parts of -} Type ( Kind )
80 import CoreLint ( lintUnfolding )
81 import DsMeta ( templateHaskellNames )
83 import VarEnv ( emptyTidyEnv )
88 import Module ( emptyModuleEnv, ModLocation(..), Module )
94 import Lexer hiding (getDynFlags)
97 import TcIface ( typecheckIface )
99 import RnNames ( rnImports )
100 import IfaceEnv ( initNameCache )
101 import LoadIface ( ifaceStats, initExternalPackageState )
102 import PrelInfo ( wiredInThings, basicKnownKeyNames )
108 import CoreToStg ( coreToStg )
109 import qualified StgCmm ( codeGen )
112 import TyCon ( TyCon, isDataTyCon )
113 import Name ( Name, NamedThing(..) )
114 import SimplStg ( stg2stg )
115 import CodeGen ( codeGen )
116 import OldCmm ( Cmm )
117 import PprCmm ( pprCmms )
118 import CmmParse ( parseCmmFile )
119 import CmmBuildInfoTables
122 import OptimizationFuel ( initOptFuelState )
124 import CmmContFlowOpt ( runCmmContFlowOpts )
126 import NameEnv ( emptyNameEnv )
127 import NameSet ( emptyNameSet )
129 import FamInstEnv ( emptyFamInstEnv )
130 import Fingerprint ( Fingerprint )
134 import UniqSupply ( mkSplitUniqSupply )
137 import HscStats ( ppSourceStats )
139 import MkExternalCore ( emitExternalCore )
141 import UniqFM ( emptyUFM )
142 import UniqSupply ( initUs_ )
151 #include "HsVersions.h"
154 %************************************************************************
158 %************************************************************************
161 newHscEnv :: DynFlags -> IO HscEnv
163 = do { eps_var <- newIORef initExternalPackageState
164 ; us <- mkSplitUniqSupply 'r'
165 ; nc_var <- newIORef (initNameCache us knownKeyNames)
166 ; fc_var <- newIORef emptyUFM
167 ; mlc_var <- newIORef emptyModuleEnv
168 ; optFuel <- initOptFuelState
169 ; return (HscEnv { hsc_dflags = dflags,
172 hsc_IC = emptyInteractiveContext,
173 hsc_HPT = emptyHomePackageTable,
178 hsc_OptFuel = optFuel,
179 hsc_type_env_var = Nothing } ) }
182 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
183 -- where templateHaskellNames are defined
184 knownKeyNames = map getName wiredInThings
185 ++ basicKnownKeyNames
187 ++ templateHaskellNames
190 -- -----------------------------------------------------------------------------
191 -- The Hsc monad: collecting warnings
193 newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
195 instance Monad Hsc where
196 return a = Hsc $ \_ w -> return (a, w)
197 Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
201 instance MonadIO Hsc where
202 liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
204 runHsc :: HscEnv -> Hsc a -> IO a
205 runHsc hsc_env (Hsc hsc) = do
206 (a, w) <- hsc hsc_env emptyBag
207 printOrThrowWarnings (hsc_dflags hsc_env) w
210 getWarnings :: Hsc WarningMessages
211 getWarnings = Hsc $ \_ w -> return (w, w)
213 clearWarnings :: Hsc ()
214 clearWarnings = Hsc $ \_ _w -> return ((), emptyBag)
216 logWarnings :: WarningMessages -> Hsc ()
217 logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
219 getHscEnv :: Hsc HscEnv
220 getHscEnv = Hsc $ \e w -> return (e, w)
222 getDynFlags :: Hsc DynFlags
223 getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
225 handleWarnings :: Hsc ()
227 dflags <- getDynFlags
229 liftIO $ printOrThrowWarnings dflags w
232 -- | log warning in the monad, and if there are errors then
233 -- throw a SourceError exception.
234 logWarningsReportErrors :: Messages -> Hsc ()
235 logWarningsReportErrors (warns,errs) = do
237 when (not (isEmptyBag errs)) $ do
238 liftIO $ throwIO $ mkSrcErr errs
240 -- | Deal with errors and warnings returned by a compilation step
242 -- In order to reduce dependencies to other parts of the compiler, functions
243 -- outside the "main" parts of GHC return warnings and errors as a parameter
244 -- and signal success via by wrapping the result in a 'Maybe' type. This
245 -- function logs the returned warnings and propagates errors as exceptions
246 -- (of type 'SourceError').
248 -- This function assumes the following invariants:
250 -- 1. If the second result indicates success (is of the form 'Just x'),
251 -- there must be no error messages in the first result.
253 -- 2. If there are no error messages, but the second result indicates failure
254 -- there should be warnings in the first result. That is, if the action
255 -- failed, it must have been due to the warnings (i.e., @-Werror@).
256 ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
258 ((warns,errs), mb_r) <- liftIO $ ioA
261 Nothing -> liftIO $ throwIO (mkSrcErr errs)
262 Just r -> ASSERT( isEmptyBag errs ) return r
264 -- | like ioMsgMaybe, except that we ignore error messages and return
265 -- 'Nothing' instead.
266 ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
268 ((warns,_errs), mb_r) <- liftIO $ ioA
272 -- -----------------------------------------------------------------------------
273 -- | Lookup things in the compiler's environment
276 hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
277 hscTcRnLookupRdrName hsc_env rdr_name =
278 runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
281 hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
282 hscTcRcLookupName hsc_env name =
283 runHsc hsc_env $ ioMsgMaybe' $ tcRnLookupName hsc_env name
284 -- ignore errors: the only error we're likely to get is
285 -- "name not found", and the Maybe in the return type
286 -- is used to indicate that.
288 hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance]))
289 hscTcRnGetInfo hsc_env name =
290 runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name
293 hscGetModuleExports :: HscEnv -> Module -> IO (Maybe [AvailInfo])
294 hscGetModuleExports hsc_env mdl =
295 runHsc hsc_env $ ioMsgMaybe' $ getModuleExports hsc_env mdl
298 -- -----------------------------------------------------------------------------
299 -- | Rename some import declarations
304 -> [LImportDecl RdrName]
307 hscRnImportDecls hsc_env this_mod import_decls = runHsc hsc_env $ do
309 ioMsgMaybe $ initTc hsc_env HsSrcFile False this_mod $
310 rnImports import_decls
313 -- -----------------------------------------------------------------------------
314 -- | parse a file, returning the abstract syntax
316 hscParse :: HscEnv -> ModSummary -> IO (Located (HsModule RdrName))
317 hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary
319 -- internal version, that doesn't fail due to -Werror
320 hscParse' :: ModSummary -> Hsc (Located (HsModule RdrName))
321 hscParse' mod_summary
323 dflags <- getDynFlags
325 src_filename = ms_hspp_file mod_summary
326 maybe_src_buf = ms_hspp_buf mod_summary
328 -------------------------- Parser ----------------
329 liftIO $ showPass dflags "Parser"
330 {-# SCC "Parser" #-} do
332 -- sometimes we already have the buffer in memory, perhaps
333 -- because we needed to parse the imports out of it, or get the
335 buf <- case maybe_src_buf of
337 Nothing -> liftIO $ hGetStringBuffer src_filename
339 let loc = mkSrcLoc (mkFastString src_filename) 1 1
341 case unP parseModule (mkPState dflags buf loc) of
343 liftIO $ throwOneError (mkPlainErrMsg span err)
345 POk pst rdr_module -> do
346 logWarningsReportErrors (getMessages pst)
347 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
349 liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
350 ppSourceStats False rdr_module
352 -- ToDo: free the string buffer later.
354 -- XXX: should this really be a Maybe X? Check under which circumstances this
355 -- can become a Nothing and decide whether this should instead throw an
356 -- exception/signal an error.
358 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
361 -- | Rename and typecheck a module, additionally returning the renamed syntax
362 hscTypecheckRename :: HscEnv -> ModSummary -> Located (HsModule RdrName)
363 -> IO (TcGblEnv, RenamedStuff)
364 hscTypecheckRename hsc_env mod_summary rdr_module
365 = runHsc hsc_env $ do
367 <- {-# SCC "Typecheck-Rename" #-}
369 tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
371 let -- This 'do' is in the Maybe monad!
372 rn_info = do decl <- tcg_rn_decls tc_result
373 let imports = tcg_rn_imports tc_result
374 exports = tcg_rn_exports tc_result
375 doc_hdr = tcg_doc_hdr tc_result
376 return (decl,imports,exports,doc_hdr)
378 return (tc_result, rn_info)
380 -- | Convert a typechecked module to Core
381 hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
382 hscDesugar hsc_env mod_summary tc_result
383 = runHsc hsc_env $ hscDesugar' mod_summary tc_result
385 hscDesugar' :: ModSummary -> TcGblEnv -> Hsc ModGuts
386 hscDesugar' mod_summary tc_result
390 deSugar hsc_env (ms_location mod_summary) tc_result
393 -- always check -Werror after desugaring, this is
394 -- the last opportunity for warnings to arise before
398 -- | Make a 'ModIface' from the results of typechecking. Used when
399 -- not optimising, and the interface doesn't need to contain any
400 -- unfoldings or other cross-module optimisation info.
401 -- ToDo: the old interface is only needed to get the version numbers,
402 -- we should use fingerprint versions instead.
403 makeSimpleIface :: HscEnv ->
404 Maybe ModIface -> TcGblEnv -> ModDetails
405 -> IO (ModIface,Bool)
406 makeSimpleIface hsc_env maybe_old_iface tc_result details
409 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
411 -- | Make a 'ModDetails' from the results of typechecking. Used when
412 -- typechecking only, as opposed to full compilation.
413 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
414 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
417 %************************************************************************
419 The main compiler pipeline
421 %************************************************************************
423 --------------------------------
424 The compilation proper
425 --------------------------------
428 It's the task of the compilation proper to compile Haskell, hs-boot and
429 core files to either byte-code, hard-code (C, asm, Java, ect) or to
430 nothing at all (the module is still parsed and type-checked. This
431 feature is mostly used by IDE's and the likes).
432 Compilation can happen in either 'one-shot', 'batch', 'nothing',
433 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
434 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
436 The modes are kept separate because of their different types and meanings.
437 In 'one-shot' mode, we're only compiling a single file and can therefore
438 discard the new ModIface and ModDetails. This is also the reason it only
439 targets hard-code; compiling to byte-code or nothing doesn't make sense
440 when we discard the result.
441 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
442 and ModDetails. 'Batch' mode doesn't target byte-code since that require
443 us to return the newly compiled byte-code.
444 'Nothing' mode has exactly the same type as 'batch' mode but they're still
445 kept separate. This is because compiling to nothing is fairly special: We
446 don't output any interface files, we don't run the simplifier and we don't
448 'Interactive' mode is similar to 'batch' mode except that we return the
449 compiled byte-code together with the ModIface and ModDetails.
451 Trying to compile a hs-boot file to byte-code will result in a run-time
452 error. This is the only thing that isn't caught by the type-system.
456 -- Status of a compilation to hard-code or nothing.
460 Bool -- Has stub files. This is a hack. We can't compile C files here
461 -- since it's done in DriverPipeline. For now we just return True
462 -- if we want the caller to compile them for us.
465 -- This is a bit ugly. Since we use a typeclass below and would like to avoid
466 -- functional dependencies, we have to parameterise the typeclass over the
467 -- result type. Therefore we need to artificially distinguish some types. We
468 -- do this by adding type tags which will simply be ignored by the caller.
469 type HscStatus = HscStatus' ()
470 type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
471 -- INVARIANT: result is @Nothing@ <=> input was a boot file
473 type OneShotResult = HscStatus
474 type BatchResult = (HscStatus, ModIface, ModDetails)
475 type NothingResult = (HscStatus, ModIface, ModDetails)
476 type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
478 -- FIXME: The old interface and module index are only using in 'batch' and
479 -- 'interactive' mode. They should be removed from 'oneshot' mode.
480 type Compiler result = HscEnv
482 -> Bool -- True <=> source unchanged
483 -> Maybe ModIface -- Old interface, if available
484 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
489 -- | Called when no recompilation is necessary.
490 hscNoRecomp :: ModIface
493 -- | Called to recompile the module.
494 hscRecompile :: ModSummary -> Maybe Fingerprint
497 hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
500 -- | Code generation for Boot modules.
501 hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
504 -- | Code generation for normal modules.
505 hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint
509 genericHscCompile :: HsCompiler a
510 -> (HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ())
511 -> HscEnv -> ModSummary -> Bool
512 -> Maybe ModIface -> Maybe (Int, Int)
514 genericHscCompile compiler hscMessage hsc_env
515 mod_summary source_unchanged
516 mb_old_iface0 mb_mod_index
518 (recomp_reqd, mb_checked_iface)
519 <- {-# SCC "checkOldIface" #-}
520 checkOldIface hsc_env mod_summary
521 source_unchanged mb_old_iface0
522 -- save the interface that comes back from checkOldIface.
523 -- In one-shot mode we don't have the old iface until this
524 -- point, when checkOldIface reads it from the disk.
525 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
526 case mb_checked_iface of
527 Just iface | not recomp_reqd
528 -> do hscMessage hsc_env mb_mod_index False mod_summary
529 runHsc hsc_env $ hscNoRecomp compiler iface
531 -> do hscMessage hsc_env mb_mod_index True mod_summary
532 runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash
534 hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
535 hscCheckRecompBackend compiler tc_result
536 hsc_env mod_summary source_unchanged mb_old_iface _m_of_n
538 (recomp_reqd, mb_checked_iface)
539 <- {-# SCC "checkOldIface" #-}
540 checkOldIface hsc_env mod_summary
541 source_unchanged mb_old_iface
543 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
544 case mb_checked_iface of
545 Just iface | not recomp_reqd
548 iface{ mi_globals = Just (tcg_rdr_env tc_result) }
551 hscBackend compiler tc_result mod_summary mb_old_hash
553 genericHscRecompile :: HsCompiler a
554 -> ModSummary -> Maybe Fingerprint
556 genericHscRecompile compiler mod_summary mb_old_hash
557 | ExtCoreFile <- ms_hsc_src mod_summary =
558 panic "GHC does not currently support reading External Core files"
560 tc_result <- hscFileFrontEnd mod_summary
561 hscBackend compiler tc_result mod_summary mb_old_hash
563 genericHscBackend :: HsCompiler a
564 -> TcGblEnv -> ModSummary -> Maybe Fingerprint
566 genericHscBackend compiler tc_result mod_summary mb_old_hash
567 | HsBootFile <- ms_hsc_src mod_summary =
568 hscGenBootOutput compiler tc_result mod_summary mb_old_hash
570 guts <- hscDesugar' mod_summary tc_result
571 hscGenOutput compiler guts mod_summary mb_old_hash
573 compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
574 compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
576 hscBackend comp tcg ms' Nothing
578 --------------------------------------------------------------
580 --------------------------------------------------------------
582 hscOneShotCompiler :: HsCompiler OneShotResult
586 hscNoRecomp = \_old_iface -> do
588 liftIO $ dumpIfaceStats hsc_env
591 , hscRecompile = genericHscRecompile hscOneShotCompiler
593 , hscBackend = \ tc_result mod_summary mb_old_hash -> do
594 dflags <- getDynFlags
595 case hscTarget dflags of
596 HscNothing -> return (HscRecomp False ())
597 _otherw -> genericHscBackend hscOneShotCompiler
598 tc_result mod_summary mb_old_hash
600 , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
601 (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
602 hscWriteIface iface changed mod_summary
603 return (HscRecomp False ())
605 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
606 guts <- hscSimplify' guts0
607 (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
608 hscWriteIface iface changed mod_summary
609 hasStub <- hscGenHardCode cgguts mod_summary
610 return (HscRecomp hasStub ())
613 -- Compile Haskell, boot and extCore in OneShot mode.
614 hscCompileOneShot :: Compiler OneShotResult
615 hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
617 -- One-shot mode needs a knot-tying mutable variable for interface
618 -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
619 type_env_var <- newIORef emptyNameEnv
621 mod = ms_mod mod_summary
622 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
624 genericHscCompile hscOneShotCompiler
625 oneShotMsg hsc_env' mod_summary src_changed
626 mb_old_iface mb_i_of_n
629 hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
630 hscOneShotBackendOnly = compilerBackend hscOneShotCompiler
632 --------------------------------------------------------------
634 hscBatchCompiler :: HsCompiler BatchResult
638 hscNoRecomp = \iface -> do
639 details <- genModDetails iface
640 return (HscNoRecomp, iface, details)
642 , hscRecompile = genericHscRecompile hscBatchCompiler
644 , hscBackend = genericHscBackend hscBatchCompiler
646 , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
647 (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
648 hscWriteIface iface changed mod_summary
649 return (HscRecomp False (), iface, details)
651 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
652 guts <- hscSimplify' guts0
653 (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
654 hscWriteIface iface changed mod_summary
655 hasStub <- hscGenHardCode cgguts mod_summary
656 return (HscRecomp hasStub (), iface, details)
659 -- Compile Haskell, boot and extCore in batch mode.
660 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
661 hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
663 hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
664 hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler
666 --------------------------------------------------------------
668 hscInteractiveCompiler :: HsCompiler InteractiveResult
669 hscInteractiveCompiler =
671 hscNoRecomp = \iface -> do
672 details <- genModDetails iface
673 return (HscNoRecomp, iface, details)
675 , hscRecompile = genericHscRecompile hscInteractiveCompiler
677 , hscBackend = genericHscBackend hscInteractiveCompiler
679 , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
680 (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
681 return (HscRecomp False Nothing, iface, details)
683 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
684 guts <- hscSimplify' guts0
685 (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
686 hscInteractive (iface, details, cgguts) mod_summary
689 -- Compile Haskell, extCore to bytecode.
690 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
691 hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
693 hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
694 hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler
696 --------------------------------------------------------------
698 hscNothingCompiler :: HsCompiler NothingResult
701 hscNoRecomp = \iface -> do
702 details <- genModDetails iface
703 return (HscNoRecomp, iface, details)
705 , hscRecompile = genericHscRecompile hscNothingCompiler
707 , hscBackend = \tc_result _mod_summary mb_old_iface -> do
709 (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
710 return (HscRecomp False (), iface, details)
712 , hscGenBootOutput = \_ _ _ ->
713 panic "hscCompileNothing: hscGenBootOutput should not be called"
715 , hscGenOutput = \_ _ _ ->
716 panic "hscCompileNothing: hscGenOutput should not be called"
719 -- Type-check Haskell and .hs-boot only (no external core)
720 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
721 hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
723 hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
724 hscNothingBackendOnly = compilerBackend hscNothingCompiler
726 --------------------------------------------------------------
728 --------------------------------------------------------------
730 genModDetails :: ModIface -> Hsc ModDetails
731 genModDetails old_iface
734 new_details <- {-# SCC "tcRnIface" #-}
735 liftIO $ initIfaceCheck hsc_env $
736 typecheckIface old_iface
737 liftIO $ dumpIfaceStats hsc_env
740 --------------------------------------------------------------
741 -- Progress displayers.
742 --------------------------------------------------------------
744 oneShotMsg :: HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ()
745 oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
748 else compilationProgressMsg (hsc_dflags hsc_env) $
749 "compilation IS NOT required"
751 batchMsg :: HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ()
752 batchMsg hsc_env mb_mod_index recomp mod_summary
754 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
755 (showModuleIndex mb_mod_index ++
756 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
758 then showMsg "Compiling "
759 else if verbosity (hsc_dflags hsc_env) >= 2
760 then showMsg "Skipping "
763 --------------------------------------------------------------
765 --------------------------------------------------------------
767 hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
768 hscFileFrontEnd mod_summary =
769 do rdr_module <- hscParse' mod_summary
771 {-# SCC "Typecheck-Rename" #-}
773 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
775 --------------------------------------------------------------
777 --------------------------------------------------------------
779 hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
780 hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts
782 hscSimplify' :: ModGuts -> Hsc ModGuts
783 hscSimplify' ds_result
784 = do hsc_env <- getHscEnv
785 {-# SCC "Core2Core" #-}
786 liftIO $ core2core hsc_env ds_result
788 --------------------------------------------------------------
789 -- Interface generators
790 --------------------------------------------------------------
792 hscSimpleIface :: TcGblEnv
794 -> Hsc (ModIface, Bool, ModDetails)
795 hscSimpleIface tc_result mb_old_iface
798 details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
799 (new_iface, no_change)
800 <- {-# SCC "MkFinalIface" #-}
802 mkIfaceTc hsc_env mb_old_iface details tc_result
803 -- And the answer is ...
804 liftIO $ dumpIfaceStats hsc_env
805 return (new_iface, no_change, details)
807 hscNormalIface :: ModGuts
809 -> Hsc (ModIface, Bool, ModDetails, CgGuts)
810 hscNormalIface simpl_result mb_old_iface
813 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
814 liftIO $ tidyProgram hsc_env simpl_result
816 -- BUILD THE NEW ModIface and ModDetails
817 -- and emit external core if necessary
818 -- This has to happen *after* code gen so that the back-end
819 -- info has been set. Not yet clear if it matters waiting
820 -- until after code output
821 (new_iface, no_change)
822 <- {-# SCC "MkFinalIface" #-}
824 mkIface hsc_env mb_old_iface details simpl_result
826 -- Emit external core
827 -- This should definitely be here and not after CorePrep,
828 -- because CorePrep produces unqualified constructor wrapper declarations,
829 -- so its output isn't valid External Core (without some preprocessing).
830 liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
831 liftIO $ dumpIfaceStats hsc_env
833 -- Return the prepared code.
834 return (new_iface, no_change, details, cg_guts)
836 --------------------------------------------------------------
837 -- BackEnd combinators
838 --------------------------------------------------------------
840 hscWriteIface :: ModIface
845 hscWriteIface iface no_change mod_summary
846 = do dflags <- getDynFlags
848 $ liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface
850 -- | Compile to hard-code.
851 hscGenHardCode :: CgGuts -> ModSummary
852 -> Hsc Bool -- ^ @True@ <=> stub.c exists
853 hscGenHardCode cgguts mod_summary
857 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
858 -- From now on, we just use the bits we need.
859 cg_module = this_mod,
860 cg_binds = core_binds,
862 cg_dir_imps = dir_imps,
863 cg_foreign = foreign_stubs,
864 cg_dep_pkgs = dependencies,
865 cg_hpc_info = hpc_info } = cgguts
866 dflags = hsc_dflags hsc_env
867 location = ms_location mod_summary
868 data_tycons = filter isDataTyCon tycons
869 -- cg_tycons includes newtypes, for the benefit of External Core,
870 -- but we don't generate any code for newtypes
873 -- PREPARE FOR CODE GENERATION
874 -- Do saturation and convert to A-normal form
875 prepd_binds <- {-# SCC "CorePrep" #-}
876 corePrepPgm dflags core_binds data_tycons ;
877 ----------------- Convert to STG ------------------
878 (stg_binds, cost_centre_info)
879 <- {-# SCC "CoreToStg" #-}
880 myCoreToStg dflags this_mod prepd_binds
882 ------------------ Code generation ------------------
884 cmms <- if dopt Opt_TryNewCodeGen dflags
885 then do cmms <- tryNewCodeGen hsc_env this_mod data_tycons
886 dir_imps cost_centre_info
889 else {-# SCC "CodeGen" #-}
890 codeGen dflags this_mod data_tycons
891 dir_imps cost_centre_info
894 --- Optionally run experimental Cmm transformations ---
895 cmms <- optionallyConvertAndOrCPS hsc_env cmms
896 -- unless certain dflags are on, the identity function
897 ------------------ Code output -----------------------
898 rawcmms <- cmmToRawCmm cmms
899 dumpIfSet_dyn dflags Opt_D_dump_cmmz "Raw Cmm" (ppr rawcmms)
900 (_stub_h_exists, stub_c_exists)
901 <- codeOutput dflags this_mod location foreign_stubs
905 hscInteractive :: (ModIface, ModDetails, CgGuts)
907 -> Hsc (InteractiveStatus, ModIface, ModDetails)
909 hscInteractive (iface, details, cgguts) mod_summary
911 dflags <- getDynFlags
912 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
913 -- From now on, we just use the bits we need.
914 cg_module = this_mod,
915 cg_binds = core_binds,
917 cg_foreign = foreign_stubs,
918 cg_modBreaks = mod_breaks } = cgguts
920 location = ms_location mod_summary
921 data_tycons = filter isDataTyCon tycons
922 -- cg_tycons includes newtypes, for the benefit of External Core,
923 -- but we don't generate any code for newtypes
926 -- PREPARE FOR CODE GENERATION
927 -- Do saturation and convert to A-normal form
928 prepd_binds <- {-# SCC "CorePrep" #-}
929 liftIO $ corePrepPgm dflags core_binds data_tycons ;
930 ----------------- Generate byte code ------------------
931 comp_bc <- liftIO $ byteCodeGen dflags prepd_binds data_tycons mod_breaks
932 ------------------ Create f-x-dynamic C-side stuff ---
933 (_istub_h_exists, istub_c_exists)
934 <- liftIO $ outputForeignStubs dflags this_mod
935 location foreign_stubs
936 return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks))
939 hscInteractive _ _ = panic "GHC not compiled with interpreter"
942 ------------------------------
944 hscCompileCmmFile :: HscEnv -> FilePath -> IO ()
945 hscCompileCmmFile hsc_env filename
946 = runHsc hsc_env $ do
947 let dflags = hsc_dflags hsc_env
948 cmm <- ioMsgMaybe $ parseCmmFile dflags filename
950 cmms <- optionallyConvertAndOrCPS hsc_env [cmm]
951 rawCmms <- cmmToRawCmm cmms
952 _ <- codeOutput dflags no_mod no_loc NoStubs [] rawCmms
955 no_mod = panic "hscCmmFile: no_mod"
956 no_loc = ModLocation{ ml_hs_file = Just filename,
957 ml_hi_file = panic "hscCmmFile: no hi file",
958 ml_obj_file = panic "hscCmmFile: no obj file" }
960 -------------------- Stuff for new code gen ---------------------
962 tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> [Module]
964 -> [(StgBinding,[(Id,[Id])])]
967 tryNewCodeGen hsc_env this_mod data_tycons imported_mods
968 cost_centre_info stg_binds hpc_info =
969 do { let dflags = hsc_dflags hsc_env
970 ; prog <- StgCmm.codeGen dflags this_mod data_tycons imported_mods
971 cost_centre_info stg_binds hpc_info
972 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen"
975 ; prog <- return $ map runCmmContFlowOpts prog
976 -- Control flow optimisation
978 -- We are building a single SRT for the entire module, so
979 -- we must thread it through all the procedures as we cps-convert them.
980 ; us <- mkSplitUniqSupply 'S'
981 ; let topSRT = initUs_ us emptySRT
982 ; (topSRT, prog) <- foldM (protoCmmCPS hsc_env) (topSRT, []) prog
983 -- The main CPS conversion
985 ; prog <- return $ map runCmmContFlowOpts (srtToData topSRT : prog)
986 -- Control flow optimisation, again
988 ; let prog' = map cmmOfZgraph prog
989 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (ppr prog')
993 optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
994 optionallyConvertAndOrCPS hsc_env cmms =
995 do let dflags = hsc_dflags hsc_env
996 -------- Optionally convert to and from zipper ------
997 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
998 then mapM (testCmmConversion hsc_env) cmms
1003 testCmmConversion :: HscEnv -> Cmm -> IO Cmm
1004 testCmmConversion hsc_env cmm =
1005 do let dflags = hsc_dflags hsc_env
1006 showPass dflags "CmmToCmm"
1007 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
1008 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
1009 us <- mkSplitUniqSupply 'C'
1010 let cvtm = runCmmContFlowOpts `liftM` cmmToZgraph cmm
1011 let zgraph = initUs_ us cvtm
1012 us <- mkSplitUniqSupply 'S'
1013 let topSRT = initUs_ us emptySRT
1014 (_, [cps_zgraph]) <- protoCmmCPS hsc_env (topSRT, []) zgraph
1015 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
1016 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
1017 showPass dflags "Convert from Z back to Cmm"
1018 let cvt = cmmOfZgraph $ runCmmContFlowOpts $ chosen_graph
1019 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
1022 myCoreToStg :: DynFlags -> Module -> [CoreBind]
1023 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
1024 , CollectedCCs) -- cost centre info (declared and used)
1026 myCoreToStg dflags this_mod prepd_binds
1028 stg_binds <- {-# SCC "Core2Stg" #-}
1029 coreToStg (thisPackage dflags) prepd_binds
1031 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
1032 stg2stg dflags this_mod stg_binds
1034 return (stg_binds2, cost_centre_info)
1038 %************************************************************************
1040 \subsection{Compiling a do-statement}
1042 %************************************************************************
1044 When the UnlinkedBCOExpr is linked you get an HValue of type
1046 When you run it you get a list of HValues that should be
1047 the same length as the list of names; add them to the ClosureEnv.
1049 A naked expression returns a singleton Name [it].
1051 What you type The IO [HValue] that hscStmt returns
1052 ------------- ------------------------------------
1053 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
1056 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
1059 expr (of IO type) ==> expr >>= \ v -> return [v]
1060 [NB: result not printed] bindings: [it]
1063 expr (of non-IO type,
1064 result showable) ==> let v = expr in print v >> return [v]
1067 expr (of non-IO type,
1068 result not showable) ==> error
1072 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
1074 -> String -- The statement
1075 -> IO (Maybe ([Id], HValue))
1076 -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
1077 hscStmt hsc_env stmt = runHsc hsc_env $ do
1078 maybe_stmt <- hscParseStmt stmt
1080 Nothing -> return Nothing
1081 Just parsed_stmt -> do -- The real stuff
1083 -- Rename and typecheck it
1084 let icontext = hsc_IC hsc_env
1085 (ids, tc_expr) <- ioMsgMaybe $
1086 tcRnStmt hsc_env icontext parsed_stmt
1088 let rdr_env = ic_rn_gbl_env icontext
1089 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
1090 ds_expr <- ioMsgMaybe $
1091 deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
1094 -- Then desugar, code gen, and link it
1095 let src_span = srcLocSpan interactiveSrcLoc
1096 hsc_env <- getHscEnv
1097 hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
1099 return $ Just (ids, hval)
1101 hscImport :: HscEnv -> String -> IO (ImportDecl RdrName)
1102 hscImport hsc_env str = runHsc hsc_env $ do
1103 (L _ (HsModule{hsmodImports=is})) <-
1104 hscParseThing parseModule str
1106 [i] -> return (unLoc i)
1107 _ -> liftIO $ throwOneError $
1108 mkPlainErrMsg noSrcSpan $
1109 ptext (sLit "parse error in import declaration")
1111 hscTcExpr -- Typecheck an expression (but don't run it)
1113 -> String -- The expression
1116 hscTcExpr hsc_env expr = runHsc hsc_env $ do
1117 maybe_stmt <- hscParseStmt expr
1119 Just (L _ (ExprStmt expr _ _)) ->
1120 ioMsgMaybe $ tcRnExpr hsc_env (hsc_IC hsc_env) expr
1122 liftIO $ throwIO $ mkSrcErr $ unitBag $
1123 mkPlainErrMsg noSrcSpan
1124 (text "not an expression:" <+> quotes (text expr))
1126 -- | Find the kind of a type
1129 -> String -- ^ The type
1132 hscKcType hsc_env str = runHsc hsc_env $ do
1133 ty <- hscParseType str
1134 ioMsgMaybe $ tcRnType hsc_env (hsc_IC hsc_env) ty
1141 hscParseStmt :: String -> Hsc (Maybe (LStmt RdrName))
1142 hscParseStmt = hscParseThing parseStmt
1144 hscParseType :: String -> Hsc (LHsType RdrName)
1145 hscParseType = hscParseThing parseType
1148 hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
1149 hscParseIdentifier hsc_env str = runHsc hsc_env $
1150 hscParseThing parseIdentifier str
1153 hscParseThing :: (Outputable thing)
1158 hscParseThing parser str
1159 = {-# SCC "Parser" #-} do
1160 dflags <- getDynFlags
1161 liftIO $ showPass dflags "Parser"
1163 let buf = stringToStringBuffer str
1164 loc = mkSrcLoc (fsLit "<interactive>") 1 1
1166 case unP parser (mkPState dflags buf loc) of
1168 PFailed span err -> do
1169 let msg = mkPlainErrMsg span err
1170 liftIO $ throwIO (mkSrcErr (unitBag msg))
1173 logWarningsReportErrors (getMessages pst)
1174 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
1179 hscCompileCore :: HscEnv
1185 hscCompileCore hsc_env simplify mod_summary binds
1186 = runHsc hsc_env $ do
1187 let maybe_simplify mod_guts | simplify = hscSimplify' mod_guts
1188 | otherwise = return mod_guts
1189 guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) binds)
1190 (iface, changed, _details, cgguts) <- hscNormalIface guts Nothing
1191 hscWriteIface iface changed mod_summary
1192 _ <- hscGenHardCode cgguts mod_summary
1195 -- Makes a "vanilla" ModGuts.
1196 mkModGuts :: Module -> [CoreBind] -> ModGuts
1197 mkModGuts mod binds = ModGuts {
1201 mg_deps = noDependencies,
1202 mg_dir_imps = emptyModuleEnv,
1203 mg_used_names = emptyNameSet,
1204 mg_rdr_env = emptyGlobalRdrEnv,
1205 mg_fix_env = emptyFixityEnv,
1206 mg_types = emptyTypeEnv,
1211 mg_foreign = NoStubs,
1212 mg_warns = NoWarnings,
1214 mg_hpc_info = emptyHpcInfo False,
1215 mg_modBreaks = emptyModBreaks,
1216 mg_vect_info = noVectInfo,
1217 mg_inst_env = emptyInstEnv,
1218 mg_fam_inst_env = emptyFamInstEnv
1222 %************************************************************************
1224 Desugar, simplify, convert to bytecode, and link an expression
1226 %************************************************************************
1230 hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
1231 hscCompileCoreExpr hsc_env srcspan ds_expr
1233 = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler")
1234 -- Otherwise you get a seg-fault when you run it
1237 let dflags = hsc_dflags hsc_env
1238 let lint_on = dopt Opt_DoCoreLinting dflags
1241 simpl_expr <- simplifyExpr dflags ds_expr
1243 -- Tidy it (temporary, until coreSat does cloning)
1244 let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1246 -- Prepare for codegen
1247 prepd_expr <- corePrepExpr dflags tidy_expr
1249 -- Lint if necessary
1250 -- ToDo: improve SrcLoc
1252 let ictxt = hsc_IC hsc_env
1253 tyvars = varSetElems (tyVarsOfTypes (map idType (ic_tmp_ids ictxt)))
1255 case lintUnfolding noSrcLoc tyvars prepd_expr of
1256 Just err -> pprPanic "hscCompileCoreExpr" err
1257 Nothing -> return ()
1260 bcos <- coreExprToBCOs dflags prepd_expr
1263 hval <- linkExpr hsc_env srcspan bcos
1270 %************************************************************************
1272 Statistics on reading interfaces
1274 %************************************************************************
1277 dumpIfaceStats :: HscEnv -> IO ()
1278 dumpIfaceStats hsc_env
1279 = do { eps <- readIORef (hsc_EPS hsc_env)
1280 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1281 "Interface statistics"
1284 dflags = hsc_dflags hsc_env
1285 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1286 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1289 %************************************************************************
1291 Progress Messages: Module i of n
1293 %************************************************************************
1296 showModuleIndex :: Maybe (Int, Int) -> String
1297 showModuleIndex Nothing = ""
1298 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1302 padded = replicate (length n_str - length i_str) ' ' ++ i_str