1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2002
7 -----------------------------------------------------------------------------
9 #include "../includes/ghcconfig.h"
11 module DriverPipeline (
13 -- Interfaces for the batch-mode driver
14 compileFile, staticLink,
16 -- Interfaces for the compilation manager (interpreted/batch-mode)
18 compile, CompResult(..),
25 #include "HsVersions.h"
33 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
34 import qualified SysTools
43 import RdrName ( GlobalRdrEnv )
46 import StringBuffer ( hGetStringBuffer )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
50 import ParserCoreUtils ( getCoreModuleName )
53 import DATA_IOREF ( readIORef, writeIORef )
62 -- ---------------------------------------------------------------------------
65 -- Just preprocess a file, put the result in a temp. file (used by the
66 -- compilation manager during the summary phase).
68 -- We return the augmented DynFlags, because they contain the result
69 -- of slurping in the OPTIONS pragmas
71 preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
72 preprocess dflags filename =
73 ASSERT2(isHaskellSrcFilename filename, text filename)
74 runPipeline anyHsc "preprocess" dflags
75 False{-temporary output file-}
76 Nothing{-no specific output file-}
78 Nothing{-no ModLocation-}
82 -- ---------------------------------------------------------------------------
84 -- This is used in batch mode
85 compileFile :: GhcMode -> DynFlags -> FilePath -> IO FilePath
86 compileFile mode dflags src = do
87 exists <- doesFileExist src
89 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
91 split <- readIORef v_Split_object_files
92 o_file <- readIORef v_Output_file
93 ghc_link <- readIORef v_GhcLink -- Set by -c or -no-link
94 -- When linking, the -o argument refers to the linker's output.
95 -- otherwise, we use it as the name for the pipeline's output.
97 | isLinkMode mode && not (isNoLink ghc_link) = Nothing
98 -- -o foo applies to linker
100 -- -o foo applies to the file we are compiling now
102 stop_phase = case mode of
103 StopBefore As | split -> SplitAs
104 StopBefore phase -> phase
107 mode_flag_string <- readIORef v_GhcModeFlag
108 (_, out_file) <- runPipeline stop_phase mode_flag_string dflags
109 True maybe_o_file src Nothing{-no ModLocation-}
113 -- ---------------------------------------------------------------------------
116 -- Compile a single module, under the control of the compilation manager.
118 -- This is the interface between the compilation manager and the
119 -- compiler proper (hsc), where we deal with tedious details like
120 -- reading the OPTIONS pragma from the source file, and passing the
121 -- output of hsc through the C compiler.
123 -- The driver sits between 'compile' and 'hscMain', translating calls
124 -- to the former into calls to the latter, and results from the latter
125 -- into results from the former. It does things like preprocessing
126 -- the .hs file if necessary, and compiling up the .stub_c files to
127 -- generate Linkables.
129 -- NB. No old interface can also mean that the source has changed.
133 -> Bool -- True <=> source unchanged
134 -> Bool -- True <=> have object
135 -> Maybe ModIface -- Old interface, if available
139 = CompOK ModDetails -- New details
140 (Maybe GlobalRdrEnv) -- Lexical environment for the module
141 -- (Maybe because we may have loaded it from
142 -- its precompiled interface)
143 ModIface -- New iface
144 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
145 -- (old code is still valid)
150 compile hsc_env mod_summary
151 source_unchanged have_object old_iface = do
153 let dyn_flags = hsc_dflags hsc_env
154 this_mod = ms_mod mod_summary
155 src_flavour = ms_hsc_src mod_summary
157 showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
159 let verb = verbosity dyn_flags
160 let location = ms_location mod_summary
161 let input_fn = expectJust "compile:hs" (ml_hs_file location)
162 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
164 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
166 -- Add in the OPTIONS from the source file
167 -- This is nasty: we've done this once already, in the compilation manager
168 -- It might be better to cache the flags in the ml_hspp_file field,say
169 opts <- getOptionsFromSource input_fnpp
170 (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
171 checkProcessArgsResult unhandled_flags input_fn
173 let (basename, _) = splitFilename input_fn
175 -- We add the directory in which the .hs files resides) to the import path.
176 -- This is needed when we try to compile the .hc file later, if it
177 -- imports a _stub.h file that we created here.
178 let current_dir = directoryOf basename
179 old_paths <- readIORef v_Include_paths
180 writeIORef v_Include_paths (current_dir : old_paths)
181 -- put back the old include paths afterward.
182 later (writeIORef v_Include_paths old_paths) $ do
184 -- Figure out what lang we're generating
185 hsc_lang <- hscMaybeAdjustTarget StopLn src_flavour (hscTarget dyn_flags)
186 -- ... and what the next phase should be
187 next_phase <- hscNextPhase src_flavour hsc_lang
188 -- ... and what file to generate the output into
189 get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
190 output_fn <- get_output_fn next_phase (Just location)
192 let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
193 hscOutName = output_fn,
194 hscStubCOutName = basename ++ "_stub.c",
195 hscStubHOutName = basename ++ "_stub.h",
196 extCoreName = basename ++ ".hcr" }
198 -- -no-recomp should also work with --make
199 let do_recomp = recompFlag dyn_flags
200 source_unchanged' = source_unchanged && do_recomp
201 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
204 hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
205 source_unchanged' have_object old_iface
208 HscFail -> return CompErrs
210 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
212 HscRecomp details rdr_env iface
213 stub_h_exists stub_c_exists maybe_interpreted_code
215 | isHsBoot src_flavour -- No further compilation to do
216 -> return (CompOK details rdr_env iface Nothing)
218 | otherwise -- Normal Haskell source files
221 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
222 let stub_unlinked = case maybe_stub_o of
224 Just stub_o -> [ DotO stub_o ]
226 (hs_unlinked, unlinked_time) <-
229 -- in interpreted mode, just return the compiled code
230 -- as our "unlinked" object.
232 case maybe_interpreted_code of
234 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
235 -- Why do we use the timestamp of the source file here,
236 -- rather than the current time? This works better in
237 -- the case where the local clock is out of sync
238 -- with the filesystem's clock. It's just as accurate:
239 -- if the source is modified, then the linkable will
242 Nothing -> panic "compile: no interpreted code"
244 -- we're in batch mode: finish the compilation pipeline.
246 let object_filename = ml_obj_file location
248 runPipeline StopLn "" dyn_flags
249 True Nothing output_fn (Just location)
250 -- the object filename comes from the ModLocation
252 o_time <- getModificationTime object_filename
253 return ([DotO object_filename], o_time)
255 let linkable = LM unlinked_time this_mod
256 (hs_unlinked ++ stub_unlinked)
258 return (CompOK details rdr_env iface (Just linkable))
260 -----------------------------------------------------------------------------
261 -- stub .h and .c files (for foreign export support)
263 compileStub dflags stub_c_exists
264 | not stub_c_exists = return Nothing
266 -- compile the _stub.c file w/ gcc
267 let stub_c = hscStubCOutName dflags
268 (_, stub_o) <- runPipeline StopLn "stub-compile" dflags
269 True{-persistent output-}
270 Nothing{-no specific output file-}
272 Nothing{-no ModLocation-}
276 -- ---------------------------------------------------------------------------
279 link :: GhciMode -- interactive or batch
280 -> DynFlags -- dynamic flags
281 -> Bool -- attempt linking in batch mode?
282 -> HomePackageTable -- what to link
285 -- For the moment, in the batch linker, we don't bother to tell doLink
286 -- which packages to link -- it just tries all that are available.
287 -- batch_attempt_linking should only be *looked at* in batch mode. It
288 -- should only be True if the upsweep was successful and someone
289 -- exports main, i.e., we have good reason to believe that linking
293 link Interactive dflags batch_attempt_linking hpt
294 = do -- Not Linking...(demand linker will do the job)
298 link Batch dflags batch_attempt_linking hpt
299 | batch_attempt_linking
302 home_mod_infos = moduleEnvElts hpt
304 -- the packages we depend on
305 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
307 -- the linkables to link
308 linkables = map hm_linkable home_mod_infos
310 when (verb >= 3) $ do
311 hPutStrLn stderr "link: linkables are ..."
312 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
314 -- check for the -no-link flag
315 ghc_link <- readIORef v_GhcLink
317 then do when (verb >= 3) $
318 hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
323 hPutStrLn stderr "Linking ..."
325 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
326 obj_files = concatMap getOfiles linkables
328 -- Don't showPass in Batch mode; doLink will do that for us.
329 staticLink dflags obj_files pkg_deps
331 when (verb >= 3) (hPutStrLn stderr "link: done")
333 -- staticLink only returns if it succeeds
337 = do when (verb >= 3) $ do
338 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
339 hPutStrLn stderr " Main.main not exported; not linking."
342 verb = verbosity dflags
344 -- ---------------------------------------------------------------------------
345 -- Run a compilation pipeline, consisting of multiple phases.
347 -- The DynFlags can be modified by phases in the pipeline (eg. by
348 -- OPTIONS pragmas), and the changes affect later phases in the
349 -- pipeline, but we throw away the resulting DynFlags at the end.
352 :: Phase -- When to stop
353 -> String -- "GhcMode" flag as a string
354 -> DynFlags -- Dynamic flags
355 -> Bool -- Final output is persistent?
356 -> Maybe FilePath -- Where to put the output, optionally
357 -> FilePath -- Input filename
358 -> Maybe ModLocation -- A ModLocation for this module, if we have one
359 -> IO (DynFlags, FilePath) -- (final flags, output filename)
361 runPipeline stop_phase mode_flag_string dflags keep_output
362 maybe_output_filename input_fn maybe_loc
364 let (basename, suffix) = splitFilename input_fn
365 start_phase = startPhase suffix
367 -- We want to catch cases of "you can't get there from here" before
368 -- we start the pipeline, because otherwise it will just run off the
371 -- There is a partial ordering on phases, where A < B iff A occurs
372 -- before B in a normal compilation pipeline.
374 when (not (start_phase `happensBefore` stop_phase)) $
376 ("flag `" ++ mode_flag_string
377 ++ "' is incompatible with source file `"
380 -- generate a function which will be used to calculate output file names
382 get_output_fn <- genOutputFilenameFunc stop_phase keep_output
383 maybe_output_filename basename
385 -- Execute the pipeline...
386 (dflags', output_fn, maybe_loc) <- pipeLoop dflags start_phase stop_phase input_fn
387 basename suffix get_output_fn maybe_loc
389 -- Sometimes, a compilation phase doesn't actually generate any output
390 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
391 -- stage, but we wanted to keep the output, then we have to explicitly
394 then do final_fn <- get_output_fn stop_phase maybe_loc
395 when (final_fn /= output_fn) $
396 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
397 ++ "'") output_fn final_fn
398 return (dflags', final_fn)
400 return (dflags', output_fn)
403 pipeLoop :: DynFlags -> Phase -> Phase
404 -> FilePath -> String -> Suffix
405 -> (Phase -> Maybe ModLocation -> IO FilePath)
407 -> IO (DynFlags, FilePath, Maybe ModLocation)
409 pipeLoop dflags phase stop_phase
410 input_fn orig_basename orig_suff
411 orig_get_output_fn maybe_loc
413 | phase `eqPhase` stop_phase -- All done
414 = return (dflags, input_fn, maybe_loc)
416 | not (phase `happensBefore` stop_phase)
417 -- Something has gone wrong. We'll try to cover all the cases when
418 -- this could happen, so if we reach here it is a panic.
419 -- eg. it might happen if the -C flag is used on a source file that
420 -- has {-# OPTIONS -fasm #-}.
421 = panic ("pipeLoop: at phase " ++ show phase ++
422 " but I wanted to stop at phase " ++ show stop_phase)
425 = do { (next_phase, dflags', maybe_loc, output_fn)
426 <- runPhase phase stop_phase dflags orig_basename
427 orig_suff input_fn orig_get_output_fn maybe_loc
428 ; pipeLoop dflags' next_phase stop_phase output_fn
429 orig_basename orig_suff orig_get_output_fn maybe_loc }
431 genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
432 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
433 genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
435 hcsuf <- readIORef v_HC_suf
436 odir <- readIORef v_Output_dir
437 osuf <- readIORef v_Object_suf
438 keep_hc <- readIORef v_Keep_hc_files
440 keep_il <- readIORef v_Keep_il_files
441 keep_ilx <- readIORef v_Keep_ilx_files
443 keep_raw_s <- readIORef v_Keep_raw_s_files
444 keep_s <- readIORef v_Keep_s_files
446 myPhaseInputExt HCc = hcsuf
447 myPhaseInputExt StopLn = osuf
448 myPhaseInputExt other = phaseInputExt other
450 func next_phase maybe_location
451 | is_last_phase, Just f <- maybe_output_filename = return f
452 | is_last_phase && keep_final_output = persistent_fn
453 | keep_this_output = persistent_fn
454 | otherwise = newTempName suffix
457 is_last_phase = next_phase `eqPhase` stop_phase
459 -- sometimes, we keep output from intermediate stages
463 Mangle | keep_raw_s -> True
465 HCc | keep_hc -> True
468 suffix = myPhaseInputExt next_phase
470 -- persistent object files get put in odir
472 | StopLn <- next_phase = return odir_persistent
473 | otherwise = return persistent
475 persistent = basename ++ '.':suffix
478 | Just loc <- maybe_location = ml_obj_file loc
479 | Just d <- odir = replaceFilenameDirectory persistent d
480 | otherwise = persistent
485 -- -----------------------------------------------------------------------------
486 -- Each phase in the pipeline returns the next phase to execute, and the
487 -- name of the file in which the output was placed.
489 -- We must do things dynamically this way, because we often don't know
490 -- what the rest of the phases will be until part-way through the
491 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
492 -- of a source file can change the latter stages of the pipeline from
493 -- taking the via-C route to using the native code generator.
495 runPhase :: Phase -- Do this phase first
496 -> Phase -- Stop just before this phase
498 -> String -- basename of original input source
499 -> String -- its extension
500 -> FilePath -- name of file which contains the input to this phase.
501 -> (Phase -> Maybe ModLocation -> IO FilePath)
502 -- how to calculate the output filename
503 -> Maybe ModLocation -- the ModLocation, if we have one
504 -> IO (Phase, -- next phase
505 DynFlags, -- new dynamic flags
506 Maybe ModLocation, -- the ModLocation, if we have one
507 FilePath) -- output filename
509 -- Invariant: the output filename always contains the output
510 -- Interesting case: Hsc when there is no recompilation to do
511 -- Then the output filename is still a .o file
513 -------------------------------------------------------------------------------
516 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
517 = do let unlit_flags = getOpts dflags opt_L
518 -- The -h option passes the file name for unlit to put in a #line directive
519 output_fn <- get_output_fn (Cpp sf) maybe_loc
521 SysTools.runUnlit dflags
522 (map SysTools.Option unlit_flags ++
523 [ SysTools.Option "-h"
524 , SysTools.Option input_fn
525 , SysTools.FileOption "" input_fn
526 , SysTools.FileOption "" output_fn
529 return (Cpp sf, dflags, maybe_loc, output_fn)
531 -------------------------------------------------------------------------------
532 -- Cpp phase : (a) gets OPTIONS out of file
533 -- (b) runs cpp if necessary
535 runPhase (Cpp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
536 = do src_opts <- getOptionsFromSource input_fn
537 (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
538 checkProcessArgsResult unhandled_flags (basename++'.':suff)
540 if not (cppFlag dflags) then
541 -- no need to preprocess CPP, just pass input file along
542 -- to the next phase of the pipeline.
543 return (HsPp sf, dflags, maybe_loc, input_fn)
545 output_fn <- get_output_fn (HsPp sf) maybe_loc
546 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
547 return (HsPp sf, dflags, maybe_loc, output_fn)
549 -------------------------------------------------------------------------------
552 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
553 = do if not (ppFlag dflags) then
554 -- no need to preprocess, just pass input file along
555 -- to the next phase of the pipeline.
556 return (Hsc sf, dflags, maybe_loc, input_fn)
558 let hspp_opts = getOpts dflags opt_F
559 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
560 let orig_fn = basename ++ '.':suff
561 output_fn <- get_output_fn (Hsc sf) maybe_loc
562 SysTools.runPp dflags
563 ( [ SysTools.Option orig_fn
564 , SysTools.Option input_fn
565 , SysTools.FileOption "" output_fn
567 map SysTools.Option hs_src_pp_opts ++
568 map SysTools.Option hspp_opts
570 return (Hsc sf, dflags, maybe_loc, output_fn)
572 -----------------------------------------------------------------------------
575 -- Compilation of a single module, in "legacy" mode (_not_ under
576 -- the direction of the compilation manager).
577 runPhase (Hsc src_flavour) stop dflags basename suff input_fn get_output_fn _maybe_loc
578 = do -- normal Hsc mode, not mkdependHS
580 -- we add the current directory (i.e. the directory in which
581 -- the .hs files resides) to the import path, since this is
582 -- what gcc does, and it's probably what you want.
583 let current_dir = directoryOf basename
585 paths <- readIORef v_Include_paths
586 writeIORef v_Include_paths (current_dir : paths)
588 -- gather the imports and module name
589 (hspp_buf,mod_name) <-
591 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
592 ; m <- getCoreModuleName input_fn
593 ; return (Nothing, mkModule m) }
595 other -> do { buf <- hGetStringBuffer input_fn
596 ; (_,_,mod_name) <- getImports dflags buf input_fn
597 ; return (Just buf, mod_name) }
599 -- Build a ModLocation to pass to hscMain.
600 -- The source filename is rather irrelevant by now, but it's used
601 -- by hscMain for messages. hscMain also needs
602 -- the .hi and .o filenames, and this is as good a way
603 -- as any to generate them, and better than most. (e.g. takes
604 -- into accout the -osuf flags)
605 location1 <- mkHomeModLocation2 mod_name basename suff
607 -- Boot-ify it if necessary
608 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
609 | otherwise = location1
612 -- Take -ohi into account if present
613 -- This can't be done in mkHomeModuleLocation because
614 -- it only applies to the module being compiles
615 ohi <- readIORef v_Output_hi
616 let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
617 | otherwise = location2
619 -- Take -o into account if present
620 -- Very like -ohi, but we must *only* do this if we aren't linking
621 -- (If we're linking then the -o applies to the linked thing, not to
622 -- the object file for one module.)
623 -- Note the nasty duplication with the same computation in compileFile above
624 expl_o_file <- readIORef v_Output_file
625 ghc_link <- readIORef v_GhcLink
626 let location4 | Just ofile <- expl_o_file
628 = location3 { ml_obj_file = ofile }
629 | otherwise = location3
631 -- Tell the finder cache about this module
632 addHomeModuleToFinder mod_name location4
634 -- Make the ModSummary to hand to hscMain
635 src_timestamp <- getModificationTime (basename ++ '.':suff)
637 unused_field = panic "runPhase:ModSummary field"
638 -- Some fields are not looked at by hscMain
639 mod_summary = ModSummary { ms_mod = mod_name,
640 ms_hsc_src = src_flavour,
641 ms_hspp_file = Just input_fn,
642 ms_hspp_buf = hspp_buf,
643 ms_location = location4,
644 ms_hs_date = src_timestamp,
645 ms_imps = unused_field,
646 ms_srcimps = unused_field }
648 o_file = ml_obj_file location4 -- The real object file
651 -- Figure out if the source has changed, for recompilation avoidance.
653 -- Setting source_unchanged to True means that M.o seems
654 -- to be up to date wrt M.hs; so no need to recompile unless imports have
655 -- changed (which the compiler itself figures out).
656 -- Setting source_unchanged to False tells the compiler that M.o is out of
657 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
658 let do_recomp = recompFlag dflags
660 if not do_recomp || not (isStopLn stop)
661 -- Set source_unchanged to False unconditionally if
662 -- (a) recompilation checker is off, or
663 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
665 -- Otherwise look at file modification dates
666 else do o_file_exists <- doesFileExist o_file
668 then return False -- Need to recompile
669 else do t2 <- getModificationTime o_file
670 if t2 > src_timestamp
675 hsc_lang <- hscMaybeAdjustTarget stop src_flavour (hscTarget dflags)
676 next_phase <- hscNextPhase src_flavour hsc_lang
677 output_fn <- get_output_fn next_phase (Just location4)
679 let dflags' = dflags { hscTarget = hsc_lang,
680 hscOutName = output_fn,
681 hscStubCOutName = basename ++ "_stub.c",
682 hscStubHOutName = basename ++ "_stub.h",
683 extCoreName = basename ++ ".hcr" }
685 hsc_env <- newHscEnv OneShot dflags'
688 result <- hscMain hsc_env printErrorsAndWarnings
689 mod_summary source_unchanged
690 False -- No object file
695 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
697 HscNoRecomp details iface -> do
698 SysTools.touch dflags' "Touching object file" o_file
699 return (StopLn, dflags', Just location4, o_file)
701 HscRecomp _details _rdr_env _iface
702 stub_h_exists stub_c_exists
703 _maybe_interpreted_code -> do
706 maybe_stub_o <- compileStub dflags' stub_c_exists
709 Just stub_o -> add v_Ld_inputs stub_o
711 -- In the case of hs-boot files, generate a dummy .o-boot
712 -- stamp file for the benefit of Make
714 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
717 return (next_phase, dflags', Just location4, output_fn)
719 -----------------------------------------------------------------------------
722 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
724 output_fn <- get_output_fn Cmm maybe_loc
725 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
726 return (Cmm, dflags, maybe_loc, output_fn)
728 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
730 hsc_lang <- hscMaybeAdjustTarget stop HsSrcFile (hscTarget dflags)
731 next_phase <- hscNextPhase HsSrcFile hsc_lang
732 output_fn <- get_output_fn next_phase maybe_loc
734 let dflags' = dflags { hscTarget = hsc_lang,
735 hscOutName = output_fn,
736 hscStubCOutName = basename ++ "_stub.c",
737 hscStubHOutName = basename ++ "_stub.h",
738 extCoreName = basename ++ ".hcr" }
740 ok <- hscCmmFile dflags' input_fn
742 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
744 return (next_phase, dflags, maybe_loc, output_fn)
746 -----------------------------------------------------------------------------
749 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
750 -- way too many hacks, and I can't say I've ever used it anyway.
752 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
753 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
754 = do let cc_opts = getOpts dflags opt_c
755 hcc = cc_phase `eqPhase` HCc
757 cmdline_include_paths <- readIORef v_Include_paths
759 -- HC files have the dependent packages stamped into them
760 pkgs <- if hcc then getHCFilePackages input_fn else return []
762 -- add package include paths even if we're just compiling .c
763 -- files; this is the Value Add(TM) that using ghc instead of
765 pkg_include_dirs <- getPackageIncludePath dflags pkgs
766 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
767 (cmdline_include_paths ++ pkg_include_dirs)
769 (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
770 pic_c_flags <- picCCOpts dflags
772 let verb = getVerbFlag dflags
774 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
776 split_objs <- readIORef v_Split_object_files
777 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
780 excessPrecision <- readIORef v_Excess_precision
783 mangle <- readIORef v_Do_asm_mangling
785 | hcc && mangle = Mangle
787 output_fn <- get_output_fn next_phase maybe_loc
789 -- force the C compiler to interpret this file as C when
790 -- compiling .hc files, by adding the -x c option.
791 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
794 SysTools.runCc dflags (langopt ++
795 [ SysTools.FileOption "" input_fn
796 , SysTools.Option "-o"
797 , SysTools.FileOption "" output_fn
799 ++ map SysTools.Option (
805 ++ [ verb, "-S", "-Wimplicit", "-O" ]
806 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
809 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
814 return (next_phase, dflags, maybe_loc, output_fn)
816 -- ToDo: postprocess the output from gcc
818 -----------------------------------------------------------------------------
821 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
822 = do let mangler_opts = getOpts dflags opt_m
825 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
827 machdep_opts <- return []
830 split <- readIORef v_Split_object_files
832 | split = SplitMangle
834 output_fn <- get_output_fn next_phase maybe_loc
836 SysTools.runMangle dflags (map SysTools.Option mangler_opts
837 ++ [ SysTools.FileOption "" input_fn
838 , SysTools.FileOption "" output_fn
840 ++ map SysTools.Option machdep_opts)
842 return (next_phase, dflags, maybe_loc, output_fn)
844 -----------------------------------------------------------------------------
847 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
848 = do -- tmp_pfx is the prefix used for the split .s files
849 -- We also use it as the file to contain the no. of split .s files (sigh)
850 split_s_prefix <- SysTools.newTempName "split"
851 let n_files_fn = split_s_prefix
853 SysTools.runSplit dflags
854 [ SysTools.FileOption "" input_fn
855 , SysTools.FileOption "" split_s_prefix
856 , SysTools.FileOption "" n_files_fn
859 -- Save the number of split files for future references
860 s <- readFile n_files_fn
861 let n_files = read s :: Int
862 writeIORef v_Split_info (split_s_prefix, n_files)
864 -- Remember to delete all these files
865 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
868 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
869 -- we don't use the filename
871 -----------------------------------------------------------------------------
874 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
875 = do let as_opts = getOpts dflags opt_a
876 cmdline_include_paths <- readIORef v_Include_paths
878 output_fn <- get_output_fn StopLn maybe_loc
880 -- we create directories for the object file, because it
881 -- might be a hierarchical module.
882 createDirectoryHierarchy (directoryOf output_fn)
884 SysTools.runAs dflags
885 (map SysTools.Option as_opts
886 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
887 ++ [ SysTools.Option "-c"
888 , SysTools.FileOption "" input_fn
889 , SysTools.Option "-o"
890 , SysTools.FileOption "" output_fn
893 return (StopLn, dflags, maybe_loc, output_fn)
896 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
897 = do let as_opts = getOpts dflags opt_a
899 (split_s_prefix, n) <- readIORef v_Split_info
901 odir <- readIORef v_Output_dir
902 let real_odir = case odir of
903 Nothing -> basename ++ "_split"
907 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
908 let output_o = replaceFilenameDirectory
909 (basename ++ "__" ++ show n ++ ".o")
911 real_o <- osuf_ify output_o
912 SysTools.runAs dflags
913 (map SysTools.Option as_opts ++
914 [ SysTools.Option "-c"
915 , SysTools.Option "-o"
916 , SysTools.FileOption "" real_o
917 , SysTools.FileOption "" input_s
920 mapM_ assemble_file [1..n]
922 output_fn <- get_output_fn StopLn maybe_loc
923 return (StopLn, dflags, maybe_loc, output_fn)
926 -----------------------------------------------------------------------------
928 -- Run ilx2il over the ILX output, getting an IL file
930 runPhase Ilx2Il stop dflags _basename _suff input_fn get_output_fn maybe_loc
931 = do let ilx2il_opts = getOpts dflags opt_I
932 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
933 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
934 SysTools.Option "mscorlib",
935 SysTools.Option "-o",
936 SysTools.FileOption "" output_fn,
937 SysTools.FileOption "" input_fn ])
940 -----------------------------------------------------------------------------
942 -- Run ilasm over the IL, getting a DLL
944 runPhase Ilasm stop dflags _basename _suff input_fn get_output_fn maybe_loc
945 = do let ilasm_opts = getOpts dflags opt_i
946 SysTools.runIlasm (map SysTools.Option ilasm_opts
947 ++ [ SysTools.Option "/QUIET",
948 SysTools.Option "/DLL",
949 SysTools.FileOption "/OUT=" output_fn,
950 SysTools.FileOption "" input_fn ])
955 -----------------------------------------------------------------------------
956 -- MoveBinary sort-of-phase
957 -- After having produced a binary, move it somewhere else and generate a
958 -- wrapper script calling the binary. Currently, we need this only in
959 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
960 -- central directory.
961 -- This is called from staticLink below, after linking. I haven't made it
962 -- a separate phase to minimise interfering with other modules, and
963 -- we don't need the generality of a phase (MoveBinary is always
964 -- done after linking and makes only sense in a parallel setup) -- HWL
966 runPhase_MoveBinary input_fn
969 pvm_root <- getEnv "PVM_ROOT"
970 pvm_arch <- getEnv "PVM_ARCH"
972 pvm_executable_base = "=" ++ input_fn
973 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
974 -- nuke old binary; maybe use configur'ed names for cp and rm?
975 system ("rm -f " ++ pvm_executable)
976 -- move the newly created binary into PVM land
977 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
978 -- generate a wrapper script for running a parallel prg under PVM
979 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
982 -- generates a Perl skript starting a parallel prg under PVM
983 mk_pvm_wrapper_script :: String -> String -> String -> String
984 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
986 "eval 'exec perl -S $0 ${1+\"$@\"}'",
987 " if $running_under_some_shell;",
988 "# =!=!=!=!=!=!=!=!=!=!=!",
989 "# This script is automatically generated: DO NOT EDIT!!!",
990 "# Generated by Glasgow Haskell Compiler",
991 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
993 "$pvm_executable = '" ++ pvm_executable ++ "';",
994 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
995 "$SysMan = '" ++ sysMan ++ "';",
997 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
998 "# first, some magical shortcuts to run "commands" on the binary",
999 "# (which is hidden)",
1000 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1001 " local($cmd) = $1;",
1002 " system("$cmd $pvm_executable");",
1003 " exit(0); # all done",
1006 "# Now, run the real binary; process the args first",
1007 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1009 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1010 "@nonPVM_args = ();",
1011 "$in_RTS_args = 0;",
1013 "args: while ($a = shift(@ARGV)) {",
1014 " if ( $a eq '+RTS' ) {",
1015 " $in_RTS_args = 1;",
1016 " } elsif ( $a eq '-RTS' ) {",
1017 " $in_RTS_args = 0;",
1019 " if ( $a eq '-d' && $in_RTS_args ) {",
1021 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1022 " $nprocessors = $1;",
1023 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1024 " $nprocessors = $1;",
1026 " push(@nonPVM_args, $a);",
1030 "local($return_val) = 0;",
1031 "# Start the parallel execution by calling SysMan",
1032 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1033 "$return_val = $?;",
1034 "# ToDo: fix race condition moving files and flushing them!!",
1035 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1036 "exit($return_val);"
1039 -----------------------------------------------------------------------------
1040 -- Complain about non-dynamic flags in OPTIONS pragmas
1042 checkProcessArgsResult flags filename
1043 = do when (notNull flags) (throwDyn (ProgramError (
1044 showSDoc (hang (text filename <> char ':')
1045 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1046 hsep (map text flags)))
1049 -----------------------------------------------------------------------------
1050 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1052 getHCFilePackages :: FilePath -> IO [PackageId]
1053 getHCFilePackages filename =
1054 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1057 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1058 return (map stringToPackageId (words rest))
1062 -----------------------------------------------------------------------------
1063 -- Static linking, of .o files
1065 -- The list of packages passed to link is the list of packages on
1066 -- which this program depends, as discovered by the compilation
1067 -- manager. It is combined with the list of packages that the user
1068 -- specifies on the command line with -package flags.
1070 -- In one-shot linking mode, we can't discover the package
1071 -- dependencies (because we haven't actually done any compilation or
1072 -- read any interface files), so the user must explicitly specify all
1075 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1076 staticLink dflags o_files dep_packages = do
1077 let verb = getVerbFlag dflags
1078 static <- readIORef v_Static
1079 no_hs_main <- readIORef v_NoHsMain
1081 -- get the full list of packages to link with, by combining the
1082 -- explicit packages with the auto packages and all of their
1083 -- dependencies, and eliminating duplicates.
1085 o_file <- readIORef v_Output_file
1086 #if defined(mingw32_HOST_OS)
1087 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1089 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1092 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1093 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1095 lib_paths <- readIORef v_Library_paths
1096 let lib_path_opts = map ("-L"++) lib_paths
1098 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1100 #ifdef darwin_TARGET_OS
1101 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1102 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1104 framework_paths <- readIORef v_Framework_paths
1105 let framework_path_opts = map ("-F"++) framework_paths
1107 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1108 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1109 frameworks <- readIORef v_Cmdline_frameworks
1110 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1111 -- reverse because they're added in reverse order from the cmd line
1114 -- probably _stub.o files
1115 extra_ld_inputs <- readIORef v_Ld_inputs
1117 -- opts from -optl-<blah> (including -l<blah> options)
1118 extra_ld_opts <- getStaticOpts v_Opt_l
1120 ways <- readIORef v_Ways
1122 -- Here are some libs that need to be linked at the *end* of
1123 -- the command line, because they contain symbols that are referred to
1124 -- by the RTS. We can't therefore use the ordinary way opts for these.
1126 debug_opts | WayDebug `elem` ways = [
1127 #if defined(HAVE_LIBBFD)
1134 thread_opts | WayThreaded `elem` ways = [
1135 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1138 #if defined(osf3_TARGET_OS)
1144 (md_c_flags, _) <- machdepCCOpts dflags
1145 SysTools.runLink dflags (
1146 [ SysTools.Option verb
1147 , SysTools.Option "-o"
1148 , SysTools.FileOption "" output_fn
1150 ++ map SysTools.Option (
1156 #ifdef darwin_TARGET_OS
1157 ++ framework_path_opts
1160 ++ pkg_lib_path_opts
1162 #ifdef darwin_TARGET_OS
1163 ++ pkg_framework_path_opts
1164 ++ pkg_framework_opts
1170 -- parallel only: move binary to another dir -- HWL
1171 ways_ <- readIORef v_Ways
1172 when (WayPar `elem` ways_)
1173 (do success <- runPhase_MoveBinary output_fn
1174 if success then return ()
1175 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1177 -----------------------------------------------------------------------------
1178 -- Making a DLL (only for Win32)
1180 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1181 doMkDLL dflags o_files dep_packages = do
1182 let verb = getVerbFlag dflags
1183 static <- readIORef v_Static
1184 no_hs_main <- readIORef v_NoHsMain
1186 o_file <- readIORef v_Output_file
1187 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1189 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1190 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1192 lib_paths <- readIORef v_Library_paths
1193 let lib_path_opts = map ("-L"++) lib_paths
1195 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1197 -- probably _stub.o files
1198 extra_ld_inputs <- readIORef v_Ld_inputs
1200 -- opts from -optdll-<blah>
1201 extra_ld_opts <- getStaticOpts v_Opt_dll
1203 let pstate = pkgState dflags
1204 rts_id | ExtPackage id <- rtsPackageId pstate = id
1205 | otherwise = panic "staticLink: rts package missing"
1206 base_id | ExtPackage id <- basePackageId pstate = id
1207 | otherwise = panic "staticLink: base package missing"
1208 rts_pkg = getPackageDetails pstate rts_id
1209 base_pkg = getPackageDetails pstate base_id
1211 let extra_os = if static || no_hs_main
1213 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1214 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1216 (md_c_flags, _) <- machdepCCOpts dflags
1217 SysTools.runMkDLL dflags
1218 ([ SysTools.Option verb
1219 , SysTools.Option "-o"
1220 , SysTools.FileOption "" output_fn
1222 ++ map SysTools.Option (
1226 ++ [ "--target=i386-mingw32" ]
1230 ++ pkg_lib_path_opts
1232 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1234 else [ "--export-all" ])
1237 -- -----------------------------------------------------------------------------
1240 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1241 doCpp dflags raw include_cc_opts input_fn output_fn = do
1242 let hscpp_opts = getOpts dflags opt_P
1244 cmdline_include_paths <- readIORef v_Include_paths
1246 pkg_include_dirs <- getPackageIncludePath dflags []
1247 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1248 (cmdline_include_paths ++ pkg_include_dirs)
1250 let verb = getVerbFlag dflags
1252 cc_opts <- if not include_cc_opts
1254 else do let optc = getOpts dflags opt_c
1255 (md_c_flags, _) <- machdepCCOpts dflags
1256 return (optc ++ md_c_flags)
1258 let cpp_prog args | raw = SysTools.runCpp dflags args
1259 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1262 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1263 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1264 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1265 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1266 -- remember, in code we *compile*, the HOST is the same our TARGET,
1267 -- and BUILD is the same as our HOST.
1269 cpp_prog ([SysTools.Option verb]
1270 ++ map SysTools.Option include_paths
1271 ++ map SysTools.Option hsSourceCppOpts
1272 ++ map SysTools.Option hscpp_opts
1273 ++ map SysTools.Option cc_opts
1274 ++ map SysTools.Option target_defs
1275 ++ [ SysTools.Option "-x"
1276 , SysTools.Option "c"
1277 , SysTools.Option input_fn
1278 -- We hackily use Option instead of FileOption here, so that the file
1279 -- name is not back-slashed on Windows. cpp is capable of
1280 -- dealing with / in filenames, so it works fine. Furthermore
1281 -- if we put in backslashes, cpp outputs #line directives
1282 -- with *double* backslashes. And that in turn means that
1283 -- our error messages get double backslashes in them.
1284 -- In due course we should arrange that the lexer deals
1285 -- with these \\ escapes properly.
1286 , SysTools.Option "-o"
1287 , SysTools.FileOption "" output_fn
1290 -- -----------------------------------------------------------------------------
1293 hscNextPhase :: HscSource -> HscTarget -> IO Phase
1294 hscNextPhase HsBootFile hsc_lang
1297 hscNextPhase other hsc_lang = do
1298 split <- readIORef v_Split_object_files
1299 return (case hsc_lang of
1301 HscAsm | split -> SplitMangle
1303 HscNothing -> StopLn
1304 HscInterpreted -> StopLn
1308 hscMaybeAdjustTarget :: Phase -> HscSource -> HscTarget -> IO HscTarget
1309 hscMaybeAdjustTarget stop HsBootFile current_hsc_lang
1310 = return HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1311 hscMaybeAdjustTarget stop other current_hsc_lang
1312 = do { keep_hc <- readIORef v_Keep_hc_files
1314 -- don't change the lang if we're interpreting
1315 | current_hsc_lang == HscInterpreted = current_hsc_lang
1317 -- force -fvia-C if we are being asked for a .hc file
1318 | HCc <- stop = HscC
1320 -- otherwise, stick to the plan
1321 | otherwise = current_hsc_lang