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 runPipeline, staticLink,
16 -- Interfaces for the compilation manager (interpreted/batch-mode)
18 compile, CompResult(..),
25 #include "HsVersions.h"
34 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
35 import qualified SysTools
44 import RdrName ( GlobalRdrEnv )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
50 import ParserCoreUtils ( getCoreModuleName )
53 import DATA_IOREF ( readIORef, writeIORef )
55 import Time ( ClockTime )
63 -- ---------------------------------------------------------------------------
66 -- Just preprocess a file, put the result in a temp. file (used by the
67 -- compilation manager during the summary phase).
69 preprocess :: DynFlags -> FilePath -> IO FilePath
70 preprocess dflags filename =
71 ASSERT(isHaskellSrcFilename filename)
72 do runPipeline (StopBefore Hsc) dflags ("preprocess")
73 False{-temporary output file-}
74 Nothing{-no specific output file-}
76 Nothing{-no ModLocation-}
78 -- ---------------------------------------------------------------------------
81 -- Compile a single module, under the control of the compilation manager.
83 -- This is the interface between the compilation manager and the
84 -- compiler proper (hsc), where we deal with tedious details like
85 -- reading the OPTIONS pragma from the source file, and passing the
86 -- output of hsc through the C compiler.
88 -- The driver sits between 'compile' and 'hscMain', translating calls
89 -- to the former into calls to the latter, and results from the latter
90 -- into results from the former. It does things like preprocessing
91 -- the .hs file if necessary, and compiling up the .stub_c files to
92 -- generate Linkables.
94 -- NB. No old interface can also mean that the source has changed.
99 -> ClockTime -- timestamp of original source file
100 -> Bool -- True <=> source unchanged
101 -> Bool -- True <=> have object
102 -> Maybe ModIface -- old interface, if available
106 = CompOK ModDetails -- New details
107 (Maybe GlobalRdrEnv) -- Lexical environment for the module
108 -- (Maybe because we may have loaded it from
109 -- its precompiled interface)
110 ModIface -- New iface
111 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
112 -- (old code is still valid)
117 compile hsc_env this_mod location src_timestamp
118 source_unchanged have_object
121 let dyn_flags = hsc_dflags hsc_env
124 (showSDoc (text "Compiling" <+> ppr this_mod))
126 let verb = verbosity dyn_flags
127 let input_fn = expectJust "compile:hs" (ml_hs_file location)
128 let input_fnpp = expectJust "compile:hspp" (ml_hspp_file location)
130 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
132 -- add in the OPTIONS from the source file
133 opts <- getOptionsFromSource input_fnpp
134 (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
135 checkProcessArgsResult unhandled_flags input_fn
137 let (basename, _) = splitFilename input_fn
139 -- We add the directory in which the .hs files resides) to the import path.
140 -- This is needed when we try to compile the .hc file later, if it
141 -- imports a _stub.h file that we created here.
142 let current_dir = directoryOf basename
143 old_paths <- readIORef v_Include_paths
144 writeIORef v_Include_paths (current_dir : old_paths)
145 -- put back the old include paths afterward.
146 later (writeIORef v_Include_paths old_paths) $ do
148 -- figure out what lang we're generating
149 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
150 -- figure out what the next phase should be
151 next_phase <- hscNextPhase hsc_lang
152 -- figure out what file to generate the output into
153 get_output_fn <- genOutputFilenameFunc False Nothing next_phase basename
154 output_fn <- get_output_fn next_phase (Just location)
156 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
157 hscOutName = output_fn,
158 hscStubCOutName = basename ++ "_stub.c",
159 hscStubHOutName = basename ++ "_stub.h",
160 extCoreName = basename ++ ".hcr" }
162 -- -no-recomp should also work with --make
163 do_recomp <- readIORef v_Recomp
164 let source_unchanged' = source_unchanged && do_recomp
165 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
168 hsc_result <- hscMain hsc_env' printErrorsAndWarnings this_mod location
169 source_unchanged' have_object old_iface
172 HscFail -> return CompErrs
174 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
176 HscRecomp details rdr_env iface
177 stub_h_exists stub_c_exists maybe_interpreted_code -> do
179 maybe_stub_o <- compileStub dyn_flags' 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], src_timestamp)
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 (StopBefore Ln) dyn_flags ""
207 True Nothing output_fn (Just location)
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 rdr_env 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 (StopBefore Ln) dflags "stub-compile"
227 True{-persistent output-}
228 Nothing{-no specific output file-}
230 Nothing{-no ModLocation-}
234 -- ---------------------------------------------------------------------------
237 link :: GhciMode -- interactive or batch
238 -> DynFlags -- dynamic flags
239 -> Bool -- attempt linking in batch mode?
240 -> HomePackageTable -- what to link
243 -- For the moment, in the batch linker, we don't bother to tell doLink
244 -- which packages to link -- it just tries all that are available.
245 -- batch_attempt_linking should only be *looked at* in batch mode. It
246 -- should only be True if the upsweep was successful and someone
247 -- exports main, i.e., we have good reason to believe that linking
251 link Interactive dflags batch_attempt_linking hpt
252 = do -- Not Linking...(demand linker will do the job)
256 link Batch 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 hm_linkable home_mod_infos
268 when (verb >= 3) $ do
269 hPutStrLn stderr "link: linkables are ..."
270 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
272 -- check for the -no-link flag
273 omit_linking <- readIORef v_NoLink
275 then do when (verb >= 3) $
276 hPutStrLn stderr "link(batch): linking omitted (-no-link flag given)."
281 hPutStrLn stderr "Linking ..."
283 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
284 obj_files = concatMap getOfiles linkables
286 -- Don't showPass in Batch mode; doLink will do that for us.
287 staticLink dflags obj_files pkg_deps
289 when (verb >= 3) (hPutStrLn stderr "link: done")
291 -- staticLink only returns if it succeeds
295 = do when (verb >= 3) $ do
296 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
297 hPutStrLn stderr " Main.main not exported; not linking."
300 verb = verbosity dflags
302 -- ---------------------------------------------------------------------------
303 -- Run a compilation pipeline, consisting of multiple phases.
305 -- The DynFlags can be modified by phases in the pipeline (eg. by
306 -- OPTIONS pragmas), and the changes affect later phases in the
307 -- pipeline, but we throw away the resulting DynFlags at the end.
310 :: GhcMode -- when to stop
311 -> DynFlags -- dynamic flags
312 -> String -- "stop after" flag
313 -> Bool -- final output is persistent?
314 -> Maybe FilePath -- where to put the output, optionally
315 -> FilePath -- input filename
316 -> Maybe ModLocation -- a ModLocation for this module, if we have one
317 -> IO FilePath -- output filename
319 runPipeline todo dflags stop_flag keep_output
320 maybe_output_filename input_fn maybe_loc
322 split <- readIORef v_Split_object_files
323 let (basename, suffix) = splitFilename input_fn
324 start_phase = startPhase suffix
326 stop_phase = case todo of
327 StopBefore As | split -> SplitAs
328 StopBefore phase -> phase
333 -- We want to catch cases of "you can't get there from here" before
334 -- we start the pipeline, because otherwise it will just run off the
337 -- There is a partial ordering on phases, where A < B iff A occurs
338 -- before B in a normal compilation pipeline.
340 when (not (start_phase `happensBefore` stop_phase)) $
342 ("flag `" ++ stop_flag
343 ++ "' is incompatible with source file `"
346 -- generate a function which will be used to calculate output file names
348 get_output_fn <- genOutputFilenameFunc keep_output maybe_output_filename
351 -- and execute the pipeline...
352 (output_fn, maybe_loc) <-
353 pipeLoop dflags start_phase stop_phase input_fn basename suffix
354 get_output_fn maybe_loc
356 -- sometimes, a compilation phase doesn't actually generate any output
357 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
358 -- stage, but we wanted to keep the output, then we have to explicitly
361 then do final_fn <- get_output_fn stop_phase maybe_loc
362 when (final_fn /= output_fn) $
363 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
364 ++ "'") output_fn final_fn
370 pipeLoop :: DynFlags -> Phase -> Phase -> FilePath -> String -> Suffix
371 -> (Phase -> Maybe ModLocation -> IO FilePath)
372 -> Maybe ModLocation -> IO (FilePath, Maybe ModLocation)
374 pipeLoop dflags phase stop_phase input_fn orig_basename orig_suff
375 get_output_fn maybe_loc
377 | phase == stop_phase = return (input_fn, maybe_loc) -- all done
379 | not (phase `happensBefore` stop_phase) =
380 -- Something has gone wrong. We'll try to cover all the cases when
381 -- this could happen, so if we reach here it is a panic.
382 -- eg. it might happen if the -C flag is used on a source file that
383 -- has {-# OPTIONS -fasm #-}.
384 panic ("pipeLoop: at phase " ++ show phase ++
385 " but I wanted to stop at phase " ++ show stop_phase)
388 maybe_next_phase <- runPhase phase dflags orig_basename
389 orig_suff input_fn get_output_fn maybe_loc
390 case maybe_next_phase of
391 (Nothing, dflags, maybe_loc, output_fn) -> do
392 -- we stopped early, but return the *final* filename
393 -- (it presumably already exists)
394 final_fn <- get_output_fn stop_phase maybe_loc
395 return (final_fn, maybe_loc)
396 (Just next_phase, dflags', maybe_loc, output_fn) ->
397 pipeLoop dflags' next_phase stop_phase output_fn
398 orig_basename orig_suff get_output_fn maybe_loc
401 genOutputFilenameFunc :: Bool -> Maybe FilePath -> Phase -> String
402 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
403 genOutputFilenameFunc keep_final_output maybe_output_filename
406 hcsuf <- readIORef v_HC_suf
407 odir <- readIORef v_Output_dir
408 osuf <- readIORef v_Object_suf
409 keep_hc <- readIORef v_Keep_hc_files
411 keep_il <- readIORef v_Keep_il_files
412 keep_ilx <- readIORef v_Keep_ilx_files
414 keep_raw_s <- readIORef v_Keep_raw_s_files
415 keep_s <- readIORef v_Keep_s_files
417 myPhaseInputExt HCc | Just s <- hcsuf = s
418 myPhaseInputExt Ln = osuf
419 myPhaseInputExt other = phaseInputExt other
421 func next_phase maybe_location
422 | is_last_phase, Just f <- maybe_output_filename = return f
423 | is_last_phase && keep_final_output = persistent_fn
424 | keep_this_output = persistent_fn
425 | otherwise = newTempName suffix
428 is_last_phase = next_phase == stop_phase
430 -- sometimes, we keep output from intermediate stages
434 Mangle | keep_raw_s -> True
436 HCc | keep_hc -> True
439 suffix = myPhaseInputExt next_phase
441 -- persistent object files get put in odir
443 | Ln <- next_phase = return odir_persistent
444 | otherwise = return persistent
446 persistent = basename ++ '.':suffix
449 | Just loc <- maybe_location = ml_obj_file loc
450 | Just d <- odir = replaceFilenameDirectory persistent d
451 | otherwise = persistent
456 -- -----------------------------------------------------------------------------
457 -- Each phase in the pipeline returns the next phase to execute, and the
458 -- name of the file in which the output was placed.
460 -- We must do things dynamically this way, because we often don't know
461 -- what the rest of the phases will be until part-way through the
462 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
463 -- of a source file can change the latter stages of the pipeline from
464 -- taking the via-C route to using the native code generator.
468 -> String -- basename of original input source
469 -> String -- its extension
470 -> FilePath -- name of file which contains the input to this phase.
471 -> (Phase -> Maybe ModLocation -> IO FilePath)
472 -- how to calculate the output filename
473 -> Maybe ModLocation -- the ModLocation, if we have one
474 -> IO (Maybe Phase, -- next phase
475 DynFlags, -- new dynamic flags
476 Maybe ModLocation, -- the ModLocation, if we have one
477 FilePath) -- output filename
479 -------------------------------------------------------------------------------
482 runPhase Unlit dflags _basename _suff input_fn get_output_fn maybe_loc
483 = do let unlit_flags = getOpts dflags opt_L
484 -- The -h option passes the file name for unlit to put in a #line directive
485 output_fn <- get_output_fn Cpp maybe_loc
487 SysTools.runUnlit dflags
488 (map SysTools.Option unlit_flags ++
489 [ SysTools.Option "-h"
490 , SysTools.Option input_fn
491 , SysTools.FileOption "" input_fn
492 , SysTools.FileOption "" output_fn
495 return (Just Cpp, dflags, maybe_loc, output_fn)
497 -------------------------------------------------------------------------------
500 runPhase Cpp dflags basename suff input_fn get_output_fn maybe_loc
501 = do src_opts <- getOptionsFromSource input_fn
502 (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
503 checkProcessArgsResult unhandled_flags (basename++'.':suff)
505 if not (cppFlag dflags) then
506 -- no need to preprocess CPP, just pass input file along
507 -- to the next phase of the pipeline.
508 return (Just HsPp, dflags, maybe_loc, input_fn)
510 output_fn <- get_output_fn HsPp maybe_loc
511 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
512 return (Just HsPp, dflags, maybe_loc, output_fn)
514 -------------------------------------------------------------------------------
517 runPhase HsPp dflags basename suff input_fn get_output_fn maybe_loc
518 = do if not (ppFlag dflags) then
519 -- no need to preprocess, just pass input file along
520 -- to the next phase of the pipeline.
521 return (Just Hsc, dflags, maybe_loc, input_fn)
523 let hspp_opts = getOpts dflags opt_F
524 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
525 let orig_fn = basename ++ '.':suff
526 output_fn <- get_output_fn Hsc maybe_loc
527 SysTools.runPp dflags
528 ( [ SysTools.Option orig_fn
529 , SysTools.Option input_fn
530 , SysTools.FileOption "" output_fn
532 map SysTools.Option hs_src_pp_opts ++
533 map SysTools.Option hspp_opts
535 return (Just Hsc, dflags, maybe_loc, output_fn)
537 -----------------------------------------------------------------------------
540 -- Compilation of a single module, in "legacy" mode (_not_ under
541 -- the direction of the compilation manager).
542 runPhase Hsc dflags basename suff input_fn get_output_fn _maybe_loc = do
543 todo <- readIORef v_GhcMode
544 if todo == DoMkDependHS then do
545 locn <- doMkDependHSPhase dflags basename suff input_fn
546 return (Nothing, dflags, Just locn, input_fn) -- Ln is a dummy stop phase
549 -- normal Hsc mode, not mkdependHS
551 -- we add the current directory (i.e. the directory in which
552 -- the .hs files resides) to the import path, since this is
553 -- what gcc does, and it's probably what you want.
554 let current_dir = directoryOf basename
556 paths <- readIORef v_Include_paths
557 writeIORef v_Include_paths (current_dir : paths)
559 -- gather the imports and module name
561 if isExtCoreFilename ('.':suff)
563 -- no explicit imports in ExtCore input.
564 m <- getCoreModuleName input_fn
565 return ([], [], mkModule m)
567 getImportsFromFile input_fn
569 -- build a ModLocation to pass to hscMain.
570 location' <- mkHomeModLocation mod_name (basename ++ '.':suff)
572 -- take -ohi into account if present
573 ohi <- readIORef v_Output_hi
574 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
575 | otherwise = location'
577 -- figure out if the source has changed, for recompilation avoidance.
578 -- only do this if we're eventually going to generate a .o file.
579 -- (ToDo: do when generating .hc files too?)
581 -- Setting source_unchanged to True means that M.o seems
582 -- to be up to date wrt M.hs; so no need to recompile unless imports have
583 -- changed (which the compiler itself figures out).
584 -- Setting source_unchanged to False tells the compiler that M.o is out of
585 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
586 do_recomp <- readIORef v_Recomp
587 expl_o_file <- readIORef v_Output_file
589 let o_file -- if the -o option is given and IT IS THE OBJECT FILE FOR
590 -- THIS COMPILATION, then use that to determine if the
591 -- source is unchanged.
592 | Just x <- expl_o_file, todo == StopBefore Ln = x
593 | otherwise = ml_obj_file location
596 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
598 else do t1 <- getModificationTime (basename ++ '.':suff)
599 o_file_exists <- doesFileExist o_file
601 then return False -- Need to recompile
602 else do t2 <- getModificationTime o_file
608 hsc_lang <- hscMaybeAdjustLang (hscLang dflags)
609 next_phase <- hscNextPhase hsc_lang
610 output_fn <- get_output_fn next_phase (Just location)
612 let dflags' = dflags { hscLang = hsc_lang,
613 hscOutName = output_fn,
614 hscStubCOutName = basename ++ "_stub.c",
615 hscStubHOutName = basename ++ "_stub.h",
616 extCoreName = basename ++ ".hcr" }
617 hsc_env <- newHscEnv OneShot dflags'
620 result <- hscMain hsc_env printErrorsAndWarnings mod_name
621 location{ ml_hspp_file=Just input_fn }
628 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
630 HscNoRecomp details iface -> do
631 SysTools.touch dflags' "Touching object file" o_file
632 return (Nothing, dflags', Just location, output_fn)
634 HscRecomp _details _rdr_env _iface
635 stub_h_exists stub_c_exists
636 _maybe_interpreted_code -> do
639 maybe_stub_o <- compileStub dflags' stub_c_exists
642 Just stub_o -> add v_Ld_inputs stub_o
643 case hscLang dflags' of
644 HscNothing -> return (Nothing, dflags', Just location, output_fn)
645 _ -> return (Just next_phase, dflags', Just location, output_fn)
647 -----------------------------------------------------------------------------
650 runPhase CmmCpp dflags basename suff input_fn get_output_fn maybe_loc
652 output_fn <- get_output_fn Cmm maybe_loc
653 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
654 return (Just Cmm, dflags, maybe_loc, output_fn)
656 runPhase Cmm dflags basename suff input_fn get_output_fn maybe_loc
658 hsc_lang <- hscMaybeAdjustLang (hscLang dflags)
659 next_phase <- hscNextPhase hsc_lang
660 output_fn <- get_output_fn next_phase maybe_loc
662 let dflags' = dflags { hscLang = hsc_lang,
663 hscOutName = output_fn,
664 hscStubCOutName = basename ++ "_stub.c",
665 hscStubHOutName = basename ++ "_stub.h",
666 extCoreName = basename ++ ".hcr" }
668 ok <- hscCmmFile dflags' input_fn
670 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
672 return (Just next_phase, dflags, maybe_loc, output_fn)
674 -----------------------------------------------------------------------------
677 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
678 -- way too many hacks, and I can't say I've ever used it anyway.
680 runPhase cc_phase dflags basename suff input_fn get_output_fn maybe_loc
681 | cc_phase == Cc || cc_phase == HCc
682 = do let cc_opts = getOpts dflags opt_c
683 cmdline_include_paths <- readIORef v_Include_paths
685 split <- readIORef v_Split_object_files
686 mangle <- readIORef v_Do_asm_mangling
688 let hcc = cc_phase == HCc
691 | hcc && mangle = Mangle
694 output_fn <- get_output_fn next_phase maybe_loc
696 -- HC files have the dependent packages stamped into them
697 pkgs <- if hcc then getHCFilePackages input_fn else return []
699 -- add package include paths even if we're just compiling .c
700 -- files; this is the Value Add(TM) that using ghc instead of
702 pkg_include_dirs <- getPackageIncludePath dflags pkgs
703 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
704 (cmdline_include_paths ++ pkg_include_dirs)
706 mangle <- readIORef v_Do_asm_mangling
707 (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
709 let verb = getVerbFlag dflags
711 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
713 split_objs <- readIORef v_Split_object_files
714 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
717 excessPrecision <- readIORef v_Excess_precision
719 -- force the C compiler to interpret this file as C when
720 -- compiling .hc files, by adding the -x c option.
722 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
725 SysTools.runCc dflags (langopt ++
726 [ SysTools.FileOption "" input_fn
727 , SysTools.Option "-o"
728 , SysTools.FileOption "" output_fn
730 ++ map SysTools.Option (
732 ++ (if cc_phase == HCc && mangle
735 ++ [ verb, "-S", "-Wimplicit", "-O" ]
736 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
739 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
744 return (Just next_phase, dflags, maybe_loc, output_fn)
746 -- ToDo: postprocess the output from gcc
748 -----------------------------------------------------------------------------
751 runPhase Mangle dflags _basename _suff input_fn get_output_fn maybe_loc
752 = do let mangler_opts = getOpts dflags opt_m
753 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
754 then do let n_regs = stolen_x86_regs dflags
755 return [ show n_regs ]
758 split <- readIORef v_Split_object_files
760 | split = SplitMangle
762 output_fn <- get_output_fn next_phase maybe_loc
764 SysTools.runMangle dflags (map SysTools.Option mangler_opts
765 ++ [ SysTools.FileOption "" input_fn
766 , SysTools.FileOption "" output_fn
768 ++ map SysTools.Option machdep_opts)
770 return (Just next_phase, dflags, maybe_loc, output_fn)
772 -----------------------------------------------------------------------------
775 runPhase SplitMangle dflags _basename _suff input_fn get_output_fn maybe_loc
776 = do -- tmp_pfx is the prefix used for the split .s files
777 -- We also use it as the file to contain the no. of split .s files (sigh)
778 split_s_prefix <- SysTools.newTempName "split"
779 let n_files_fn = split_s_prefix
781 SysTools.runSplit dflags
782 [ SysTools.FileOption "" input_fn
783 , SysTools.FileOption "" split_s_prefix
784 , SysTools.FileOption "" n_files_fn
787 -- Save the number of split files for future references
788 s <- readFile n_files_fn
789 let n_files = read s :: Int
790 writeIORef v_Split_info (split_s_prefix, n_files)
792 -- Remember to delete all these files
793 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
796 return (Just SplitAs, dflags, maybe_loc, "**splitmangle**")
797 -- we don't use the filename
799 -----------------------------------------------------------------------------
802 runPhase As dflags _basename _suff input_fn get_output_fn maybe_loc
803 = do let as_opts = getOpts dflags opt_a
804 cmdline_include_paths <- readIORef v_Include_paths
806 output_fn <- get_output_fn Ln maybe_loc
808 -- we create directories for the object file, because it
809 -- might be a hierarchical module.
810 createDirectoryHierarchy (directoryOf output_fn)
812 SysTools.runAs dflags
813 (map SysTools.Option as_opts
814 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
815 ++ [ SysTools.Option "-c"
816 , SysTools.FileOption "" input_fn
817 , SysTools.Option "-o"
818 , SysTools.FileOption "" output_fn
821 return (Just Ln, dflags, maybe_loc, output_fn)
824 runPhase SplitAs dflags basename _suff _input_fn get_output_fn maybe_loc
825 = do let as_opts = getOpts dflags opt_a
827 (split_s_prefix, n) <- readIORef v_Split_info
829 odir <- readIORef v_Output_dir
830 let real_odir = case odir of
831 Nothing -> basename ++ "_split"
835 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
836 let output_o = replaceFilenameDirectory
837 (basename ++ "__" ++ show n ++ ".o")
839 real_o <- osuf_ify output_o
840 SysTools.runAs dflags
841 (map SysTools.Option as_opts ++
842 [ SysTools.Option "-c"
843 , SysTools.Option "-o"
844 , SysTools.FileOption "" real_o
845 , SysTools.FileOption "" input_s
848 mapM_ assemble_file [1..n]
850 output_fn <- get_output_fn Ln maybe_loc
851 return (Just Ln, dflags, maybe_loc, output_fn)
854 -----------------------------------------------------------------------------
856 -- Run ilx2il over the ILX output, getting an IL file
858 runPhase Ilx2Il dflags _basename _suff input_fn get_output_fn maybe_loc
859 = do let ilx2il_opts = getOpts dflags opt_I
860 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
861 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
862 SysTools.Option "mscorlib",
863 SysTools.Option "-o",
864 SysTools.FileOption "" output_fn,
865 SysTools.FileOption "" input_fn ])
868 -----------------------------------------------------------------------------
870 -- Run ilasm over the IL, getting a DLL
872 runPhase Ilasm dflags _basename _suff input_fn get_output_fn maybe_loc
873 = do let ilasm_opts = getOpts dflags opt_i
874 SysTools.runIlasm (map SysTools.Option ilasm_opts
875 ++ [ SysTools.Option "/QUIET",
876 SysTools.Option "/DLL",
877 SysTools.FileOption "/OUT=" output_fn,
878 SysTools.FileOption "" input_fn ])
883 -----------------------------------------------------------------------------
884 -- MoveBinary sort-of-phase
885 -- After having produced a binary, move it somewhere else and generate a
886 -- wrapper script calling the binary. Currently, we need this only in
887 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
888 -- central directory.
889 -- This is called from staticLink below, after linking. I haven't made it
890 -- a separate phase to minimise interfering with other modules, and
891 -- we don't need the generality of a phase (MoveBinary is always
892 -- done after linking and makes only sense in a parallel setup) -- HWL
894 runPhase_MoveBinary input_fn
897 pvm_root <- getEnv "PVM_ROOT"
898 pvm_arch <- getEnv "PVM_ARCH"
900 pvm_executable_base = "=" ++ input_fn
901 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
902 -- nuke old binary; maybe use configur'ed names for cp and rm?
903 system ("rm -f " ++ pvm_executable)
904 -- move the newly created binary into PVM land
905 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
906 -- generate a wrapper script for running a parallel prg under PVM
907 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
910 -- generates a Perl skript starting a parallel prg under PVM
911 mk_pvm_wrapper_script :: String -> String -> String -> String
912 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
914 "eval 'exec perl -S $0 ${1+\"$@\"}'",
915 " if $running_under_some_shell;",
916 "# =!=!=!=!=!=!=!=!=!=!=!",
917 "# This script is automatically generated: DO NOT EDIT!!!",
918 "# Generated by Glasgow Haskell Compiler",
919 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
921 "$pvm_executable = '" ++ pvm_executable ++ "';",
922 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
923 "$SysMan = '" ++ sysMan ++ "';",
925 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
926 "# first, some magical shortcuts to run "commands" on the binary",
927 "# (which is hidden)",
928 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
929 " local($cmd) = $1;",
930 " system("$cmd $pvm_executable");",
931 " exit(0); # all done",
934 "# Now, run the real binary; process the args first",
935 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
937 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
938 "@nonPVM_args = ();",
941 "args: while ($a = shift(@ARGV)) {",
942 " if ( $a eq '+RTS' ) {",
943 " $in_RTS_args = 1;",
944 " } elsif ( $a eq '-RTS' ) {",
945 " $in_RTS_args = 0;",
947 " if ( $a eq '-d' && $in_RTS_args ) {",
949 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
950 " $nprocessors = $1;",
951 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
952 " $nprocessors = $1;",
954 " push(@nonPVM_args, $a);",
958 "local($return_val) = 0;",
959 "# Start the parallel execution by calling SysMan",
960 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
962 "# ToDo: fix race condition moving files and flushing them!!",
963 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
967 -----------------------------------------------------------------------------
968 -- Complain about non-dynamic flags in OPTIONS pragmas
970 checkProcessArgsResult flags filename
971 = do when (notNull flags) (throwDyn (ProgramError (
972 showSDoc (hang (text filename <> char ':')
973 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
974 hsep (map text flags)))
977 -----------------------------------------------------------------------------
978 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
980 getHCFilePackages :: FilePath -> IO [PackageId]
981 getHCFilePackages filename =
982 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
985 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
986 return (map stringToPackageId (words rest))
990 -----------------------------------------------------------------------------
991 -- Static linking, of .o files
993 -- The list of packages passed to link is the list of packages on
994 -- which this program depends, as discovered by the compilation
995 -- manager. It is combined with the list of packages that the user
996 -- specifies on the command line with -package flags.
998 -- In one-shot linking mode, we can't discover the package
999 -- dependencies (because we haven't actually done any compilation or
1000 -- read any interface files), so the user must explicitly specify all
1003 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1004 staticLink dflags o_files dep_packages = do
1005 let verb = getVerbFlag dflags
1006 static <- readIORef v_Static
1007 no_hs_main <- readIORef v_NoHsMain
1009 -- get the full list of packages to link with, by combining the
1010 -- explicit packages with the auto packages and all of their
1011 -- dependencies, and eliminating duplicates.
1013 o_file <- readIORef v_Output_file
1014 #if defined(mingw32_HOST_OS)
1015 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1017 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1020 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1021 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1023 lib_paths <- readIORef v_Library_paths
1024 let lib_path_opts = map ("-L"++) lib_paths
1026 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1028 #ifdef darwin_TARGET_OS
1029 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1030 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1032 framework_paths <- readIORef v_Framework_paths
1033 let framework_path_opts = map ("-F"++) framework_paths
1035 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1036 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1038 frameworks <- readIORef v_Cmdline_frameworks
1039 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1040 -- reverse because they're added in reverse order from the cmd line
1043 -- probably _stub.o files
1044 extra_ld_inputs <- readIORef v_Ld_inputs
1046 -- opts from -optl-<blah> (including -l<blah> options)
1047 extra_ld_opts <- getStaticOpts v_Opt_l
1049 let pstate = pkgState dflags
1050 rts_id | Just id <- rtsPackageId pstate = id
1051 | otherwise = panic "staticLink: rts package missing"
1052 base_id | Just id <- basePackageId pstate = id
1053 | otherwise = panic "staticLink: base package missing"
1054 rts_pkg = getPackageDetails pstate rts_id
1055 base_pkg = getPackageDetails pstate base_id
1057 ways <- readIORef v_Ways
1059 -- Here are some libs that need to be linked at the *end* of
1060 -- the command line, because they contain symbols that are referred to
1061 -- by the RTS. We can't therefore use the ordinary way opts for these.
1063 debug_opts | WayDebug `elem` ways = [
1064 #if defined(HAVE_LIBBFD)
1071 thread_opts | WayThreaded `elem` ways = [
1072 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1075 #if defined(osf3_TARGET_OS)
1081 let extra_os = if static || no_hs_main
1083 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1084 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1086 (md_c_flags, _) <- machdepCCOpts dflags
1087 SysTools.runLink dflags (
1088 [ SysTools.Option verb
1089 , SysTools.Option "-o"
1090 , SysTools.FileOption "" output_fn
1092 ++ map SysTools.Option (
1099 #ifdef darwin_TARGET_OS
1100 ++ framework_path_opts
1103 ++ pkg_lib_path_opts
1105 #ifdef darwin_TARGET_OS
1106 ++ pkg_framework_path_opts
1107 ++ pkg_framework_opts
1113 -- parallel only: move binary to another dir -- HWL
1114 ways_ <- readIORef v_Ways
1115 when (WayPar `elem` ways_)
1116 (do success <- runPhase_MoveBinary output_fn
1117 if success then return ()
1118 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1120 -----------------------------------------------------------------------------
1121 -- Making a DLL (only for Win32)
1123 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1124 doMkDLL dflags o_files dep_packages = do
1125 let verb = getVerbFlag dflags
1126 static <- readIORef v_Static
1127 no_hs_main <- readIORef v_NoHsMain
1129 o_file <- readIORef v_Output_file
1130 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1132 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1133 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1135 lib_paths <- readIORef v_Library_paths
1136 let lib_path_opts = map ("-L"++) lib_paths
1138 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1140 -- probably _stub.o files
1141 extra_ld_inputs <- readIORef v_Ld_inputs
1143 -- opts from -optdll-<blah>
1144 extra_ld_opts <- getStaticOpts v_Opt_dll
1146 let pstate = pkgState dflags
1147 rts_id | Just id <- rtsPackageId pstate = id
1148 | otherwise = panic "staticLink: rts package missing"
1149 base_id | Just id <- basePackageId pstate = id
1150 | otherwise = panic "staticLink: base package missing"
1151 rts_pkg = getPackageDetails pstate rts_id
1152 base_pkg = getPackageDetails pstate base_id
1154 let extra_os = if static || no_hs_main
1156 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1157 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1159 (md_c_flags, _) <- machdepCCOpts dflags
1160 SysTools.runMkDLL dflags
1161 ([ SysTools.Option verb
1162 , SysTools.Option "-o"
1163 , SysTools.FileOption "" output_fn
1165 ++ map SysTools.Option (
1169 ++ [ "--target=i386-mingw32" ]
1173 ++ pkg_lib_path_opts
1175 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1177 else [ "--export-all" ])
1180 -- -----------------------------------------------------------------------------
1183 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1184 doCpp dflags raw include_cc_opts input_fn output_fn = do
1185 let hscpp_opts = getOpts dflags opt_P
1187 cmdline_include_paths <- readIORef v_Include_paths
1189 pkg_include_dirs <- getPackageIncludePath dflags []
1190 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1191 (cmdline_include_paths ++ pkg_include_dirs)
1193 let verb = getVerbFlag dflags
1195 cc_opts <- if not include_cc_opts
1197 else do let optc = getOpts dflags opt_c
1198 (md_c_flags, _) <- machdepCCOpts dflags
1199 return (optc ++ md_c_flags)
1201 let cpp_prog args | raw = SysTools.runCpp dflags args
1202 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1205 [ "-D" ++ cTARGETOS ++ "_TARGET_OS=1",
1206 "-D" ++ cTARGETARCH ++ "_TARGET_ARCH=1" ]
1208 cpp_prog ([SysTools.Option verb]
1209 ++ map SysTools.Option include_paths
1210 ++ map SysTools.Option hsSourceCppOpts
1211 ++ map SysTools.Option hscpp_opts
1212 ++ map SysTools.Option cc_opts
1213 ++ map SysTools.Option target_defs
1214 ++ [ SysTools.Option "-x"
1215 , SysTools.Option "c"
1216 , SysTools.Option input_fn
1217 -- We hackily use Option instead of FileOption here, so that the file
1218 -- name is not back-slashed on Windows. cpp is capable of
1219 -- dealing with / in filenames, so it works fine. Furthermore
1220 -- if we put in backslashes, cpp outputs #line directives
1221 -- with *double* backslashes. And that in turn means that
1222 -- our error messages get double backslashes in them.
1223 -- In due course we should arrange that the lexer deals
1224 -- with these \\ escapes properly.
1225 , SysTools.Option "-o"
1226 , SysTools.FileOption "" output_fn
1229 -- -----------------------------------------------------------------------------
1232 hscNextPhase :: HscLang -> IO Phase
1233 hscNextPhase hsc_lang = do
1234 split <- readIORef v_Split_object_files
1235 return (case hsc_lang of
1237 HscAsm | split -> SplitMangle
1239 HscNothing -> HCc -- dummy (no output will be generated)
1240 HscInterpreted -> HCc -- "" ""
1241 _other -> HCc -- "" ""
1244 hscMaybeAdjustLang :: HscLang -> IO HscLang
1245 hscMaybeAdjustLang current_hsc_lang = do
1246 todo <- readIORef v_GhcMode
1247 keep_hc <- readIORef v_Keep_hc_files
1249 -- don't change the lang if we're interpreting
1250 | current_hsc_lang == HscInterpreted = current_hsc_lang
1251 -- force -fvia-C if we are being asked for a .hc file
1252 | todo == StopBefore HCc || keep_hc = HscC
1253 -- otherwise, stick to the plan
1254 | otherwise = current_hsc_lang