1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2005
7 -----------------------------------------------------------------------------
9 module DriverPipeline (
10 -- Run a series of compilation steps in a pipeline, for a
11 -- collection of source files.
14 -- Interfaces for the batch-mode driver
17 -- Interfaces for the compilation manager (interpreted/batch-mode)
19 compile, CompResult(..),
25 getOptionsFromStringBuffer, -- used in module GHC
28 #include "HsVersions.h"
33 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
34 import qualified SysTools
42 import StaticFlags ( v_Ld_inputs, opt_Static, WayName(..) )
44 import RdrName ( GlobalRdrEnv )
47 import StringBuffer ( hGetStringBuffer )
48 import BasicTypes ( SuccessFlag(..) )
49 import Maybes ( expectJust )
50 import Ctype ( is_ident )
51 import StringBuffer ( StringBuffer(..), lexemeToString )
52 import ParserCoreUtils ( getCoreModuleName )
55 import DATA_IOREF ( readIORef, writeIORef, IORef )
56 import GLAEXTS ( Int(..) )
65 -- ---------------------------------------------------------------------------
68 -- Just preprocess a file, put the result in a temp. file (used by the
69 -- compilation manager during the summary phase).
71 -- We return the augmented DynFlags, because they contain the result
72 -- of slurping in the OPTIONS pragmas
74 preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
75 preprocess dflags filename =
76 ASSERT2(isHaskellSrcFilename filename, text filename)
77 runPipeline anyHsc dflags filename Temporary Nothing{-no ModLocation-}
79 -- ---------------------------------------------------------------------------
82 -- Compile a single module, under the control of the compilation manager.
84 -- This is the interface between the compilation manager and the
85 -- compiler proper (hsc), where we deal with tedious details like
86 -- reading the OPTIONS pragma from the source file, and passing the
87 -- output of hsc through the C compiler.
89 -- NB. No old interface can also mean that the source has changed.
92 -> (Messages -> IO ()) -- error message callback
94 -> Maybe Linkable -- Just linkable <=> source unchanged
95 -> Maybe ModIface -- Old interface, if available
99 = CompOK ModDetails -- New details
100 ModIface -- New iface
101 (Maybe Linkable) -- a Maybe, for the same reasons as hm_linkable
106 compile hsc_env msg_act mod_summary maybe_old_linkable old_iface = do
108 let dflags0 = hsc_dflags hsc_env
109 this_mod = ms_mod mod_summary
110 src_flavour = ms_hsc_src mod_summary
113 | Just l <- maybe_old_linkable, isObjectLinkable l = True
116 showPass dflags0 ("Compiling " ++ showModMsg have_object mod_summary)
118 let location = ms_location mod_summary
119 let input_fn = expectJust "compile:hs" (ml_hs_file location)
120 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
122 debugTraceMsg dflags0 2 ("compile: input file " ++ input_fnpp)
124 -- Add in the OPTIONS from the source file
125 -- This is nasty: we've done this once already, in the compilation manager
126 -- It might be better to cache the flags in the ml_hspp_file field,say
127 let hspp_buf = expectJust "compile:hspp_buf" (ms_hspp_buf mod_summary)
128 opts = getOptionsFromStringBuffer hspp_buf
129 (dflags1,unhandled_flags) <- parseDynamicFlags dflags0 opts
130 checkProcessArgsResult unhandled_flags input_fn
132 let (basename, _) = splitFilename input_fn
134 -- We add the directory in which the .hs files resides) to the import path.
135 -- This is needed when we try to compile the .hc file later, if it
136 -- imports a _stub.h file that we created here.
137 let current_dir = directoryOf basename
138 old_paths = includePaths dflags1
139 dflags = dflags1 { includePaths = current_dir : old_paths }
141 -- Figure out what lang we're generating
142 let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
143 -- ... and what the next phase should be
144 let next_phase = hscNextPhase dflags src_flavour hsc_lang
145 -- ... and what file to generate the output into
146 output_fn <- getOutputFilename dflags next_phase
147 Temporary basename next_phase (Just location)
149 let dflags' = dflags { hscTarget = hsc_lang,
150 hscOutName = output_fn,
151 hscStubCOutName = basename ++ "_stub.c",
152 hscStubHOutName = basename ++ "_stub.h",
153 extCoreName = basename ++ ".hcr" }
155 -- -no-recomp should also work with --make
156 let do_recomp = dopt Opt_RecompChecking dflags
157 source_unchanged = isJust maybe_old_linkable && do_recomp
158 hsc_env' = hsc_env { hsc_dflags = dflags' }
161 hsc_result <- hscMain hsc_env' msg_act mod_summary
162 source_unchanged have_object old_iface
165 HscFail -> return CompErrs
167 HscNoRecomp details iface ->
168 ASSERT(isJust maybe_old_linkable)
169 return (CompOK details iface maybe_old_linkable)
171 HscRecomp details iface
172 stub_h_exists stub_c_exists maybe_interpreted_code
174 | isHsBoot src_flavour -- No further compilation to do
175 -> return (CompOK details iface Nothing)
177 | otherwise -- Normal Haskell source files
179 maybe_stub_o <- compileStub dflags' stub_c_exists
180 let stub_unlinked = case maybe_stub_o of
182 Just stub_o -> [ DotO stub_o ]
184 (hs_unlinked, unlinked_time) <-
187 -- in interpreted mode, just return the compiled code
188 -- as our "unlinked" object.
190 case maybe_interpreted_code of
192 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
193 -- Why do we use the timestamp of the source file here,
194 -- rather than the current time? This works better in
195 -- the case where the local clock is out of sync
196 -- with the filesystem's clock. It's just as accurate:
197 -- if the source is modified, then the linkable will
200 Nothing -> panic "compile: no interpreted code"
202 -- we're in batch mode: finish the compilation pipeline.
204 let object_filename = ml_obj_file location
206 runPipeline StopLn dflags output_fn Persistent
208 -- the object filename comes from the ModLocation
210 o_time <- getModificationTime object_filename
211 return ([DotO object_filename], o_time)
213 let linkable = LM unlinked_time this_mod
214 (hs_unlinked ++ stub_unlinked)
216 return (CompOK details iface (Just linkable))
218 -----------------------------------------------------------------------------
219 -- stub .h and .c files (for foreign export support)
221 compileStub dflags stub_c_exists
222 | not stub_c_exists = return Nothing
224 -- compile the _stub.c file w/ gcc
225 let stub_c = hscStubCOutName dflags
226 (_, stub_o) <- runPipeline StopLn dflags
227 stub_c Persistent Nothing{-no ModLocation-}
231 -- ---------------------------------------------------------------------------
234 link :: GhcMode -- interactive or batch
235 -> DynFlags -- dynamic flags
236 -> Bool -- attempt linking in batch mode?
237 -> HomePackageTable -- what to link
240 -- For the moment, in the batch linker, we don't bother to tell doLink
241 -- which packages to link -- it just tries all that are available.
242 -- batch_attempt_linking should only be *looked at* in batch mode. It
243 -- should only be True if the upsweep was successful and someone
244 -- exports main, i.e., we have good reason to believe that linking
248 link Interactive dflags batch_attempt_linking hpt
249 = do -- Not Linking...(demand linker will do the job)
253 link JustTypecheck dflags batch_attempt_linking hpt
256 link BatchCompile dflags batch_attempt_linking hpt
257 | batch_attempt_linking
260 home_mod_infos = moduleEnvElts hpt
262 -- the packages we depend on
263 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
265 -- the linkables to link
266 linkables = map (fromJust.hm_linkable) home_mod_infos
268 debugTraceMsg dflags 3 "link: linkables are ..."
269 debugTraceMsg dflags 3 (showSDoc (vcat (map ppr linkables)))
271 -- check for the -no-link flag
272 if isNoLink (ghcLink dflags)
273 then do debugTraceMsg dflags 3 "link(batch): linking omitted (-c flag given)."
277 debugTraceMsg dflags 1 "Linking ..."
279 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
280 obj_files = concatMap getOfiles linkables
282 -- Don't showPass in Batch mode; doLink will do that for us.
283 staticLink dflags obj_files pkg_deps
285 debugTraceMsg dflags 3 "link: done"
287 -- staticLink only returns if it succeeds
291 = do debugTraceMsg dflags 3 "link(batch): upsweep (partially) failed OR"
292 debugTraceMsg dflags 3 " Main.main not exported; not linking."
296 -- -----------------------------------------------------------------------------
297 -- Compile files in one-shot mode.
299 oneShot :: DynFlags -> Phase -> [String] -> IO ()
300 oneShot dflags stop_phase srcs = do
301 o_files <- mapM (compileFile dflags stop_phase) srcs
302 doLink dflags stop_phase o_files
304 compileFile :: DynFlags -> Phase -> FilePath -> IO FilePath
305 compileFile dflags stop_phase src = do
306 exists <- doesFileExist src
308 throwDyn (CmdLineError ("does not exist: " ++ src))
311 split = dopt Opt_SplitObjs dflags
312 mb_o_file = outputFile dflags
313 ghc_link = ghcLink dflags -- Set by -c or -no-link
315 -- When linking, the -o argument refers to the linker's output.
316 -- otherwise, we use it as the name for the pipeline's output.
318 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
319 -- -o foo applies to linker
320 | Just o_file <- mb_o_file = SpecificFile o_file
321 -- -o foo applies to the file we are compiling now
322 | otherwise = Persistent
324 stop_phase' = case stop_phase of
325 As | split -> SplitAs
328 (_, out_file) <- runPipeline stop_phase' dflags
329 src output Nothing{-no ModLocation-}
333 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
334 doLink dflags stop_phase o_files
335 | not (isStopLn stop_phase)
336 = return () -- We stopped before the linking phase
339 = case ghcLink dflags of
341 StaticLink -> staticLink dflags o_files link_pkgs
342 MkDLL -> doMkDLL dflags o_files link_pkgs
344 -- Always link in the haskell98 package for static linking. Other
345 -- packages have to be specified via the -package flag.
347 | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
351 -- ---------------------------------------------------------------------------
352 -- Run a compilation pipeline, consisting of multiple phases.
354 -- This is the interface to the compilation pipeline, which runs
355 -- a series of compilation steps on a single source file, specifying
356 -- at which stage to stop.
358 -- The DynFlags can be modified by phases in the pipeline (eg. by
359 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
364 -- output should be to a temporary file: we're going to
365 -- run more compilation steps on this output later
367 -- we want a persistent file, i.e. a file in the current directory
368 -- derived from the input filename, but with the appropriate extension.
369 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
370 | SpecificFile FilePath
371 -- the output must go into the specified file.
374 :: Phase -- When to stop
375 -> DynFlags -- Dynamic flags
376 -> FilePath -- Input filename
377 -> PipelineOutput -- Output filename
378 -> Maybe ModLocation -- A ModLocation, if this is a Haskell module
379 -> IO (DynFlags, FilePath) -- (final flags, output filename)
381 runPipeline stop_phase dflags input_fn output maybe_loc
383 let (basename, suffix) = splitFilename input_fn
384 start_phase = startPhase suffix
386 -- We want to catch cases of "you can't get there from here" before
387 -- we start the pipeline, because otherwise it will just run off the
390 -- There is a partial ordering on phases, where A < B iff A occurs
391 -- before B in a normal compilation pipeline.
393 when (not (start_phase `happensBefore` stop_phase)) $
395 ("cannot compile this file to desired target: "
398 -- this is a function which will be used to calculate output file names
399 -- as we go along (we partially apply it to some of its inputs here)
400 let get_output_fn = getOutputFilename dflags stop_phase output basename
402 -- Execute the pipeline...
403 (dflags', output_fn, maybe_loc) <-
404 pipeLoop dflags start_phase stop_phase input_fn
405 basename suffix get_output_fn maybe_loc
407 -- Sometimes, a compilation phase doesn't actually generate any output
408 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
409 -- stage, but we wanted to keep the output, then we have to explicitly
413 return (dflags', output_fn)
415 do final_fn <- get_output_fn stop_phase maybe_loc
416 when (final_fn /= output_fn) $
417 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
418 ++ "'") output_fn final_fn
419 return (dflags', final_fn)
423 pipeLoop :: DynFlags -> Phase -> Phase
424 -> FilePath -> String -> Suffix
425 -> (Phase -> Maybe ModLocation -> IO FilePath)
427 -> IO (DynFlags, FilePath, Maybe ModLocation)
429 pipeLoop dflags phase stop_phase
430 input_fn orig_basename orig_suff
431 orig_get_output_fn maybe_loc
433 | phase `eqPhase` stop_phase -- All done
434 = return (dflags, input_fn, maybe_loc)
436 | not (phase `happensBefore` stop_phase)
437 -- Something has gone wrong. We'll try to cover all the cases when
438 -- this could happen, so if we reach here it is a panic.
439 -- eg. it might happen if the -C flag is used on a source file that
440 -- has {-# OPTIONS -fasm #-}.
441 = panic ("pipeLoop: at phase " ++ show phase ++
442 " but I wanted to stop at phase " ++ show stop_phase)
445 = do { (next_phase, dflags', maybe_loc, output_fn)
446 <- runPhase phase stop_phase dflags orig_basename
447 orig_suff input_fn orig_get_output_fn maybe_loc
448 ; pipeLoop dflags' next_phase stop_phase output_fn
449 orig_basename orig_suff orig_get_output_fn maybe_loc }
452 :: DynFlags -> Phase -> PipelineOutput -> String
453 -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
454 getOutputFilename dflags stop_phase output basename
458 odir = outputDir dflags
459 osuf = objectSuf dflags
460 keep_hc = dopt Opt_KeepHcFiles dflags
461 keep_raw_s = dopt Opt_KeepRawSFiles dflags
462 keep_s = dopt Opt_KeepSFiles dflags
464 myPhaseInputExt HCc = hcsuf
465 myPhaseInputExt StopLn = osuf
466 myPhaseInputExt other = phaseInputExt other
468 func next_phase maybe_location
469 | is_last_phase, Persistent <- output = persistent_fn
470 | is_last_phase, SpecificFile f <- output = return f
471 | keep_this_output = persistent_fn
472 | otherwise = newTempName dflags suffix
474 is_last_phase = next_phase `eqPhase` stop_phase
476 -- sometimes, we keep output from intermediate stages
480 Mangle | keep_raw_s -> True
482 HCc | keep_hc -> True
485 suffix = myPhaseInputExt next_phase
487 -- persistent object files get put in odir
489 | StopLn <- next_phase = return odir_persistent
490 | otherwise = return persistent
492 persistent = basename ++ '.':suffix
495 | Just loc <- maybe_location = ml_obj_file loc
496 | Just d <- odir = replaceFilenameDirectory persistent d
497 | otherwise = persistent
500 -- -----------------------------------------------------------------------------
501 -- Each phase in the pipeline returns the next phase to execute, and the
502 -- name of the file in which the output was placed.
504 -- We must do things dynamically this way, because we often don't know
505 -- what the rest of the phases will be until part-way through the
506 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
507 -- of a source file can change the latter stages of the pipeline from
508 -- taking the via-C route to using the native code generator.
510 runPhase :: Phase -- Do this phase first
511 -> Phase -- Stop just before this phase
513 -> String -- basename of original input source
514 -> String -- its extension
515 -> FilePath -- name of file which contains the input to this phase.
516 -> (Phase -> Maybe ModLocation -> IO FilePath)
517 -- how to calculate the output filename
518 -> Maybe ModLocation -- the ModLocation, if we have one
519 -> IO (Phase, -- next phase
520 DynFlags, -- new dynamic flags
521 Maybe ModLocation, -- the ModLocation, if we have one
522 FilePath) -- output filename
524 -- Invariant: the output filename always contains the output
525 -- Interesting case: Hsc when there is no recompilation to do
526 -- Then the output filename is still a .o file
528 -------------------------------------------------------------------------------
531 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
532 = do let unlit_flags = getOpts dflags opt_L
533 -- The -h option passes the file name for unlit to put in a #line directive
534 output_fn <- get_output_fn (Cpp sf) maybe_loc
536 SysTools.runUnlit dflags
537 (map SysTools.Option unlit_flags ++
538 [ SysTools.Option "-h"
539 , SysTools.Option input_fn
540 , SysTools.FileOption "" input_fn
541 , SysTools.FileOption "" output_fn
544 return (Cpp sf, dflags, maybe_loc, output_fn)
546 -------------------------------------------------------------------------------
547 -- Cpp phase : (a) gets OPTIONS out of file
548 -- (b) runs cpp if necessary
550 runPhase (Cpp sf) _stop dflags0 basename suff input_fn get_output_fn maybe_loc
551 = do src_opts <- getOptionsFromSource input_fn
552 (dflags,unhandled_flags) <- parseDynamicFlags dflags0 src_opts
553 checkProcessArgsResult unhandled_flags (basename++'.':suff)
555 if not (dopt Opt_Cpp dflags) then
556 -- no need to preprocess CPP, just pass input file along
557 -- to the next phase of the pipeline.
558 return (HsPp sf, dflags, maybe_loc, input_fn)
560 output_fn <- get_output_fn (HsPp sf) maybe_loc
561 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
562 return (HsPp sf, dflags, maybe_loc, output_fn)
564 -------------------------------------------------------------------------------
567 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
568 = do if not (dopt Opt_Pp dflags) then
569 -- no need to preprocess, just pass input file along
570 -- to the next phase of the pipeline.
571 return (Hsc sf, dflags, maybe_loc, input_fn)
573 let hspp_opts = getOpts dflags opt_F
574 let orig_fn = basename ++ '.':suff
575 output_fn <- get_output_fn (Hsc sf) maybe_loc
576 SysTools.runPp dflags
577 ( [ SysTools.Option orig_fn
578 , SysTools.Option input_fn
579 , SysTools.FileOption "" output_fn
581 map SysTools.Option hspp_opts
583 return (Hsc sf, dflags, maybe_loc, output_fn)
585 -----------------------------------------------------------------------------
588 -- Compilation of a single module, in "legacy" mode (_not_ under
589 -- the direction of the compilation manager).
590 runPhase (Hsc src_flavour) stop dflags0 basename suff input_fn get_output_fn _maybe_loc
591 = do -- normal Hsc mode, not mkdependHS
593 -- we add the current directory (i.e. the directory in which
594 -- the .hs files resides) to the import path, since this is
595 -- what gcc does, and it's probably what you want.
596 let current_dir = directoryOf basename
598 paths = includePaths dflags0
599 dflags = dflags0 { includePaths = current_dir : paths }
601 -- gather the imports and module name
602 (hspp_buf,mod_name) <-
604 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
605 ; m <- getCoreModuleName input_fn
606 ; return (Nothing, mkModule m) }
608 other -> do { buf <- hGetStringBuffer input_fn
609 ; (_,_,mod_name) <- getImports dflags buf input_fn
610 ; return (Just buf, mod_name) }
612 -- Build a ModLocation to pass to hscMain.
613 -- The source filename is rather irrelevant by now, but it's used
614 -- by hscMain for messages. hscMain also needs
615 -- the .hi and .o filenames, and this is as good a way
616 -- as any to generate them, and better than most. (e.g. takes
617 -- into accout the -osuf flags)
618 location1 <- mkHomeModLocation2 dflags mod_name basename suff
620 -- Boot-ify it if necessary
621 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
622 | otherwise = location1
625 -- Take -ohi into account if present
626 -- This can't be done in mkHomeModuleLocation because
627 -- it only applies to the module being compiles
628 let ohi = outputHi dflags
629 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
630 | otherwise = location2
632 -- Take -o into account if present
633 -- Very like -ohi, but we must *only* do this if we aren't linking
634 -- (If we're linking then the -o applies to the linked thing, not to
635 -- the object file for one module.)
636 -- Note the nasty duplication with the same computation in compileFile above
637 let expl_o_file = outputFile dflags
638 location4 | Just ofile <- expl_o_file
639 , isNoLink (ghcLink dflags)
640 = location3 { ml_obj_file = ofile }
641 | otherwise = location3
643 -- Make the ModSummary to hand to hscMain
644 src_timestamp <- getModificationTime (basename ++ '.':suff)
646 unused_field = panic "runPhase:ModSummary field"
647 -- Some fields are not looked at by hscMain
648 mod_summary = ModSummary { ms_mod = mod_name,
649 ms_hsc_src = src_flavour,
650 ms_hspp_file = Just input_fn,
651 ms_hspp_buf = hspp_buf,
652 ms_location = location4,
653 ms_hs_date = src_timestamp,
654 ms_obj_date = Nothing,
655 ms_imps = unused_field,
656 ms_srcimps = unused_field }
658 o_file = ml_obj_file location4 -- The real object file
661 -- Figure out if the source has changed, for recompilation avoidance.
663 -- Setting source_unchanged to True means that M.o seems
664 -- to be up to date wrt M.hs; so no need to recompile unless imports have
665 -- changed (which the compiler itself figures out).
666 -- Setting source_unchanged to False tells the compiler that M.o is out of
667 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
668 let do_recomp = dopt Opt_RecompChecking dflags
670 if not do_recomp || not (isStopLn stop)
671 -- Set source_unchanged to False unconditionally if
672 -- (a) recompilation checker is off, or
673 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
675 -- Otherwise look at file modification dates
676 else do o_file_exists <- doesFileExist o_file
678 then return False -- Need to recompile
679 else do t2 <- getModificationTime o_file
680 if t2 > src_timestamp
685 let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
686 let next_phase = hscNextPhase dflags src_flavour hsc_lang
687 output_fn <- get_output_fn next_phase (Just location4)
689 let dflags' = dflags { hscTarget = hsc_lang,
690 hscOutName = output_fn,
691 hscStubCOutName = basename ++ "_stub.c",
692 hscStubHOutName = basename ++ "_stub.h",
693 extCoreName = basename ++ ".hcr" }
695 hsc_env <- newHscEnv dflags'
697 -- Tell the finder cache about this module
698 addHomeModuleToFinder hsc_env mod_name location4
701 result <- hscMain hsc_env printErrorsAndWarnings
702 mod_summary source_unchanged
703 False -- No object file
708 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
710 HscNoRecomp details iface -> do
711 SysTools.touch dflags' "Touching object file" o_file
712 return (StopLn, dflags', Just location4, o_file)
714 HscRecomp _details _iface
715 stub_h_exists stub_c_exists
716 _maybe_interpreted_code -> do
719 maybe_stub_o <- compileStub dflags' stub_c_exists
722 Just stub_o -> consIORef v_Ld_inputs stub_o
724 -- In the case of hs-boot files, generate a dummy .o-boot
725 -- stamp file for the benefit of Make
727 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
730 return (next_phase, dflags', Just location4, output_fn)
732 -----------------------------------------------------------------------------
735 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
737 output_fn <- get_output_fn Cmm maybe_loc
738 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
739 return (Cmm, dflags, maybe_loc, output_fn)
741 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
743 let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
744 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
745 output_fn <- get_output_fn next_phase maybe_loc
747 let dflags' = dflags { hscTarget = hsc_lang,
748 hscOutName = output_fn,
749 hscStubCOutName = basename ++ "_stub.c",
750 hscStubHOutName = basename ++ "_stub.h",
751 extCoreName = basename ++ ".hcr" }
753 ok <- hscCmmFile dflags' input_fn
755 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
757 return (next_phase, dflags, maybe_loc, output_fn)
759 -----------------------------------------------------------------------------
762 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
763 -- way too many hacks, and I can't say I've ever used it anyway.
765 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
766 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
767 = do let cc_opts = getOpts dflags opt_c
768 hcc = cc_phase `eqPhase` HCc
770 let cmdline_include_paths = includePaths dflags
772 -- HC files have the dependent packages stamped into them
773 pkgs <- if hcc then getHCFilePackages input_fn else return []
775 -- add package include paths even if we're just compiling .c
776 -- files; this is the Value Add(TM) that using ghc instead of
778 pkg_include_dirs <- getPackageIncludePath dflags pkgs
779 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
780 (cmdline_include_paths ++ pkg_include_dirs)
782 let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
783 let pic_c_flags = picCCOpts dflags
785 let verb = getVerbFlag dflags
787 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
789 let split_objs = dopt Opt_SplitObjs dflags
790 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
793 let excessPrecision = dopt Opt_ExcessPrecision dflags
797 let mangle = dopt Opt_DoAsmMangling dflags
799 | hcc && mangle = Mangle
801 output_fn <- get_output_fn next_phase maybe_loc
803 -- force the C compiler to interpret this file as C when
804 -- compiling .hc files, by adding the -x c option.
805 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
808 SysTools.runCc dflags (langopt ++
809 [ SysTools.FileOption "" input_fn
810 , SysTools.Option "-o"
811 , SysTools.FileOption "" output_fn
813 ++ map SysTools.Option (
819 ++ [ verb, "-S", "-Wimplicit", "-O" ]
820 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
823 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
828 return (next_phase, dflags, maybe_loc, output_fn)
830 -- ToDo: postprocess the output from gcc
832 -----------------------------------------------------------------------------
835 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
836 = do let mangler_opts = getOpts dflags opt_m
839 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
841 machdep_opts <- return []
844 let split = dopt Opt_SplitObjs dflags
846 | split = SplitMangle
848 output_fn <- get_output_fn next_phase maybe_loc
850 SysTools.runMangle dflags (map SysTools.Option mangler_opts
851 ++ [ SysTools.FileOption "" input_fn
852 , SysTools.FileOption "" output_fn
854 ++ map SysTools.Option machdep_opts)
856 return (next_phase, dflags, maybe_loc, output_fn)
858 -----------------------------------------------------------------------------
861 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
862 = do -- tmp_pfx is the prefix used for the split .s files
863 -- We also use it as the file to contain the no. of split .s files (sigh)
864 split_s_prefix <- SysTools.newTempName dflags "split"
865 let n_files_fn = split_s_prefix
867 SysTools.runSplit dflags
868 [ SysTools.FileOption "" input_fn
869 , SysTools.FileOption "" split_s_prefix
870 , SysTools.FileOption "" n_files_fn
873 -- Save the number of split files for future references
874 s <- readFile n_files_fn
875 let n_files = read s :: Int
876 writeIORef v_Split_info (split_s_prefix, n_files)
878 -- Remember to delete all these files
879 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
882 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
883 -- we don't use the filename
885 -----------------------------------------------------------------------------
888 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
889 = do let as_opts = getOpts dflags opt_a
890 let cmdline_include_paths = includePaths dflags
892 output_fn <- get_output_fn StopLn maybe_loc
894 -- we create directories for the object file, because it
895 -- might be a hierarchical module.
896 createDirectoryHierarchy (directoryOf output_fn)
898 SysTools.runAs dflags
899 (map SysTools.Option as_opts
900 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
901 ++ [ SysTools.Option "-c"
902 , SysTools.FileOption "" input_fn
903 , SysTools.Option "-o"
904 , SysTools.FileOption "" output_fn
907 return (StopLn, dflags, maybe_loc, output_fn)
910 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
911 = do let as_opts = getOpts dflags opt_a
913 (split_s_prefix, n) <- readIORef v_Split_info
916 | Just d <- outputDir dflags = d
917 | otherwise = basename ++ "_split"
920 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
921 let output_o = replaceFilenameDirectory
922 (basename ++ "__" ++ show n ++ ".o")
924 let osuf = objectSuf dflags
925 let real_o = replaceFilenameSuffix output_o osuf
926 SysTools.runAs dflags
927 (map SysTools.Option as_opts ++
928 [ SysTools.Option "-c"
929 , SysTools.Option "-o"
930 , SysTools.FileOption "" real_o
931 , SysTools.FileOption "" input_s
934 mapM_ assemble_file [1..n]
936 output_fn <- get_output_fn StopLn maybe_loc
937 return (StopLn, dflags, maybe_loc, output_fn)
939 -----------------------------------------------------------------------------
940 -- MoveBinary sort-of-phase
941 -- After having produced a binary, move it somewhere else and generate a
942 -- wrapper script calling the binary. Currently, we need this only in
943 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
944 -- central directory.
945 -- This is called from staticLink below, after linking. I haven't made it
946 -- a separate phase to minimise interfering with other modules, and
947 -- we don't need the generality of a phase (MoveBinary is always
948 -- done after linking and makes only sense in a parallel setup) -- HWL
950 runPhase_MoveBinary input_fn
953 pvm_root <- getEnv "PVM_ROOT"
954 pvm_arch <- getEnv "PVM_ARCH"
956 pvm_executable_base = "=" ++ input_fn
957 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
958 -- nuke old binary; maybe use configur'ed names for cp and rm?
959 system ("rm -f " ++ pvm_executable)
960 -- move the newly created binary into PVM land
961 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
962 -- generate a wrapper script for running a parallel prg under PVM
963 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
966 -- generates a Perl skript starting a parallel prg under PVM
967 mk_pvm_wrapper_script :: String -> String -> String -> String
968 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
970 "eval 'exec perl -S $0 ${1+\"$@\"}'",
971 " if $running_under_some_shell;",
972 "# =!=!=!=!=!=!=!=!=!=!=!",
973 "# This script is automatically generated: DO NOT EDIT!!!",
974 "# Generated by Glasgow Haskell Compiler",
975 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
977 "$pvm_executable = '" ++ pvm_executable ++ "';",
978 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
979 "$SysMan = '" ++ sysMan ++ "';",
981 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
982 "# first, some magical shortcuts to run "commands" on the binary",
983 "# (which is hidden)",
984 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
985 " local($cmd) = $1;",
986 " system("$cmd $pvm_executable");",
987 " exit(0); # all done",
990 "# Now, run the real binary; process the args first",
991 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
993 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
994 "@nonPVM_args = ();",
997 "args: while ($a = shift(@ARGV)) {",
998 " if ( $a eq '+RTS' ) {",
999 " $in_RTS_args = 1;",
1000 " } elsif ( $a eq '-RTS' ) {",
1001 " $in_RTS_args = 0;",
1003 " if ( $a eq '-d' && $in_RTS_args ) {",
1005 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1006 " $nprocessors = $1;",
1007 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1008 " $nprocessors = $1;",
1010 " push(@nonPVM_args, $a);",
1014 "local($return_val) = 0;",
1015 "# Start the parallel execution by calling SysMan",
1016 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1017 "$return_val = $?;",
1018 "# ToDo: fix race condition moving files and flushing them!!",
1019 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1020 "exit($return_val);"
1023 -----------------------------------------------------------------------------
1024 -- Complain about non-dynamic flags in OPTIONS pragmas
1026 checkProcessArgsResult flags filename
1027 = do when (notNull flags) (throwDyn (ProgramError (
1028 showSDoc (hang (text filename <> char ':')
1029 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1030 hsep (map text flags)))
1033 -----------------------------------------------------------------------------
1034 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1036 getHCFilePackages :: FilePath -> IO [PackageId]
1037 getHCFilePackages filename =
1038 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1041 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1042 return (map stringToPackageId (words rest))
1046 -----------------------------------------------------------------------------
1047 -- Static linking, of .o files
1049 -- The list of packages passed to link is the list of packages on
1050 -- which this program depends, as discovered by the compilation
1051 -- manager. It is combined with the list of packages that the user
1052 -- specifies on the command line with -package flags.
1054 -- In one-shot linking mode, we can't discover the package
1055 -- dependencies (because we haven't actually done any compilation or
1056 -- read any interface files), so the user must explicitly specify all
1059 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1060 staticLink dflags o_files dep_packages = do
1061 let verb = getVerbFlag dflags
1063 -- get the full list of packages to link with, by combining the
1064 -- explicit packages with the auto packages and all of their
1065 -- dependencies, and eliminating duplicates.
1067 let o_file = outputFile dflags
1068 #if defined(mingw32_HOST_OS)
1069 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1071 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1074 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1075 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1077 let lib_paths = libraryPaths dflags
1078 let lib_path_opts = map ("-L"++) lib_paths
1080 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1082 #ifdef darwin_TARGET_OS
1083 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1084 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1086 let framework_paths = frameworkPaths dflags
1087 framework_path_opts = map ("-F"++) framework_paths
1089 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1090 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1092 let frameworks = cmdlineFrameworks dflags
1093 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1094 -- reverse because they're added in reverse order from the cmd line
1097 -- probably _stub.o files
1098 extra_ld_inputs <- readIORef v_Ld_inputs
1100 -- opts from -optl-<blah> (including -l<blah> options)
1101 let extra_ld_opts = getOpts dflags opt_l
1103 let ways = wayNames dflags
1105 -- Here are some libs that need to be linked at the *end* of
1106 -- the command line, because they contain symbols that are referred to
1107 -- by the RTS. We can't therefore use the ordinary way opts for these.
1109 debug_opts | WayDebug `elem` ways = [
1110 #if defined(HAVE_LIBBFD)
1117 thread_opts | WayThreaded `elem` ways = [
1118 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1121 #if defined(osf3_TARGET_OS)
1127 let (md_c_flags, _) = machdepCCOpts dflags
1128 SysTools.runLink dflags (
1129 [ SysTools.Option verb
1130 , SysTools.Option "-o"
1131 , SysTools.FileOption "" output_fn
1133 ++ map SysTools.Option (
1139 #ifdef darwin_TARGET_OS
1140 ++ framework_path_opts
1143 ++ pkg_lib_path_opts
1145 #ifdef darwin_TARGET_OS
1146 ++ pkg_framework_path_opts
1147 ++ pkg_framework_opts
1153 -- parallel only: move binary to another dir -- HWL
1154 when (WayPar `elem` ways)
1155 (do success <- runPhase_MoveBinary output_fn
1156 if success then return ()
1157 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1159 -----------------------------------------------------------------------------
1160 -- Making a DLL (only for Win32)
1162 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1163 doMkDLL dflags o_files dep_packages = do
1164 let verb = getVerbFlag dflags
1165 let static = opt_Static
1166 let no_hs_main = dopt Opt_NoHsMain dflags
1167 let o_file = outputFile dflags
1168 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1170 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1171 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1173 let lib_paths = libraryPaths dflags
1174 let lib_path_opts = map ("-L"++) lib_paths
1176 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1178 -- probably _stub.o files
1179 extra_ld_inputs <- readIORef v_Ld_inputs
1181 -- opts from -optdll-<blah>
1182 let extra_ld_opts = getOpts dflags opt_dll
1184 let pstate = pkgState dflags
1185 rts_id | ExtPackage id <- rtsPackageId pstate = id
1186 | otherwise = panic "staticLink: rts package missing"
1187 base_id | ExtPackage id <- basePackageId pstate = id
1188 | otherwise = panic "staticLink: base package missing"
1189 rts_pkg = getPackageDetails pstate rts_id
1190 base_pkg = getPackageDetails pstate base_id
1192 let extra_os = if static || no_hs_main
1194 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1195 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1197 let (md_c_flags, _) = machdepCCOpts dflags
1198 SysTools.runMkDLL dflags
1199 ([ SysTools.Option verb
1200 , SysTools.Option "-o"
1201 , SysTools.FileOption "" output_fn
1203 ++ map SysTools.Option (
1207 ++ [ "--target=i386-mingw32" ]
1211 ++ pkg_lib_path_opts
1213 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1215 else [ "--export-all" ])
1218 -- -----------------------------------------------------------------------------
1221 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1222 doCpp dflags raw include_cc_opts input_fn output_fn = do
1223 let hscpp_opts = getOpts dflags opt_P
1224 let cmdline_include_paths = includePaths dflags
1226 pkg_include_dirs <- getPackageIncludePath dflags []
1227 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1228 (cmdline_include_paths ++ pkg_include_dirs)
1230 let verb = getVerbFlag dflags
1233 | not include_cc_opts = []
1234 | otherwise = (optc ++ md_c_flags)
1236 optc = getOpts dflags opt_c
1237 (md_c_flags, _) = machdepCCOpts dflags
1239 let cpp_prog args | raw = SysTools.runCpp dflags args
1240 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1243 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1244 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1245 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1246 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1247 -- remember, in code we *compile*, the HOST is the same our TARGET,
1248 -- and BUILD is the same as our HOST.
1250 cpp_prog ([SysTools.Option verb]
1251 ++ map SysTools.Option include_paths
1252 ++ map SysTools.Option hsSourceCppOpts
1253 ++ map SysTools.Option hscpp_opts
1254 ++ map SysTools.Option cc_opts
1255 ++ map SysTools.Option target_defs
1256 ++ [ SysTools.Option "-x"
1257 , SysTools.Option "c"
1258 , SysTools.Option input_fn
1259 -- We hackily use Option instead of FileOption here, so that the file
1260 -- name is not back-slashed on Windows. cpp is capable of
1261 -- dealing with / in filenames, so it works fine. Furthermore
1262 -- if we put in backslashes, cpp outputs #line directives
1263 -- with *double* backslashes. And that in turn means that
1264 -- our error messages get double backslashes in them.
1265 -- In due course we should arrange that the lexer deals
1266 -- with these \\ escapes properly.
1267 , SysTools.Option "-o"
1268 , SysTools.FileOption "" output_fn
1271 cHaskell1Version = "5" -- i.e., Haskell 98
1273 -- Default CPP defines in Haskell source
1275 [ "-D__HASKELL1__="++cHaskell1Version
1276 , "-D__GLASGOW_HASKELL__="++cProjectVersionInt
1278 , "-D__CONCURRENT_HASKELL__"
1281 -----------------------------------------------------------------------------
1282 -- Reading OPTIONS pragmas
1284 getOptionsFromSource
1285 :: String -- input file
1286 -> IO [String] -- options, if any
1287 getOptionsFromSource file
1288 = do h <- openFile file ReadMode
1289 look h `finally` hClose h
1292 r <- tryJust ioErrors (hGetLine h)
1294 Left e | isEOFError e -> return []
1295 | otherwise -> ioError e
1297 let l = removeSpaces l'
1299 () | null l -> look h
1300 | prefixMatch "#" l -> look h
1301 | prefixMatch "{-# LINE" l -> look h -- -}
1302 | Just opts <- matchOptions l
1303 -> do rest <- look h
1304 return (opts ++ rest)
1305 | otherwise -> return []
1307 getOptionsFromStringBuffer :: StringBuffer -> [String]
1308 getOptionsFromStringBuffer buffer@(StringBuffer _ len# _) =
1310 ls = lines (lexemeToString buffer (I# len#)) -- lazy, so it's ok
1316 let l = removeSpaces l'
1318 () | null l -> look ls
1319 | prefixMatch "#" l -> look ls
1320 | prefixMatch "{-# LINE" l -> look ls -- -}
1321 | Just opts <- matchOptions l
1325 -- detect {-# OPTIONS_GHC ... #-}. For the time being, we accept OPTIONS
1326 -- instead of OPTIONS_GHC, but that is deprecated.
1328 | Just s1 <- maybePrefixMatch "{-#" s -- -}
1329 = matchOptions1 (removeSpaces s1)
1334 | Just s2 <- maybePrefixMatch "OPTIONS" s
1336 _ | Just s3 <- maybePrefixMatch "_GHC" s2, not (is_ident (head s3))
1338 | not (is_ident (head s2))
1341 -> Just [] -- OPTIONS_anything is ignored, not treated as start of source
1342 | Just s2 <- maybePrefixMatch "INCLUDE" s, not (is_ident (head s2)),
1343 Just s3 <- maybePrefixMatch "}-#" (reverse s2)
1344 = Just ["-#include", removeSpaces (reverse s3)]
1345 | otherwise = Nothing
1347 | Just s3 <- maybePrefixMatch "}-#" (reverse s) = Just (words (reverse s3))
1348 | otherwise = Nothing
1351 -- -----------------------------------------------------------------------------
1354 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1355 hscNextPhase dflags HsBootFile hsc_lang = StopLn
1356 hscNextPhase dflags other hsc_lang =
1359 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1361 HscNothing -> StopLn
1362 HscInterpreted -> StopLn
1366 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1367 hscMaybeAdjustTarget dflags stop HsBootFile current_hsc_lang
1368 = HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1369 hscMaybeAdjustTarget dflags stop other current_hsc_lang
1372 keep_hc = dopt Opt_KeepHcFiles dflags
1374 -- don't change the lang if we're interpreting
1375 | current_hsc_lang == HscInterpreted = current_hsc_lang
1377 -- force -fvia-C if we are being asked for a .hc file
1378 | HCc <- stop = HscC
1380 -- otherwise, stick to the plan
1381 | otherwise = current_hsc_lang
1383 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1384 -- The split prefix and number of files