1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2002
7 -----------------------------------------------------------------------------
9 module DriverPipeline (
11 -- Interfaces for the batch-mode driver
12 compileFile, staticLink,
14 -- Interfaces for the compilation manager (interpreted/batch-mode)
16 compile, CompResult(..),
23 #include "HsVersions.h"
31 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
32 import qualified SysTools
41 import RdrName ( GlobalRdrEnv )
44 import StringBuffer ( hGetStringBuffer )
45 import BasicTypes ( SuccessFlag(..) )
46 import Maybes ( expectJust )
48 import ParserCoreUtils ( getCoreModuleName )
51 import DATA_IOREF ( readIORef, writeIORef )
60 -- ---------------------------------------------------------------------------
63 -- Just preprocess a file, put the result in a temp. file (used by the
64 -- compilation manager during the summary phase).
66 -- We return the augmented DynFlags, because they contain the result
67 -- of slurping in the OPTIONS pragmas
69 preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
70 preprocess dflags filename =
71 ASSERT2(isHaskellSrcFilename filename, text filename)
72 runPipeline anyHsc "preprocess" dflags
73 False{-temporary output file-}
74 Nothing{-no specific output file-}
76 Nothing{-no ModLocation-}
80 -- ---------------------------------------------------------------------------
82 -- This is used in batch mode
83 compileFile :: GhcMode -> DynFlags -> FilePath -> IO FilePath
84 compileFile mode dflags src = do
85 exists <- doesFileExist src
87 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
89 split <- readIORef v_Split_object_files
90 o_file <- readIORef v_Output_file
91 ghc_link <- readIORef v_GhcLink -- Set by -c or -no-link
92 -- When linking, the -o argument refers to the linker's output.
93 -- otherwise, we use it as the name for the pipeline's output.
95 | isLinkMode mode && not (isNoLink ghc_link) = Nothing
96 -- -o foo applies to linker
98 -- -o foo applies to the file we are compiling now
100 stop_phase = case mode of
101 StopBefore As | split -> SplitAs
102 StopBefore phase -> phase
105 mode_flag_string <- readIORef v_GhcModeFlag
106 (_, out_file) <- runPipeline stop_phase mode_flag_string dflags
107 True maybe_o_file src Nothing{-no ModLocation-}
111 -- ---------------------------------------------------------------------------
114 -- Compile a single module, under the control of the compilation manager.
116 -- This is the interface between the compilation manager and the
117 -- compiler proper (hsc), where we deal with tedious details like
118 -- reading the OPTIONS pragma from the source file, and passing the
119 -- output of hsc through the C compiler.
121 -- The driver sits between 'compile' and 'hscMain', translating calls
122 -- to the former into calls to the latter, and results from the latter
123 -- into results from the former. It does things like preprocessing
124 -- the .hs file if necessary, and compiling up the .stub_c files to
125 -- generate Linkables.
127 -- NB. No old interface can also mean that the source has changed.
131 -> Bool -- True <=> source unchanged
132 -> Bool -- True <=> have object
133 -> Maybe ModIface -- Old interface, if available
137 = CompOK ModDetails -- New details
138 ModIface -- New iface
139 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
140 -- (old code is still valid)
145 compile hsc_env mod_summary
146 source_unchanged have_object old_iface = do
148 let dyn_flags = hsc_dflags hsc_env
149 this_mod = ms_mod mod_summary
150 src_flavour = ms_hsc_src mod_summary
152 showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
154 let verb = verbosity dyn_flags
155 let location = ms_location mod_summary
156 let input_fn = expectJust "compile:hs" (ml_hs_file location)
157 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
159 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
161 -- Add in the OPTIONS from the source file
162 -- This is nasty: we've done this once already, in the compilation manager
163 -- It might be better to cache the flags in the ml_hspp_file field,say
164 opts <- getOptionsFromSource input_fnpp
165 (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
166 checkProcessArgsResult unhandled_flags input_fn
168 let (basename, _) = splitFilename input_fn
170 -- We add the directory in which the .hs files resides) to the import path.
171 -- This is needed when we try to compile the .hc file later, if it
172 -- imports a _stub.h file that we created here.
173 let current_dir = directoryOf basename
174 old_paths <- readIORef v_Include_paths
175 writeIORef v_Include_paths (current_dir : old_paths)
176 -- put back the old include paths afterward.
177 later (writeIORef v_Include_paths old_paths) $ do
179 -- Figure out what lang we're generating
180 hsc_lang <- hscMaybeAdjustTarget StopLn src_flavour (hscTarget dyn_flags)
181 -- ... and what the next phase should be
182 next_phase <- hscNextPhase src_flavour hsc_lang
183 -- ... and what file to generate the output into
184 get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
185 output_fn <- get_output_fn next_phase (Just location)
187 let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
188 hscOutName = output_fn,
189 hscStubCOutName = basename ++ "_stub.c",
190 hscStubHOutName = basename ++ "_stub.h",
191 extCoreName = basename ++ ".hcr" }
193 -- -no-recomp should also work with --make
194 let do_recomp = recompFlag dyn_flags
195 source_unchanged' = source_unchanged && do_recomp
196 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
199 hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
200 source_unchanged' have_object old_iface
203 HscFail -> return CompErrs
205 HscNoRecomp details iface -> return (CompOK details iface Nothing)
207 HscRecomp details iface
208 stub_h_exists stub_c_exists maybe_interpreted_code
210 | isHsBoot src_flavour -- No further compilation to do
211 -> return (CompOK details iface Nothing)
213 | otherwise -- Normal Haskell source files
216 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
217 let stub_unlinked = case maybe_stub_o of
219 Just stub_o -> [ DotO stub_o ]
221 (hs_unlinked, unlinked_time) <-
224 -- in interpreted mode, just return the compiled code
225 -- as our "unlinked" object.
227 case maybe_interpreted_code of
229 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
230 -- Why do we use the timestamp of the source file here,
231 -- rather than the current time? This works better in
232 -- the case where the local clock is out of sync
233 -- with the filesystem's clock. It's just as accurate:
234 -- if the source is modified, then the linkable will
237 Nothing -> panic "compile: no interpreted code"
239 -- we're in batch mode: finish the compilation pipeline.
241 let object_filename = ml_obj_file location
243 runPipeline StopLn "" dyn_flags
244 True Nothing output_fn (Just location)
245 -- the object filename comes from the ModLocation
247 o_time <- getModificationTime object_filename
248 return ([DotO object_filename], o_time)
250 let linkable = LM unlinked_time this_mod
251 (hs_unlinked ++ stub_unlinked)
253 return (CompOK details iface (Just linkable))
255 -----------------------------------------------------------------------------
256 -- stub .h and .c files (for foreign export support)
258 compileStub dflags stub_c_exists
259 | not stub_c_exists = return Nothing
261 -- compile the _stub.c file w/ gcc
262 let stub_c = hscStubCOutName dflags
263 (_, stub_o) <- runPipeline StopLn "stub-compile" dflags
264 True{-persistent output-}
265 Nothing{-no specific output file-}
267 Nothing{-no ModLocation-}
271 -- ---------------------------------------------------------------------------
274 link :: GhciMode -- interactive or batch
275 -> DynFlags -- dynamic flags
276 -> Bool -- attempt linking in batch mode?
277 -> HomePackageTable -- what to link
280 -- For the moment, in the batch linker, we don't bother to tell doLink
281 -- which packages to link -- it just tries all that are available.
282 -- batch_attempt_linking should only be *looked at* in batch mode. It
283 -- should only be True if the upsweep was successful and someone
284 -- exports main, i.e., we have good reason to believe that linking
288 link Interactive dflags batch_attempt_linking hpt
289 = do -- Not Linking...(demand linker will do the job)
293 link Batch dflags batch_attempt_linking hpt
294 | batch_attempt_linking
297 home_mod_infos = moduleEnvElts hpt
299 -- the packages we depend on
300 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
302 -- the linkables to link
303 linkables = map hm_linkable home_mod_infos
305 when (verb >= 3) $ do
306 hPutStrLn stderr "link: linkables are ..."
307 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
309 -- check for the -no-link flag
310 ghc_link <- readIORef v_GhcLink
312 then do when (verb >= 3) $
313 hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
318 hPutStrLn stderr "Linking ..."
320 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
321 obj_files = concatMap getOfiles linkables
323 -- Don't showPass in Batch mode; doLink will do that for us.
324 staticLink dflags obj_files pkg_deps
326 when (verb >= 3) (hPutStrLn stderr "link: done")
328 -- staticLink only returns if it succeeds
332 = do when (verb >= 3) $ do
333 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
334 hPutStrLn stderr " Main.main not exported; not linking."
337 verb = verbosity dflags
339 -- ---------------------------------------------------------------------------
340 -- Run a compilation pipeline, consisting of multiple phases.
342 -- The DynFlags can be modified by phases in the pipeline (eg. by
343 -- OPTIONS pragmas), and the changes affect later phases in the
344 -- pipeline, but we throw away the resulting DynFlags at the end.
347 :: Phase -- When to stop
348 -> String -- "GhcMode" flag as a string
349 -> DynFlags -- Dynamic flags
350 -> Bool -- Final output is persistent?
351 -> Maybe FilePath -- Where to put the output, optionally
352 -> FilePath -- Input filename
353 -> Maybe ModLocation -- A ModLocation for this module, if we have one
354 -> IO (DynFlags, FilePath) -- (final flags, output filename)
356 runPipeline stop_phase mode_flag_string dflags keep_output
357 maybe_output_filename input_fn maybe_loc
359 let (basename, suffix) = splitFilename input_fn
360 start_phase = startPhase suffix
362 -- We want to catch cases of "you can't get there from here" before
363 -- we start the pipeline, because otherwise it will just run off the
366 -- There is a partial ordering on phases, where A < B iff A occurs
367 -- before B in a normal compilation pipeline.
369 when (not (start_phase `happensBefore` stop_phase)) $
371 ("flag `" ++ mode_flag_string
372 ++ "' is incompatible with source file `"
375 -- generate a function which will be used to calculate output file names
377 get_output_fn <- genOutputFilenameFunc stop_phase keep_output
378 maybe_output_filename basename
380 -- Execute the pipeline...
381 (dflags', output_fn, maybe_loc) <- pipeLoop dflags start_phase stop_phase input_fn
382 basename suffix get_output_fn maybe_loc
384 -- Sometimes, a compilation phase doesn't actually generate any output
385 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
386 -- stage, but we wanted to keep the output, then we have to explicitly
389 then do final_fn <- get_output_fn stop_phase maybe_loc
390 when (final_fn /= output_fn) $
391 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
392 ++ "'") output_fn final_fn
393 return (dflags', final_fn)
395 return (dflags', output_fn)
398 pipeLoop :: DynFlags -> Phase -> Phase
399 -> FilePath -> String -> Suffix
400 -> (Phase -> Maybe ModLocation -> IO FilePath)
402 -> IO (DynFlags, FilePath, Maybe ModLocation)
404 pipeLoop dflags phase stop_phase
405 input_fn orig_basename orig_suff
406 orig_get_output_fn maybe_loc
408 | phase `eqPhase` stop_phase -- All done
409 = return (dflags, input_fn, maybe_loc)
411 | not (phase `happensBefore` stop_phase)
412 -- Something has gone wrong. We'll try to cover all the cases when
413 -- this could happen, so if we reach here it is a panic.
414 -- eg. it might happen if the -C flag is used on a source file that
415 -- has {-# OPTIONS -fasm #-}.
416 = panic ("pipeLoop: at phase " ++ show phase ++
417 " but I wanted to stop at phase " ++ show stop_phase)
420 = do { (next_phase, dflags', maybe_loc, output_fn)
421 <- runPhase phase stop_phase dflags orig_basename
422 orig_suff input_fn orig_get_output_fn maybe_loc
423 ; pipeLoop dflags' next_phase stop_phase output_fn
424 orig_basename orig_suff orig_get_output_fn maybe_loc }
426 genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
427 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
428 genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
430 hcsuf <- readIORef v_HC_suf
431 odir <- readIORef v_Output_dir
432 osuf <- readIORef v_Object_suf
433 keep_hc <- readIORef v_Keep_hc_files
435 keep_il <- readIORef v_Keep_il_files
436 keep_ilx <- readIORef v_Keep_ilx_files
438 keep_raw_s <- readIORef v_Keep_raw_s_files
439 keep_s <- readIORef v_Keep_s_files
441 myPhaseInputExt HCc = hcsuf
442 myPhaseInputExt StopLn = osuf
443 myPhaseInputExt other = phaseInputExt other
445 func next_phase maybe_location
446 | is_last_phase, Just f <- maybe_output_filename = return f
447 | is_last_phase && keep_final_output = persistent_fn
448 | keep_this_output = persistent_fn
449 | otherwise = newTempName suffix
452 is_last_phase = next_phase `eqPhase` stop_phase
454 -- sometimes, we keep output from intermediate stages
458 Mangle | keep_raw_s -> True
460 HCc | keep_hc -> True
463 suffix = myPhaseInputExt next_phase
465 -- persistent object files get put in odir
467 | StopLn <- next_phase = return odir_persistent
468 | otherwise = return persistent
470 persistent = basename ++ '.':suffix
473 | Just loc <- maybe_location = ml_obj_file loc
474 | Just d <- odir = replaceFilenameDirectory persistent d
475 | otherwise = persistent
480 -- -----------------------------------------------------------------------------
481 -- Each phase in the pipeline returns the next phase to execute, and the
482 -- name of the file in which the output was placed.
484 -- We must do things dynamically this way, because we often don't know
485 -- what the rest of the phases will be until part-way through the
486 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
487 -- of a source file can change the latter stages of the pipeline from
488 -- taking the via-C route to using the native code generator.
490 runPhase :: Phase -- Do this phase first
491 -> Phase -- Stop just before this phase
493 -> String -- basename of original input source
494 -> String -- its extension
495 -> FilePath -- name of file which contains the input to this phase.
496 -> (Phase -> Maybe ModLocation -> IO FilePath)
497 -- how to calculate the output filename
498 -> Maybe ModLocation -- the ModLocation, if we have one
499 -> IO (Phase, -- next phase
500 DynFlags, -- new dynamic flags
501 Maybe ModLocation, -- the ModLocation, if we have one
502 FilePath) -- output filename
504 -- Invariant: the output filename always contains the output
505 -- Interesting case: Hsc when there is no recompilation to do
506 -- Then the output filename is still a .o file
508 -------------------------------------------------------------------------------
511 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
512 = do let unlit_flags = getOpts dflags opt_L
513 -- The -h option passes the file name for unlit to put in a #line directive
514 output_fn <- get_output_fn (Cpp sf) maybe_loc
516 SysTools.runUnlit dflags
517 (map SysTools.Option unlit_flags ++
518 [ SysTools.Option "-h"
519 , SysTools.Option input_fn
520 , SysTools.FileOption "" input_fn
521 , SysTools.FileOption "" output_fn
524 return (Cpp sf, dflags, maybe_loc, output_fn)
526 -------------------------------------------------------------------------------
527 -- Cpp phase : (a) gets OPTIONS out of file
528 -- (b) runs cpp if necessary
530 runPhase (Cpp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
531 = do src_opts <- getOptionsFromSource input_fn
532 (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
533 checkProcessArgsResult unhandled_flags (basename++'.':suff)
535 if not (cppFlag dflags) then
536 -- no need to preprocess CPP, just pass input file along
537 -- to the next phase of the pipeline.
538 return (HsPp sf, dflags, maybe_loc, input_fn)
540 output_fn <- get_output_fn (HsPp sf) maybe_loc
541 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
542 return (HsPp sf, dflags, maybe_loc, output_fn)
544 -------------------------------------------------------------------------------
547 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
548 = do if not (ppFlag dflags) then
549 -- no need to preprocess, just pass input file along
550 -- to the next phase of the pipeline.
551 return (Hsc sf, dflags, maybe_loc, input_fn)
553 let hspp_opts = getOpts dflags opt_F
554 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
555 let orig_fn = basename ++ '.':suff
556 output_fn <- get_output_fn (Hsc sf) maybe_loc
557 SysTools.runPp dflags
558 ( [ SysTools.Option orig_fn
559 , SysTools.Option input_fn
560 , SysTools.FileOption "" output_fn
562 map SysTools.Option hs_src_pp_opts ++
563 map SysTools.Option hspp_opts
565 return (Hsc sf, dflags, maybe_loc, output_fn)
567 -----------------------------------------------------------------------------
570 -- Compilation of a single module, in "legacy" mode (_not_ under
571 -- the direction of the compilation manager).
572 runPhase (Hsc src_flavour) stop dflags basename suff input_fn get_output_fn _maybe_loc
573 = do -- normal Hsc mode, not mkdependHS
575 -- we add the current directory (i.e. the directory in which
576 -- the .hs files resides) to the import path, since this is
577 -- what gcc does, and it's probably what you want.
578 let current_dir = directoryOf basename
580 paths <- readIORef v_Include_paths
581 writeIORef v_Include_paths (current_dir : paths)
583 -- gather the imports and module name
584 (hspp_buf,mod_name) <-
586 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
587 ; m <- getCoreModuleName input_fn
588 ; return (Nothing, mkModule m) }
590 other -> do { buf <- hGetStringBuffer input_fn
591 ; (_,_,mod_name) <- getImports dflags buf input_fn
592 ; return (Just buf, mod_name) }
594 -- Build a ModLocation to pass to hscMain.
595 -- The source filename is rather irrelevant by now, but it's used
596 -- by hscMain for messages. hscMain also needs
597 -- the .hi and .o filenames, and this is as good a way
598 -- as any to generate them, and better than most. (e.g. takes
599 -- into accout the -osuf flags)
600 location1 <- mkHomeModLocation2 mod_name basename suff
602 -- Boot-ify it if necessary
603 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
604 | otherwise = location1
607 -- Take -ohi into account if present
608 -- This can't be done in mkHomeModuleLocation because
609 -- it only applies to the module being compiles
610 ohi <- readIORef v_Output_hi
611 let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
612 | otherwise = location2
614 -- Take -o into account if present
615 -- Very like -ohi, but we must *only* do this if we aren't linking
616 -- (If we're linking then the -o applies to the linked thing, not to
617 -- the object file for one module.)
618 -- Note the nasty duplication with the same computation in compileFile above
619 expl_o_file <- readIORef v_Output_file
620 ghc_link <- readIORef v_GhcLink
621 let location4 | Just ofile <- expl_o_file
623 = location3 { ml_obj_file = ofile }
624 | otherwise = location3
626 -- Tell the finder cache about this module
627 addHomeModuleToFinder mod_name location4
629 -- Make the ModSummary to hand to hscMain
630 src_timestamp <- getModificationTime (basename ++ '.':suff)
632 unused_field = panic "runPhase:ModSummary field"
633 -- Some fields are not looked at by hscMain
634 mod_summary = ModSummary { ms_mod = mod_name,
635 ms_hsc_src = src_flavour,
636 ms_hspp_file = Just input_fn,
637 ms_hspp_buf = hspp_buf,
638 ms_location = location4,
639 ms_hs_date = src_timestamp,
640 ms_imps = unused_field,
641 ms_srcimps = unused_field }
643 o_file = ml_obj_file location4 -- The real object file
646 -- Figure out if the source has changed, for recompilation avoidance.
648 -- Setting source_unchanged to True means that M.o seems
649 -- to be up to date wrt M.hs; so no need to recompile unless imports have
650 -- changed (which the compiler itself figures out).
651 -- Setting source_unchanged to False tells the compiler that M.o is out of
652 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
653 let do_recomp = recompFlag dflags
655 if not do_recomp || not (isStopLn stop)
656 -- Set source_unchanged to False unconditionally if
657 -- (a) recompilation checker is off, or
658 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
660 -- Otherwise look at file modification dates
661 else do o_file_exists <- doesFileExist o_file
663 then return False -- Need to recompile
664 else do t2 <- getModificationTime o_file
665 if t2 > src_timestamp
670 hsc_lang <- hscMaybeAdjustTarget stop src_flavour (hscTarget dflags)
671 next_phase <- hscNextPhase src_flavour hsc_lang
672 output_fn <- get_output_fn next_phase (Just location4)
674 let dflags' = dflags { hscTarget = hsc_lang,
675 hscOutName = output_fn,
676 hscStubCOutName = basename ++ "_stub.c",
677 hscStubHOutName = basename ++ "_stub.h",
678 extCoreName = basename ++ ".hcr" }
680 hsc_env <- newHscEnv OneShot dflags'
683 result <- hscMain hsc_env printErrorsAndWarnings
684 mod_summary source_unchanged
685 False -- No object file
690 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
692 HscNoRecomp details iface -> do
693 SysTools.touch dflags' "Touching object file" o_file
694 return (StopLn, dflags', Just location4, o_file)
696 HscRecomp _details _iface
697 stub_h_exists stub_c_exists
698 _maybe_interpreted_code -> do
701 maybe_stub_o <- compileStub dflags' stub_c_exists
704 Just stub_o -> add v_Ld_inputs stub_o
706 -- In the case of hs-boot files, generate a dummy .o-boot
707 -- stamp file for the benefit of Make
709 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
712 return (next_phase, dflags', Just location4, output_fn)
714 -----------------------------------------------------------------------------
717 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
719 output_fn <- get_output_fn Cmm maybe_loc
720 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
721 return (Cmm, dflags, maybe_loc, output_fn)
723 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
725 hsc_lang <- hscMaybeAdjustTarget stop HsSrcFile (hscTarget dflags)
726 next_phase <- hscNextPhase HsSrcFile hsc_lang
727 output_fn <- get_output_fn next_phase maybe_loc
729 let dflags' = dflags { hscTarget = hsc_lang,
730 hscOutName = output_fn,
731 hscStubCOutName = basename ++ "_stub.c",
732 hscStubHOutName = basename ++ "_stub.h",
733 extCoreName = basename ++ ".hcr" }
735 ok <- hscCmmFile dflags' input_fn
737 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
739 return (next_phase, dflags, maybe_loc, output_fn)
741 -----------------------------------------------------------------------------
744 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
745 -- way too many hacks, and I can't say I've ever used it anyway.
747 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
748 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
749 = do let cc_opts = getOpts dflags opt_c
750 hcc = cc_phase `eqPhase` HCc
752 cmdline_include_paths <- readIORef v_Include_paths
754 -- HC files have the dependent packages stamped into them
755 pkgs <- if hcc then getHCFilePackages input_fn else return []
757 -- add package include paths even if we're just compiling .c
758 -- files; this is the Value Add(TM) that using ghc instead of
760 pkg_include_dirs <- getPackageIncludePath dflags pkgs
761 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
762 (cmdline_include_paths ++ pkg_include_dirs)
764 (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
765 pic_c_flags <- picCCOpts dflags
767 let verb = getVerbFlag dflags
769 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
771 split_objs <- readIORef v_Split_object_files
772 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
775 excessPrecision <- readIORef v_Excess_precision
778 mangle <- readIORef v_Do_asm_mangling
780 | hcc && mangle = Mangle
782 output_fn <- get_output_fn next_phase maybe_loc
784 -- force the C compiler to interpret this file as C when
785 -- compiling .hc files, by adding the -x c option.
786 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
789 SysTools.runCc dflags (langopt ++
790 [ SysTools.FileOption "" input_fn
791 , SysTools.Option "-o"
792 , SysTools.FileOption "" output_fn
794 ++ map SysTools.Option (
800 ++ [ verb, "-S", "-Wimplicit", "-O" ]
801 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
804 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
809 return (next_phase, dflags, maybe_loc, output_fn)
811 -- ToDo: postprocess the output from gcc
813 -----------------------------------------------------------------------------
816 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
817 = do let mangler_opts = getOpts dflags opt_m
820 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
822 machdep_opts <- return []
825 split <- readIORef v_Split_object_files
827 | split = SplitMangle
829 output_fn <- get_output_fn next_phase maybe_loc
831 SysTools.runMangle dflags (map SysTools.Option mangler_opts
832 ++ [ SysTools.FileOption "" input_fn
833 , SysTools.FileOption "" output_fn
835 ++ map SysTools.Option machdep_opts)
837 return (next_phase, dflags, maybe_loc, output_fn)
839 -----------------------------------------------------------------------------
842 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
843 = do -- tmp_pfx is the prefix used for the split .s files
844 -- We also use it as the file to contain the no. of split .s files (sigh)
845 split_s_prefix <- SysTools.newTempName "split"
846 let n_files_fn = split_s_prefix
848 SysTools.runSplit dflags
849 [ SysTools.FileOption "" input_fn
850 , SysTools.FileOption "" split_s_prefix
851 , SysTools.FileOption "" n_files_fn
854 -- Save the number of split files for future references
855 s <- readFile n_files_fn
856 let n_files = read s :: Int
857 writeIORef v_Split_info (split_s_prefix, n_files)
859 -- Remember to delete all these files
860 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
863 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
864 -- we don't use the filename
866 -----------------------------------------------------------------------------
869 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
870 = do let as_opts = getOpts dflags opt_a
871 cmdline_include_paths <- readIORef v_Include_paths
873 output_fn <- get_output_fn StopLn maybe_loc
875 -- we create directories for the object file, because it
876 -- might be a hierarchical module.
877 createDirectoryHierarchy (directoryOf output_fn)
879 SysTools.runAs dflags
880 (map SysTools.Option as_opts
881 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
882 ++ [ SysTools.Option "-c"
883 , SysTools.FileOption "" input_fn
884 , SysTools.Option "-o"
885 , SysTools.FileOption "" output_fn
888 return (StopLn, dflags, maybe_loc, output_fn)
891 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
892 = do let as_opts = getOpts dflags opt_a
894 (split_s_prefix, n) <- readIORef v_Split_info
896 odir <- readIORef v_Output_dir
897 let real_odir = case odir of
898 Nothing -> basename ++ "_split"
902 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
903 let output_o = replaceFilenameDirectory
904 (basename ++ "__" ++ show n ++ ".o")
906 real_o <- osuf_ify output_o
907 SysTools.runAs dflags
908 (map SysTools.Option as_opts ++
909 [ SysTools.Option "-c"
910 , SysTools.Option "-o"
911 , SysTools.FileOption "" real_o
912 , SysTools.FileOption "" input_s
915 mapM_ assemble_file [1..n]
917 output_fn <- get_output_fn StopLn maybe_loc
918 return (StopLn, dflags, maybe_loc, output_fn)
921 -----------------------------------------------------------------------------
923 -- Run ilx2il over the ILX output, getting an IL file
925 runPhase Ilx2Il stop dflags _basename _suff input_fn get_output_fn maybe_loc
926 = do let ilx2il_opts = getOpts dflags opt_I
927 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
928 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
929 SysTools.Option "mscorlib",
930 SysTools.Option "-o",
931 SysTools.FileOption "" output_fn,
932 SysTools.FileOption "" input_fn ])
935 -----------------------------------------------------------------------------
937 -- Run ilasm over the IL, getting a DLL
939 runPhase Ilasm stop dflags _basename _suff input_fn get_output_fn maybe_loc
940 = do let ilasm_opts = getOpts dflags opt_i
941 SysTools.runIlasm (map SysTools.Option ilasm_opts
942 ++ [ SysTools.Option "/QUIET",
943 SysTools.Option "/DLL",
944 SysTools.FileOption "/OUT=" output_fn,
945 SysTools.FileOption "" input_fn ])
950 -----------------------------------------------------------------------------
951 -- MoveBinary sort-of-phase
952 -- After having produced a binary, move it somewhere else and generate a
953 -- wrapper script calling the binary. Currently, we need this only in
954 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
955 -- central directory.
956 -- This is called from staticLink below, after linking. I haven't made it
957 -- a separate phase to minimise interfering with other modules, and
958 -- we don't need the generality of a phase (MoveBinary is always
959 -- done after linking and makes only sense in a parallel setup) -- HWL
961 runPhase_MoveBinary input_fn
964 pvm_root <- getEnv "PVM_ROOT"
965 pvm_arch <- getEnv "PVM_ARCH"
967 pvm_executable_base = "=" ++ input_fn
968 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
969 -- nuke old binary; maybe use configur'ed names for cp and rm?
970 system ("rm -f " ++ pvm_executable)
971 -- move the newly created binary into PVM land
972 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
973 -- generate a wrapper script for running a parallel prg under PVM
974 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
977 -- generates a Perl skript starting a parallel prg under PVM
978 mk_pvm_wrapper_script :: String -> String -> String -> String
979 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
981 "eval 'exec perl -S $0 ${1+\"$@\"}'",
982 " if $running_under_some_shell;",
983 "# =!=!=!=!=!=!=!=!=!=!=!",
984 "# This script is automatically generated: DO NOT EDIT!!!",
985 "# Generated by Glasgow Haskell Compiler",
986 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
988 "$pvm_executable = '" ++ pvm_executable ++ "';",
989 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
990 "$SysMan = '" ++ sysMan ++ "';",
992 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
993 "# first, some magical shortcuts to run "commands" on the binary",
994 "# (which is hidden)",
995 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
996 " local($cmd) = $1;",
997 " system("$cmd $pvm_executable");",
998 " exit(0); # all done",
1001 "# Now, run the real binary; process the args first",
1002 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1004 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1005 "@nonPVM_args = ();",
1006 "$in_RTS_args = 0;",
1008 "args: while ($a = shift(@ARGV)) {",
1009 " if ( $a eq '+RTS' ) {",
1010 " $in_RTS_args = 1;",
1011 " } elsif ( $a eq '-RTS' ) {",
1012 " $in_RTS_args = 0;",
1014 " if ( $a eq '-d' && $in_RTS_args ) {",
1016 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1017 " $nprocessors = $1;",
1018 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1019 " $nprocessors = $1;",
1021 " push(@nonPVM_args, $a);",
1025 "local($return_val) = 0;",
1026 "# Start the parallel execution by calling SysMan",
1027 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1028 "$return_val = $?;",
1029 "# ToDo: fix race condition moving files and flushing them!!",
1030 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1031 "exit($return_val);"
1034 -----------------------------------------------------------------------------
1035 -- Complain about non-dynamic flags in OPTIONS pragmas
1037 checkProcessArgsResult flags filename
1038 = do when (notNull flags) (throwDyn (ProgramError (
1039 showSDoc (hang (text filename <> char ':')
1040 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1041 hsep (map text flags)))
1044 -----------------------------------------------------------------------------
1045 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1047 getHCFilePackages :: FilePath -> IO [PackageId]
1048 getHCFilePackages filename =
1049 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1052 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1053 return (map stringToPackageId (words rest))
1057 -----------------------------------------------------------------------------
1058 -- Static linking, of .o files
1060 -- The list of packages passed to link is the list of packages on
1061 -- which this program depends, as discovered by the compilation
1062 -- manager. It is combined with the list of packages that the user
1063 -- specifies on the command line with -package flags.
1065 -- In one-shot linking mode, we can't discover the package
1066 -- dependencies (because we haven't actually done any compilation or
1067 -- read any interface files), so the user must explicitly specify all
1070 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1071 staticLink dflags o_files dep_packages = do
1072 let verb = getVerbFlag dflags
1073 static <- readIORef v_Static
1074 no_hs_main <- readIORef v_NoHsMain
1076 -- get the full list of packages to link with, by combining the
1077 -- explicit packages with the auto packages and all of their
1078 -- dependencies, and eliminating duplicates.
1080 o_file <- readIORef v_Output_file
1081 #if defined(mingw32_HOST_OS)
1082 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1084 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1087 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1088 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1090 lib_paths <- readIORef v_Library_paths
1091 let lib_path_opts = map ("-L"++) lib_paths
1093 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1095 #ifdef darwin_TARGET_OS
1096 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1097 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1099 framework_paths <- readIORef v_Framework_paths
1100 let framework_path_opts = map ("-F"++) framework_paths
1102 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1103 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1104 frameworks <- readIORef v_Cmdline_frameworks
1105 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1106 -- reverse because they're added in reverse order from the cmd line
1109 -- probably _stub.o files
1110 extra_ld_inputs <- readIORef v_Ld_inputs
1112 -- opts from -optl-<blah> (including -l<blah> options)
1113 extra_ld_opts <- getStaticOpts v_Opt_l
1115 ways <- readIORef v_Ways
1117 -- Here are some libs that need to be linked at the *end* of
1118 -- the command line, because they contain symbols that are referred to
1119 -- by the RTS. We can't therefore use the ordinary way opts for these.
1121 debug_opts | WayDebug `elem` ways = [
1122 #if defined(HAVE_LIBBFD)
1129 thread_opts | WayThreaded `elem` ways = [
1130 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1133 #if defined(osf3_TARGET_OS)
1139 (md_c_flags, _) <- machdepCCOpts dflags
1140 SysTools.runLink dflags (
1141 [ SysTools.Option verb
1142 , SysTools.Option "-o"
1143 , SysTools.FileOption "" output_fn
1145 ++ map SysTools.Option (
1151 #ifdef darwin_TARGET_OS
1152 ++ framework_path_opts
1155 ++ pkg_lib_path_opts
1157 #ifdef darwin_TARGET_OS
1158 ++ pkg_framework_path_opts
1159 ++ pkg_framework_opts
1165 -- parallel only: move binary to another dir -- HWL
1166 ways_ <- readIORef v_Ways
1167 when (WayPar `elem` ways_)
1168 (do success <- runPhase_MoveBinary output_fn
1169 if success then return ()
1170 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1172 -----------------------------------------------------------------------------
1173 -- Making a DLL (only for Win32)
1175 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1176 doMkDLL dflags o_files dep_packages = do
1177 let verb = getVerbFlag dflags
1178 static <- readIORef v_Static
1179 no_hs_main <- readIORef v_NoHsMain
1181 o_file <- readIORef v_Output_file
1182 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1184 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1185 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1187 lib_paths <- readIORef v_Library_paths
1188 let lib_path_opts = map ("-L"++) lib_paths
1190 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1192 -- probably _stub.o files
1193 extra_ld_inputs <- readIORef v_Ld_inputs
1195 -- opts from -optdll-<blah>
1196 extra_ld_opts <- getStaticOpts v_Opt_dll
1198 let pstate = pkgState dflags
1199 rts_id | ExtPackage id <- rtsPackageId pstate = id
1200 | otherwise = panic "staticLink: rts package missing"
1201 base_id | ExtPackage id <- basePackageId pstate = id
1202 | otherwise = panic "staticLink: base package missing"
1203 rts_pkg = getPackageDetails pstate rts_id
1204 base_pkg = getPackageDetails pstate base_id
1206 let extra_os = if static || no_hs_main
1208 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1209 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1211 (md_c_flags, _) <- machdepCCOpts dflags
1212 SysTools.runMkDLL dflags
1213 ([ SysTools.Option verb
1214 , SysTools.Option "-o"
1215 , SysTools.FileOption "" output_fn
1217 ++ map SysTools.Option (
1221 ++ [ "--target=i386-mingw32" ]
1225 ++ pkg_lib_path_opts
1227 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1229 else [ "--export-all" ])
1232 -- -----------------------------------------------------------------------------
1235 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1236 doCpp dflags raw include_cc_opts input_fn output_fn = do
1237 let hscpp_opts = getOpts dflags opt_P
1239 cmdline_include_paths <- readIORef v_Include_paths
1241 pkg_include_dirs <- getPackageIncludePath dflags []
1242 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1243 (cmdline_include_paths ++ pkg_include_dirs)
1245 let verb = getVerbFlag dflags
1247 cc_opts <- if not include_cc_opts
1249 else do let optc = getOpts dflags opt_c
1250 (md_c_flags, _) <- machdepCCOpts dflags
1251 return (optc ++ md_c_flags)
1253 let cpp_prog args | raw = SysTools.runCpp dflags args
1254 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1257 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1258 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1259 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1260 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1261 -- remember, in code we *compile*, the HOST is the same our TARGET,
1262 -- and BUILD is the same as our HOST.
1264 cpp_prog ([SysTools.Option verb]
1265 ++ map SysTools.Option include_paths
1266 ++ map SysTools.Option hsSourceCppOpts
1267 ++ map SysTools.Option hscpp_opts
1268 ++ map SysTools.Option cc_opts
1269 ++ map SysTools.Option target_defs
1270 ++ [ SysTools.Option "-x"
1271 , SysTools.Option "c"
1272 , SysTools.Option input_fn
1273 -- We hackily use Option instead of FileOption here, so that the file
1274 -- name is not back-slashed on Windows. cpp is capable of
1275 -- dealing with / in filenames, so it works fine. Furthermore
1276 -- if we put in backslashes, cpp outputs #line directives
1277 -- with *double* backslashes. And that in turn means that
1278 -- our error messages get double backslashes in them.
1279 -- In due course we should arrange that the lexer deals
1280 -- with these \\ escapes properly.
1281 , SysTools.Option "-o"
1282 , SysTools.FileOption "" output_fn
1285 -- -----------------------------------------------------------------------------
1288 hscNextPhase :: HscSource -> HscTarget -> IO Phase
1289 hscNextPhase HsBootFile hsc_lang
1292 hscNextPhase other hsc_lang = do
1293 split <- readIORef v_Split_object_files
1294 return (case hsc_lang of
1296 HscAsm | split -> SplitMangle
1298 HscNothing -> StopLn
1299 HscInterpreted -> StopLn
1303 hscMaybeAdjustTarget :: Phase -> HscSource -> HscTarget -> IO HscTarget
1304 hscMaybeAdjustTarget stop HsBootFile current_hsc_lang
1305 = return HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1306 hscMaybeAdjustTarget stop other current_hsc_lang
1307 = do { keep_hc <- readIORef v_Keep_hc_files
1309 -- don't change the lang if we're interpreting
1310 | current_hsc_lang == HscInterpreted = current_hsc_lang
1312 -- force -fvia-C if we are being asked for a .hc file
1313 | HCc <- stop = HscC
1315 -- otherwise, stick to the plan
1316 | otherwise = current_hsc_lang