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 :: FilePath -> IO FilePath
71 ASSERT(isHaskellSrcFilename filename)
72 do restoreDynFlags -- Restore to state of last save
73 runPipeline (StopBefore Hsc) ("preprocess")
74 False{-temporary output file-}
75 Nothing{-no specific output file-}
77 Nothing{-no ModLocation-}
79 -- ---------------------------------------------------------------------------
82 -- Compile a single module, under the control of the compilation manager.
84 -- This is the interface between the compilation manager and the
85 -- compiler proper (hsc), where we deal with tedious details like
86 -- reading the OPTIONS pragma from the source file, and passing the
87 -- output of hsc through the C compiler.
89 -- The driver sits between 'compile' and 'hscMain', translating calls
90 -- to the former into calls to the latter, and results from the latter
91 -- into results from the former. It does things like preprocessing
92 -- the .hs file if necessary, and compiling up the .stub_c files to
93 -- generate Linkables.
95 -- NB. No old interface can also mean that the source has changed.
100 -> ClockTime -- timestamp of original source file
101 -> Bool -- True <=> source unchanged
102 -> Bool -- True <=> have object
103 -> Maybe ModIface -- old interface, if available
107 = CompOK ModDetails -- New details
108 (Maybe GlobalRdrEnv) -- Lexical environment for the module
109 -- (Maybe because we may have loaded it from
110 -- its precompiled interface)
111 ModIface -- New iface
112 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
113 -- (old code is still valid)
118 compile hsc_env this_mod location src_timestamp
119 source_unchanged have_object
122 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
125 (showSDoc (text "Compiling" <+> ppr this_mod))
127 let verb = verbosity dyn_flags
128 let input_fn = expectJust "compile:hs" (ml_hs_file location)
129 let input_fnpp = expectJust "compile:hspp" (ml_hspp_file location)
130 let mod_name = moduleName this_mod
132 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
134 opts <- getOptionsFromSource input_fnpp
135 processArgs dynamic_flags opts []
136 dyn_flags <- getDynFlags
138 let (basename, _) = splitFilename input_fn
140 -- We add the directory in which the .hs files resides) to the import path.
141 -- This is needed when we try to compile the .hc file later, if it
142 -- imports a _stub.h file that we created here.
143 let current_dir = directoryOf basename
144 old_paths <- readIORef v_Include_paths
145 writeIORef v_Include_paths (current_dir : old_paths)
146 -- put back the old include paths afterward.
147 later (writeIORef v_Include_paths old_paths) $ do
149 -- figure out what lang we're generating
150 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
151 -- figure out what the next phase should be
152 next_phase <- hscNextPhase hsc_lang
153 -- figure out what file to generate the output into
154 get_output_fn <- genOutputFilenameFunc False Nothing next_phase basename
155 output_fn <- get_output_fn next_phase (Just location)
157 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
158 hscOutName = output_fn,
159 hscStubCOutName = basename ++ "_stub.c",
160 hscStubHOutName = basename ++ "_stub.h",
161 extCoreName = basename ++ ".hcr" }
163 -- -no-recomp should also work with --make
164 do_recomp <- readIORef v_Recomp
165 let source_unchanged' = source_unchanged && do_recomp
166 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
169 hsc_result <- hscMain hsc_env' printErrorsAndWarnings this_mod location
170 source_unchanged' have_object old_iface
173 HscFail -> return CompErrs
175 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
177 HscRecomp details rdr_env iface
178 stub_h_exists stub_c_exists maybe_interpreted_code -> do
180 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
181 let stub_unlinked = case maybe_stub_o of
183 Just stub_o -> [ DotO stub_o ]
185 (hs_unlinked, unlinked_time) <-
188 -- in interpreted mode, just return the compiled code
189 -- as our "unlinked" object.
191 case maybe_interpreted_code of
193 Just comp_bc -> return ([BCOs comp_bc], src_timestamp)
194 -- Why do we use the timestamp of the source file here,
195 -- rather than the current time? This works better in
196 -- the case where the local clock is out of sync
197 -- with the filesystem's clock. It's just as accurate:
198 -- if the source is modified, then the linkable will
201 Nothing -> panic "compile: no interpreted code"
203 -- we're in batch mode: finish the compilation pipeline.
205 let object_filename = ml_obj_file location
207 runPipeline (StopBefore Ln) ""
208 True Nothing output_fn (Just location)
209 -- the object filename comes from the ModLocation
211 o_time <- getModificationTime object_filename
212 return ([DotO object_filename], o_time)
214 let linkable = LM unlinked_time mod_name
215 (hs_unlinked ++ stub_unlinked)
217 return (CompOK details rdr_env iface (Just linkable))
219 -----------------------------------------------------------------------------
220 -- stub .h and .c files (for foreign export support)
222 compileStub dflags stub_c_exists
223 | not stub_c_exists = return Nothing
225 -- compile the _stub.c file w/ gcc
226 let stub_c = hscStubCOutName dflags
227 stub_o <- runPipeline (StopBefore Ln) "stub-compile"
228 True{-persistent output-}
229 Nothing{-no specific output file-}
231 Nothing{-no ModLocation-}
235 -- ---------------------------------------------------------------------------
238 link :: GhciMode -- interactive or batch
239 -> DynFlags -- dynamic flags
240 -> Bool -- attempt linking in batch mode?
241 -> HomePackageTable -- what to link
244 -- For the moment, in the batch linker, we don't bother to tell doLink
245 -- which packages to link -- it just tries all that are available.
246 -- batch_attempt_linking should only be *looked at* in batch mode. It
247 -- should only be True if the upsweep was successful and someone
248 -- exports main, i.e., we have good reason to believe that linking
252 link Interactive dflags batch_attempt_linking hpt
253 = do -- Not Linking...(demand linker will do the job)
257 link Batch dflags batch_attempt_linking hpt
258 | batch_attempt_linking
261 home_mod_infos = moduleEnvElts hpt
263 -- the packages we depend on
264 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
266 -- the linkables to link
267 linkables = map hm_linkable home_mod_infos
269 when (verb >= 3) $ do
270 hPutStrLn stderr "link: linkables are ..."
271 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
273 -- check for the -no-link flag
274 omit_linking <- readIORef v_NoLink
276 then do when (verb >= 3) $
277 hPutStrLn stderr "link(batch): linking omitted (-no-link flag given)."
282 hPutStrLn stderr "Linking ..."
284 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
285 obj_files = concatMap getOfiles linkables
287 -- Don't showPass in Batch mode; doLink will do that for us.
288 staticLink obj_files pkg_deps
290 when (verb >= 3) (hPutStrLn stderr "link: done")
292 -- staticLink only returns if it succeeds
296 = do when (verb >= 3) $ do
297 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
298 hPutStrLn stderr " Main.main not exported; not linking."
301 verb = verbosity dflags
303 -- ---------------------------------------------------------------------------
304 -- Run a compilation pipeline, consisting of multiple phases.
307 :: GhcMode -- when to stop
308 -> String -- "stop after" flag
309 -> Bool -- final output is persistent?
310 -> Maybe FilePath -- where to put the output, optionally
311 -> FilePath -- input filename
312 -> Maybe ModLocation -- a ModLocation for this module, if we have one
313 -> IO FilePath -- output filename
315 runPipeline todo stop_flag keep_output maybe_output_filename input_fn maybe_loc
317 split <- readIORef v_Split_object_files
318 let (basename, suffix) = splitFilename input_fn
319 start_phase = startPhase suffix
321 stop_phase = case todo of
322 StopBefore As | split -> SplitAs
323 StopBefore phase -> phase
328 -- We want to catch cases of "you can't get there from here" before
329 -- we start the pipeline, because otherwise it will just run off the
332 -- There is a partial ordering on phases, where A < B iff A occurs
333 -- before B in a normal compilation pipeline.
335 when (not (start_phase `happensBefore` stop_phase)) $
337 ("flag `" ++ stop_flag
338 ++ "' is incompatible with source file `"
341 -- generate a function which will be used to calculate output file names
343 get_output_fn <- genOutputFilenameFunc keep_output maybe_output_filename
346 -- and execute the pipeline...
347 (output_fn, maybe_loc) <-
348 pipeLoop start_phase stop_phase input_fn basename suffix
349 get_output_fn maybe_loc
351 -- sometimes, a compilation phase doesn't actually generate any output
352 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
353 -- stage, but we wanted to keep the output, then we have to explicitly
356 then do final_fn <- get_output_fn stop_phase maybe_loc
357 when (final_fn /= output_fn) $
358 copy ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
359 ++ "'") output_fn final_fn
365 pipeLoop :: Phase -> Phase -> FilePath -> String -> Suffix
366 -> (Phase -> Maybe ModLocation -> IO FilePath)
367 -> Maybe ModLocation -> IO (FilePath, Maybe ModLocation)
369 pipeLoop phase stop_phase input_fn orig_basename orig_suff
370 get_output_fn maybe_loc
372 | phase == stop_phase = return (input_fn, maybe_loc) -- all done
374 | not (phase `happensBefore` stop_phase) =
375 -- Something has gone wrong. We'll try to cover all the cases when
376 -- this could happen, so if we reach here it is a panic.
377 -- eg. it might happen if the -C flag is used on a source file that
378 -- has {-# OPTIONS -fasm #-}.
379 panic ("pipeLoop: at phase " ++ show phase ++
380 " but I wanted to stop at phase " ++ show stop_phase)
383 maybe_next_phase <- runPhase phase orig_basename orig_suff input_fn
384 get_output_fn maybe_loc
385 case maybe_next_phase of
386 (Nothing, maybe_loc, output_fn) -> do
387 -- we stopped early, but return the *final* filename
388 -- (it presumably already exists)
389 final_fn <- get_output_fn stop_phase maybe_loc
390 return (final_fn, maybe_loc)
391 (Just next_phase, maybe_loc, output_fn) ->
392 pipeLoop next_phase stop_phase output_fn
393 orig_basename orig_suff get_output_fn maybe_loc
396 genOutputFilenameFunc :: Bool -> Maybe FilePath -> Phase -> String
397 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
398 genOutputFilenameFunc keep_final_output maybe_output_filename
401 hcsuf <- readIORef v_HC_suf
402 odir <- readIORef v_Output_dir
403 osuf <- readIORef v_Object_suf
404 keep_hc <- readIORef v_Keep_hc_files
406 keep_il <- readIORef v_Keep_il_files
407 keep_ilx <- readIORef v_Keep_ilx_files
409 keep_raw_s <- readIORef v_Keep_raw_s_files
410 keep_s <- readIORef v_Keep_s_files
412 myPhaseInputExt HCc | Just s <- hcsuf = s
413 myPhaseInputExt Ln = osuf
414 myPhaseInputExt other = phaseInputExt other
416 func next_phase maybe_location
417 | is_last_phase, Just f <- maybe_output_filename = return f
418 | is_last_phase && keep_final_output = persistent_fn
419 | keep_this_output = persistent_fn
420 | otherwise = newTempName suffix
423 is_last_phase = next_phase == stop_phase
425 -- sometimes, we keep output from intermediate stages
429 Mangle | keep_raw_s -> True
431 HCc | keep_hc -> True
434 suffix = myPhaseInputExt next_phase
436 -- persistent object files get put in odir
438 | Ln <- next_phase = return odir_persistent
439 | otherwise = return persistent
441 persistent = basename ++ '.':suffix
444 | Just loc <- maybe_location = ml_obj_file loc
445 | Just d <- odir = replaceFilenameDirectory persistent d
446 | otherwise = persistent
451 -- -----------------------------------------------------------------------------
452 -- Each phase in the pipeline returns the next phase to execute, and the
453 -- name of the file in which the output was placed.
455 -- We must do things dynamically this way, because we often don't know
456 -- what the rest of the phases will be until part-way through the
457 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
458 -- of a source file can change the latter stages of the pipeline from
459 -- taking the via-C route to using the native code generator.
462 -> String -- basename of original input source
463 -> String -- its extension
464 -> FilePath -- name of file which contains the input to this phase.
465 -> (Phase -> Maybe ModLocation -> IO FilePath)
466 -- how to calculate the output filename
467 -> Maybe ModLocation -- the ModLocation, if we have one
468 -> IO (Maybe Phase, -- next phase
469 Maybe ModLocation, -- the ModLocation, if we have one
470 FilePath) -- output filename
472 -------------------------------------------------------------------------------
475 runPhase Unlit _basename _suff input_fn get_output_fn maybe_loc
476 = do unlit_flags <- getOpts opt_L
477 -- The -h option passes the file name for unlit to put in a #line directive
478 output_fn <- get_output_fn Cpp maybe_loc
480 SysTools.runUnlit (map SysTools.Option unlit_flags ++
481 [ SysTools.Option "-h"
482 , SysTools.Option input_fn
483 , SysTools.FileOption "" input_fn
484 , SysTools.FileOption "" output_fn
487 return (Just Cpp, maybe_loc, output_fn)
489 -------------------------------------------------------------------------------
492 runPhase Cpp basename suff input_fn get_output_fn maybe_loc
493 = do src_opts <- getOptionsFromSource input_fn
494 unhandled_flags <- processArgs dynamic_flags src_opts []
495 checkProcessArgsResult unhandled_flags basename suff
497 do_cpp <- dynFlag cppFlag
499 -- no need to preprocess CPP, just pass input file along
500 -- to the next phase of the pipeline.
501 return (Just HsPp, maybe_loc, input_fn)
503 output_fn <- get_output_fn HsPp maybe_loc
504 doCpp True{-raw-} False{-no CC opts-} input_fn output_fn
505 return (Just HsPp, maybe_loc, output_fn)
507 -------------------------------------------------------------------------------
510 runPhase HsPp basename suff input_fn get_output_fn maybe_loc
511 = do do_pp <- dynFlag ppFlag
513 -- no need to preprocess, just pass input file along
514 -- to the next phase of the pipeline.
515 return (Just Hsc, maybe_loc, input_fn)
517 hspp_opts <- getOpts opt_F
518 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
519 let orig_fn = basename ++ '.':suff
520 output_fn <- get_output_fn Hsc maybe_loc
521 SysTools.runPp ( [ SysTools.Option orig_fn
522 , SysTools.Option input_fn
523 , SysTools.FileOption "" output_fn
525 map SysTools.Option hs_src_pp_opts ++
526 map SysTools.Option hspp_opts
528 return (Just Hsc, maybe_loc, output_fn)
530 -----------------------------------------------------------------------------
533 -- Compilation of a single module, in "legacy" mode (_not_ under
534 -- the direction of the compilation manager).
535 runPhase Hsc basename suff input_fn get_output_fn _maybe_loc = do
536 todo <- readIORef v_GhcMode
537 if todo == DoMkDependHS then do
538 locn <- doMkDependHSPhase basename suff input_fn
539 return (Nothing, Just locn, input_fn) -- Ln is a dummy stop phase
542 -- normal Hsc mode, not mkdependHS
544 -- we add the current directory (i.e. the directory in which
545 -- the .hs files resides) to the import path, since this is
546 -- what gcc does, and it's probably what you want.
547 let current_dir = directoryOf basename
549 paths <- readIORef v_Include_paths
550 writeIORef v_Include_paths (current_dir : paths)
552 -- gather the imports and module name
554 if isExtCoreFilename ('.':suff)
556 -- no explicit imports in ExtCore input.
557 m <- getCoreModuleName input_fn
558 return ([], [], mkModuleName m)
560 getImportsFromFile input_fn
562 -- build a ModLocation to pass to hscMain.
563 (mod, location') <- mkHomeModLocation mod_name (basename ++ '.':suff)
565 -- take -ohi into account if present
566 ohi <- readIORef v_Output_hi
567 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
568 | otherwise = location'
570 -- figure out if the source has changed, for recompilation avoidance.
571 -- only do this if we're eventually going to generate a .o file.
572 -- (ToDo: do when generating .hc files too?)
574 -- Setting source_unchanged to True means that M.o seems
575 -- to be up to date wrt M.hs; so no need to recompile unless imports have
576 -- changed (which the compiler itself figures out).
577 -- Setting source_unchanged to False tells the compiler that M.o is out of
578 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
579 do_recomp <- readIORef v_Recomp
580 expl_o_file <- readIORef v_Output_file
582 let o_file -- if the -o option is given and IT IS THE OBJECT FILE FOR
583 -- THIS COMPILATION, then use that to determine if the
584 -- source is unchanged.
585 | Just x <- expl_o_file, todo == StopBefore Ln = x
586 | otherwise = ml_obj_file location
589 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
591 else do t1 <- getModificationTime (basename ++ '.':suff)
592 o_file_exists <- doesFileExist o_file
594 then return False -- Need to recompile
595 else do t2 <- getModificationTime o_file
601 dyn_flags <- getDynFlags
602 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
603 next_phase <- hscNextPhase hsc_lang
604 output_fn <- get_output_fn next_phase (Just location)
606 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
607 hscOutName = output_fn,
608 hscStubCOutName = basename ++ "_stub.c",
609 hscStubHOutName = basename ++ "_stub.h",
610 extCoreName = basename ++ ".hcr" }
611 hsc_env <- newHscEnv OneShot dyn_flags'
614 result <- hscMain hsc_env printErrorsAndWarnings mod
615 location{ ml_hspp_file=Just input_fn }
622 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
624 HscNoRecomp details iface -> do
625 SysTools.touch "Touching object file" o_file
626 return (Nothing, Just location, output_fn)
628 HscRecomp _details _rdr_env _iface
629 stub_h_exists stub_c_exists
630 _maybe_interpreted_code -> do
633 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
636 Just stub_o -> add v_Ld_inputs stub_o
637 case hscLang dyn_flags of
638 HscNothing -> return (Nothing, Just location, output_fn)
639 _ -> return (Just next_phase, Just location, output_fn)
641 -----------------------------------------------------------------------------
644 runPhase CmmCpp basename suff input_fn get_output_fn maybe_loc
646 output_fn <- get_output_fn Cmm maybe_loc
647 doCpp False{-not raw-} True{-include CC opts-} input_fn output_fn
648 return (Just Cmm, maybe_loc, output_fn)
650 runPhase Cmm basename suff input_fn get_output_fn maybe_loc
652 dyn_flags <- getDynFlags
653 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
654 next_phase <- hscNextPhase hsc_lang
655 output_fn <- get_output_fn next_phase maybe_loc
657 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
658 hscOutName = output_fn,
659 hscStubCOutName = basename ++ "_stub.c",
660 hscStubHOutName = basename ++ "_stub.h",
661 extCoreName = basename ++ ".hcr" }
663 ok <- hscCmmFile dyn_flags' input_fn
665 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
667 return (Just next_phase, maybe_loc, output_fn)
669 -----------------------------------------------------------------------------
672 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
673 -- way too many hacks, and I can't say I've ever used it anyway.
675 runPhase cc_phase basename suff input_fn get_output_fn maybe_loc
676 | cc_phase == Cc || cc_phase == HCc
677 = do cc_opts <- getOpts opt_c
678 cmdline_include_paths <- readIORef v_Include_paths
680 split <- readIORef v_Split_object_files
681 mangle <- readIORef v_Do_asm_mangling
683 let hcc = cc_phase == HCc
686 | hcc && mangle = Mangle
689 output_fn <- get_output_fn next_phase maybe_loc
691 -- HC files have the dependent packages stamped into them
692 pkgs <- if hcc then getHCFilePackages input_fn else return []
694 -- add package include paths even if we're just compiling .c
695 -- files; this is the Value Add(TM) that using ghc instead of
697 pkg_include_dirs <- getPackageIncludePath pkgs
698 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
699 (cmdline_include_paths ++ pkg_include_dirs)
701 mangle <- readIORef v_Do_asm_mangling
702 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
706 pkg_extra_cc_opts <- getPackageExtraCcOpts pkgs
708 split_objs <- readIORef v_Split_object_files
709 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
712 excessPrecision <- readIORef v_Excess_precision
714 -- force the C compiler to interpret this file as C when
715 -- compiling .hc files, by adding the -x c option.
717 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
720 SysTools.runCc (langopt ++
721 [ SysTools.FileOption "" input_fn
722 , SysTools.Option "-o"
723 , SysTools.FileOption "" output_fn
725 ++ map SysTools.Option (
727 ++ (if cc_phase == HCc && mangle
730 ++ [ verb, "-S", "-Wimplicit", "-O" ]
731 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
734 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
739 return (Just next_phase, maybe_loc, output_fn)
741 -- ToDo: postprocess the output from gcc
743 -----------------------------------------------------------------------------
746 runPhase Mangle _basename _suff input_fn get_output_fn maybe_loc
747 = do mangler_opts <- getOpts opt_m
748 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
749 then do n_regs <- dynFlag stolen_x86_regs
750 return [ show n_regs ]
753 split <- readIORef v_Split_object_files
755 | split = SplitMangle
757 output_fn <- get_output_fn next_phase maybe_loc
759 SysTools.runMangle (map SysTools.Option mangler_opts
760 ++ [ SysTools.FileOption "" input_fn
761 , SysTools.FileOption "" output_fn
763 ++ map SysTools.Option machdep_opts)
765 return (Just next_phase, maybe_loc, output_fn)
767 -----------------------------------------------------------------------------
770 runPhase SplitMangle _basename _suff input_fn get_output_fn maybe_loc
771 = do -- tmp_pfx is the prefix used for the split .s files
772 -- We also use it as the file to contain the no. of split .s files (sigh)
773 split_s_prefix <- SysTools.newTempName "split"
774 let n_files_fn = split_s_prefix
776 SysTools.runSplit [ SysTools.FileOption "" input_fn
777 , SysTools.FileOption "" split_s_prefix
778 , SysTools.FileOption "" n_files_fn
781 -- Save the number of split files for future references
782 s <- readFile n_files_fn
783 let n_files = read s :: Int
784 writeIORef v_Split_info (split_s_prefix, n_files)
786 -- Remember to delete all these files
787 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
790 return (Just SplitAs, maybe_loc, "**splitmangle**")
791 -- we don't use the filename
793 -----------------------------------------------------------------------------
796 runPhase As _basename _suff input_fn get_output_fn maybe_loc
797 = do as_opts <- getOpts opt_a
798 cmdline_include_paths <- readIORef v_Include_paths
800 output_fn <- get_output_fn Ln maybe_loc
802 -- we create directories for the object file, because it
803 -- might be a hierarchical module.
804 createDirectoryHierarchy (directoryOf output_fn)
806 SysTools.runAs (map SysTools.Option as_opts
807 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
808 ++ [ SysTools.Option "-c"
809 , SysTools.FileOption "" input_fn
810 , SysTools.Option "-o"
811 , SysTools.FileOption "" output_fn
814 return (Just Ln, maybe_loc, output_fn)
817 runPhase SplitAs basename _suff _input_fn get_output_fn maybe_loc
818 = do as_opts <- getOpts opt_a
820 (split_s_prefix, n) <- readIORef v_Split_info
822 odir <- readIORef v_Output_dir
823 let real_odir = case odir of
824 Nothing -> basename ++ "_split"
828 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
829 let output_o = replaceFilenameDirectory
830 (basename ++ "__" ++ show n ++ ".o")
832 real_o <- osuf_ify output_o
833 SysTools.runAs (map SysTools.Option as_opts ++
834 [ SysTools.Option "-c"
835 , SysTools.Option "-o"
836 , SysTools.FileOption "" real_o
837 , SysTools.FileOption "" input_s
840 mapM_ assemble_file [1..n]
842 output_fn <- get_output_fn Ln maybe_loc
843 return (Just Ln, maybe_loc, output_fn)
846 -----------------------------------------------------------------------------
848 -- Run ilx2il over the ILX output, getting an IL file
850 runPhase Ilx2Il _basename _suff input_fn get_output_fn maybe_loc
851 = do ilx2il_opts <- getOpts opt_I
852 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
853 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
854 SysTools.Option "mscorlib",
855 SysTools.Option "-o",
856 SysTools.FileOption "" output_fn,
857 SysTools.FileOption "" input_fn ])
860 -----------------------------------------------------------------------------
862 -- Run ilasm over the IL, getting a DLL
864 runPhase Ilasm _basename _suff input_fn get_output_fn maybe_loc
865 = do ilasm_opts <- getOpts opt_i
866 SysTools.runIlasm (map SysTools.Option ilasm_opts
867 ++ [ SysTools.Option "/QUIET",
868 SysTools.Option "/DLL",
869 SysTools.FileOption "/OUT=" output_fn,
870 SysTools.FileOption "" input_fn ])
875 -----------------------------------------------------------------------------
876 -- MoveBinary sort-of-phase
877 -- After having produced a binary, move it somewhere else and generate a
878 -- wrapper script calling the binary. Currently, we need this only in
879 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
880 -- central directory.
881 -- This is called from staticLink below, after linking. I haven't made it
882 -- a separate phase to minimise interfering with other modules, and
883 -- we don't need the generality of a phase (MoveBinary is always
884 -- done after linking and makes only sense in a parallel setup) -- HWL
886 runPhase_MoveBinary input_fn
889 pvm_root <- getEnv "PVM_ROOT"
890 pvm_arch <- getEnv "PVM_ARCH"
892 pvm_executable_base = "=" ++ input_fn
893 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
894 -- nuke old binary; maybe use configur'ed names for cp and rm?
895 system ("rm -f " ++ pvm_executable)
896 -- move the newly created binary into PVM land
897 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
898 -- generate a wrapper script for running a parallel prg under PVM
899 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
902 -- generates a Perl skript starting a parallel prg under PVM
903 mk_pvm_wrapper_script :: String -> String -> String -> String
904 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
906 "eval 'exec perl -S $0 ${1+\"$@\"}'",
907 " if $running_under_some_shell;",
908 "# =!=!=!=!=!=!=!=!=!=!=!",
909 "# This script is automatically generated: DO NOT EDIT!!!",
910 "# Generated by Glasgow Haskell Compiler",
911 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
913 "$pvm_executable = '" ++ pvm_executable ++ "';",
914 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
915 "$SysMan = '" ++ sysMan ++ "';",
917 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
918 "# first, some magical shortcuts to run "commands" on the binary",
919 "# (which is hidden)",
920 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
921 " local($cmd) = $1;",
922 " system("$cmd $pvm_executable");",
923 " exit(0); # all done",
926 "# Now, run the real binary; process the args first",
927 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
929 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
930 "@nonPVM_args = ();",
933 "args: while ($a = shift(@ARGV)) {",
934 " if ( $a eq '+RTS' ) {",
935 " $in_RTS_args = 1;",
936 " } elsif ( $a eq '-RTS' ) {",
937 " $in_RTS_args = 0;",
939 " if ( $a eq '-d' && $in_RTS_args ) {",
941 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
942 " $nprocessors = $1;",
943 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
944 " $nprocessors = $1;",
946 " push(@nonPVM_args, $a);",
950 "local($return_val) = 0;",
951 "# Start the parallel execution by calling SysMan",
952 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
954 "# ToDo: fix race condition moving files and flushing them!!",
955 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
959 -----------------------------------------------------------------------------
960 -- Complain about non-dynamic flags in OPTIONS pragmas
962 checkProcessArgsResult flags basename suff
963 = do when (notNull flags) (throwDyn (ProgramError (
964 showSDoc (hang (text basename <> text ('.':suff) <> char ':')
965 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
966 hsep (map text flags)))
969 -----------------------------------------------------------------------------
970 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
972 getHCFilePackages :: FilePath -> IO [PackageName]
973 getHCFilePackages filename =
974 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
977 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
978 return (map mkPackageName (words rest))
982 -----------------------------------------------------------------------------
983 -- Static linking, of .o files
985 -- The list of packages passed to link is the list of packages on
986 -- which this program depends, as discovered by the compilation
987 -- manager. It is combined with the list of packages that the user
988 -- specifies on the command line with -package flags.
990 -- In one-shot linking mode, we can't discover the package
991 -- dependencies (because we haven't actually done any compilation or
992 -- read any interface files), so the user must explicitly specify all
995 staticLink :: [FilePath] -> [PackageName] -> IO ()
996 staticLink o_files dep_packages = do
998 static <- readIORef v_Static
999 no_hs_main <- readIORef v_NoHsMain
1001 -- get the full list of packages to link with, by combining the
1002 -- explicit packages with the auto packages and all of their
1003 -- dependencies, and eliminating duplicates.
1005 o_file <- readIORef v_Output_file
1006 #if defined(mingw32_HOST_OS)
1007 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1009 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1012 pkg_lib_paths <- getPackageLibraryPath dep_packages
1013 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1015 lib_paths <- readIORef v_Library_paths
1016 let lib_path_opts = map ("-L"++) lib_paths
1018 pkg_link_opts <- getPackageLinkOpts dep_packages
1020 #ifdef darwin_TARGET_OS
1021 pkg_framework_paths <- getPackageFrameworkPath dep_packages
1022 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1024 framework_paths <- readIORef v_Framework_paths
1025 let framework_path_opts = map ("-F"++) framework_paths
1027 pkg_frameworks <- getPackageFrameworks dep_packages
1028 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1030 frameworks <- readIORef v_Cmdline_frameworks
1031 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1032 -- reverse because they're added in reverse order from the cmd line
1035 -- probably _stub.o files
1036 extra_ld_inputs <- readIORef v_Ld_inputs
1038 -- opts from -optl-<blah> (including -l<blah> options)
1039 extra_ld_opts <- getStaticOpts v_Opt_l
1041 [rts_pkg, std_pkg] <- getPackageDetails [rtsPackage, basePackage]
1043 ways <- readIORef v_Ways
1045 -- Here are some libs that need to be linked at the *end* of
1046 -- the command line, because they contain symbols that are referred to
1047 -- by the RTS. We can't therefore use the ordinary way opts for these.
1049 debug_opts | WayDebug `elem` ways = [
1050 #if defined(HAVE_LIBBFD)
1057 thread_opts | WayThreaded `elem` ways = [
1058 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1061 #if defined(osf3_TARGET_OS)
1067 let extra_os = if static || no_hs_main
1069 else [ head (library_dirs rts_pkg) ++ "/Main.dll_o",
1070 head (library_dirs std_pkg) ++ "/PrelMain.dll_o" ]
1072 (md_c_flags, _) <- machdepCCOpts
1073 SysTools.runLink ( [ SysTools.Option verb
1074 , SysTools.Option "-o"
1075 , SysTools.FileOption "" output_fn
1077 ++ map SysTools.Option (
1084 #ifdef darwin_TARGET_OS
1085 ++ framework_path_opts
1088 ++ pkg_lib_path_opts
1090 #ifdef darwin_TARGET_OS
1091 ++ pkg_framework_path_opts
1092 ++ pkg_framework_opts
1098 -- parallel only: move binary to another dir -- HWL
1099 ways_ <- readIORef v_Ways
1100 when (WayPar `elem` ways_)
1101 (do success <- runPhase_MoveBinary output_fn
1102 if success then return ()
1103 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1105 -----------------------------------------------------------------------------
1106 -- Making a DLL (only for Win32)
1108 doMkDLL :: [String] -> [PackageName] -> IO ()
1109 doMkDLL o_files dep_packages = do
1111 static <- readIORef v_Static
1112 no_hs_main <- readIORef v_NoHsMain
1114 o_file <- readIORef v_Output_file
1115 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1117 pkg_lib_paths <- getPackageLibraryPath dep_packages
1118 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1120 lib_paths <- readIORef v_Library_paths
1121 let lib_path_opts = map ("-L"++) lib_paths
1123 pkg_link_opts <- getPackageLinkOpts dep_packages
1125 -- probably _stub.o files
1126 extra_ld_inputs <- readIORef v_Ld_inputs
1128 -- opts from -optdll-<blah>
1129 extra_ld_opts <- getStaticOpts v_Opt_dll
1131 [rts_pkg, std_pkg] <- getPackageDetails [rtsPackage, basePackage]
1133 let extra_os = if static || no_hs_main
1135 else [ head (library_dirs rts_pkg) ++ "/Main.dll_o",
1136 head (library_dirs std_pkg) ++ "/PrelMain.dll_o" ]
1138 (md_c_flags, _) <- machdepCCOpts
1140 ([ SysTools.Option verb
1141 , SysTools.Option "-o"
1142 , SysTools.FileOption "" output_fn
1144 ++ map SysTools.Option (
1148 ++ [ "--target=i386-mingw32" ]
1152 ++ pkg_lib_path_opts
1154 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1156 else [ "--export-all" ])
1159 -- -----------------------------------------------------------------------------
1162 doCpp :: Bool -> Bool -> FilePath -> FilePath -> IO ()
1163 doCpp raw include_cc_opts input_fn output_fn = do
1164 hscpp_opts <- getOpts opt_P
1166 cmdline_include_paths <- readIORef v_Include_paths
1168 pkg_include_dirs <- getPackageIncludePath []
1169 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1170 (cmdline_include_paths ++ pkg_include_dirs)
1174 cc_opts <- if not include_cc_opts
1176 else do optc <- getOpts opt_c
1177 (md_c_flags, _) <- machdepCCOpts
1178 return (optc ++ md_c_flags)
1180 let cpp_prog args | raw = SysTools.runCpp args
1181 | otherwise = SysTools.runCc (SysTools.Option "-E" : args)
1184 [ "-D" ++ cTARGETOS ++ "_TARGET_OS=1",
1185 "-D" ++ cTARGETARCH ++ "_TARGET_ARCH=1" ]
1187 cpp_prog ([SysTools.Option verb]
1188 ++ map SysTools.Option include_paths
1189 ++ map SysTools.Option hsSourceCppOpts
1190 ++ map SysTools.Option hscpp_opts
1191 ++ map SysTools.Option cc_opts
1192 ++ map SysTools.Option target_defs
1193 ++ [ SysTools.Option "-x"
1194 , SysTools.Option "c"
1195 , SysTools.Option input_fn
1196 -- We hackily use Option instead of FileOption here, so that the file
1197 -- name is not back-slashed on Windows. cpp is capable of
1198 -- dealing with / in filenames, so it works fine. Furthermore
1199 -- if we put in backslashes, cpp outputs #line directives
1200 -- with *double* backslashes. And that in turn means that
1201 -- our error messages get double backslashes in them.
1202 -- In due course we should arrange that the lexer deals
1203 -- with these \\ escapes properly.
1204 , SysTools.Option "-o"
1205 , SysTools.FileOption "" output_fn
1208 -- -----------------------------------------------------------------------------
1211 hscNextPhase :: HscLang -> IO Phase
1212 hscNextPhase hsc_lang = do
1213 split <- readIORef v_Split_object_files
1214 return (case hsc_lang of
1216 HscAsm | split -> SplitMangle
1218 HscNothing -> HCc -- dummy (no output will be generated)
1219 HscInterpreted -> HCc -- "" ""
1220 _other -> HCc -- "" ""
1223 hscMaybeAdjustLang :: HscLang -> IO HscLang
1224 hscMaybeAdjustLang current_hsc_lang = do
1225 todo <- readIORef v_GhcMode
1226 keep_hc <- readIORef v_Keep_hc_files
1228 -- don't change the lang if we're interpreting
1229 | current_hsc_lang == HscInterpreted = current_hsc_lang
1230 -- force -fvia-C if we are being asked for a .hc file
1231 | todo == StopBefore HCc || keep_hc = HscC
1232 -- otherwise, stick to the plan
1233 | otherwise = current_hsc_lang