1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2002
7 -----------------------------------------------------------------------------
9 #include "../includes/config.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 )
56 import Time ( getClockTime )
65 -- ---------------------------------------------------------------------------
68 -- Just preprocess a file, put the result in a temp. file (used by the
69 -- compilation manager during the summary phase).
71 preprocess :: FilePath -> IO FilePath
73 ASSERT(isHaskellSrcFilename filename)
74 do restoreDynFlags -- Restore to state of last save
75 runPipeline (StopBefore Hsc) ("preprocess")
76 False{-temporary output file-}
77 Nothing{-no specific output file-}
79 Nothing{-no ModLocation-}
81 -- ---------------------------------------------------------------------------
84 -- Compile a single module, under the control of the compilation manager.
86 -- This is the interface between the compilation manager and the
87 -- compiler proper (hsc), where we deal with tedious details like
88 -- reading the OPTIONS pragma from the source file, and passing the
89 -- output of hsc through the C compiler.
91 -- The driver sits between 'compile' and 'hscMain', translating calls
92 -- to the former into calls to the latter, and results from the latter
93 -- into results from the former. It does things like preprocessing
94 -- the .hs file if necessary, and compiling up the .stub_c files to
95 -- generate Linkables.
97 -- NB. No old interface can also mean that the source has changed.
102 -> Bool -- True <=> source unchanged
103 -> Bool -- True <=> have object
104 -> Maybe ModIface -- old interface, if available
108 = CompOK ModDetails -- New details
109 (Maybe GlobalRdrEnv) -- Lexical environment for the module
110 -- (Maybe because we may have loaded it from
111 -- its precompiled interface)
112 ModIface -- New iface
113 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
114 -- (old code is still valid)
119 compile hsc_env this_mod location
120 source_unchanged have_object
123 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
126 (showSDoc (text "Compiling" <+> ppr this_mod))
128 let verb = verbosity dyn_flags
129 let input_fn = expectJust "compile:hs" (ml_hs_file location)
130 let input_fnpp = expectJust "compile:hspp" (ml_hspp_file location)
131 let mod_name = moduleName this_mod
133 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
135 opts <- getOptionsFromSource input_fnpp
136 processArgs dynamic_flags opts []
137 dyn_flags <- getDynFlags
139 let (basename, _) = splitFilename input_fn
141 -- figure out what lang we're generating
142 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
143 -- figure out what the next phase should be
144 next_phase <- hscNextPhase hsc_lang
145 -- figure out what file to generate the output into
146 get_output_fn <- genOutputFilenameFunc False Nothing next_phase basename
147 output_fn <- get_output_fn next_phase (Just location)
149 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
150 hscOutName = output_fn,
151 hscStubCOutName = basename ++ "_stub.c",
152 hscStubHOutName = basename ++ "_stub.h",
153 extCoreName = basename ++ ".hcr" }
155 -- -no-recomp should also work with --make
156 do_recomp <- readIORef v_Recomp
157 let source_unchanged' = source_unchanged && do_recomp
158 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
161 hsc_result <- hscMain hsc_env' this_mod location
162 source_unchanged' have_object old_iface
165 HscFail -> return CompErrs
167 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
169 HscRecomp details rdr_env iface
170 stub_h_exists stub_c_exists maybe_interpreted_code -> do
172 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
173 let stub_unlinked = case maybe_stub_o of
175 Just stub_o -> [ DotO stub_o ]
177 (hs_unlinked, unlinked_time) <-
180 -- in interpreted mode, just return the compiled code
181 -- as our "unlinked" object.
183 case maybe_interpreted_code of
185 Just comp_bc -> do tm <- getClockTime
186 return ([BCOs comp_bc], tm)
188 Nothing -> panic "compile: no interpreted code"
190 -- we're in batch mode: finish the compilation pipeline.
192 let object_filename = ml_obj_file location
194 runPipeline (StopBefore Ln) ""
195 True Nothing output_fn (Just location)
196 -- the object filename comes from the ModLocation
198 o_time <- getModificationTime object_filename
199 return ([DotO object_filename], o_time)
201 let linkable = LM unlinked_time mod_name
202 (hs_unlinked ++ stub_unlinked)
204 return (CompOK details rdr_env iface (Just linkable))
206 -----------------------------------------------------------------------------
207 -- stub .h and .c files (for foreign export support)
209 compileStub dflags stub_c_exists
210 | not stub_c_exists = return Nothing
212 -- compile the _stub.c file w/ gcc
213 let stub_c = hscStubCOutName dflags
214 stub_o <- runPipeline (StopBefore Ln) "stub-compile"
215 True{-persistent output-}
216 Nothing{-no specific output file-}
218 Nothing{-no ModLocation-}
222 -- ---------------------------------------------------------------------------
225 link :: GhciMode -- interactive or batch
226 -> DynFlags -- dynamic flags
227 -> Bool -- attempt linking in batch mode?
228 -> HomePackageTable -- what to link
231 -- For the moment, in the batch linker, we don't bother to tell doLink
232 -- which packages to link -- it just tries all that are available.
233 -- batch_attempt_linking should only be *looked at* in batch mode. It
234 -- should only be True if the upsweep was successful and someone
235 -- exports main, i.e., we have good reason to believe that linking
239 link Interactive dflags batch_attempt_linking hpt
240 = do -- Not Linking...(demand linker will do the job)
244 link Batch dflags batch_attempt_linking hpt
245 | batch_attempt_linking
248 home_mod_infos = moduleEnvElts hpt
250 -- the packages we depend on
251 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
253 -- the linkables to link
254 linkables = map hm_linkable home_mod_infos
256 when (verb >= 3) $ do
257 hPutStrLn stderr "link: linkables are ..."
258 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
260 -- check for the -no-link flag
261 omit_linking <- readIORef v_NoLink
263 then do when (verb >= 3) $
264 hPutStrLn stderr "link(batch): linking omitted (-no-link flag given)."
269 hPutStrLn stderr "Linking ..."
271 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
272 obj_files = concatMap getOfiles linkables
274 -- Don't showPass in Batch mode; doLink will do that for us.
275 staticLink obj_files pkg_deps
277 when (verb >= 3) (hPutStrLn stderr "link: done")
279 -- staticLink only returns if it succeeds
283 = do when (verb >= 3) $ do
284 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
285 hPutStrLn stderr " Main.main not exported; not linking."
288 verb = verbosity dflags
290 -- ---------------------------------------------------------------------------
291 -- Run a compilation pipeline, consisting of multiple phases.
294 :: GhcMode -- when to stop
295 -> String -- "stop after" flag
296 -> Bool -- final output is persistent?
297 -> Maybe FilePath -- where to put the output, optionally
298 -> FilePath -- input filename
299 -> Maybe ModLocation -- a ModLocation for this module, if we have one
300 -> IO FilePath -- output filename
302 runPipeline todo stop_flag keep_output maybe_output_filename input_fn maybe_loc
304 split <- readIORef v_Split_object_files
305 let (basename, suffix) = splitFilename input_fn
306 start_phase = startPhase suffix
308 stop_phase = case todo of
309 StopBefore As | split -> SplitAs
310 StopBefore phase -> phase
315 -- We want to catch cases of "you can't get there from here" before
316 -- we start the pipeline, because otherwise it will just run off the
319 -- There is a partial ordering on phases, where A < B iff A occurs
320 -- before B in a normal compilation pipeline.
322 when (not (start_phase `happensBefore` stop_phase)) $
324 ("flag `" ++ stop_flag
325 ++ "' is incompatible with source file `"
328 -- generate a function which will be used to calculate output file names
330 get_output_fn <- genOutputFilenameFunc keep_output maybe_output_filename
333 -- and execute the pipeline...
334 (output_fn, maybe_loc) <-
335 pipeLoop start_phase stop_phase input_fn basename suffix
336 get_output_fn maybe_loc
338 -- sometimes, a compilation phase doesn't actually generate any output
339 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
340 -- stage, but we wanted to keep the output, then we have to explicitly
343 then do final_fn <- get_output_fn stop_phase maybe_loc
344 when (final_fn /= output_fn) $
345 copy ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
346 ++ "'") output_fn final_fn
352 pipeLoop :: Phase -> Phase -> FilePath -> String -> Suffix
353 -> (Phase -> Maybe ModLocation -> IO FilePath)
354 -> Maybe ModLocation -> IO (FilePath, Maybe ModLocation)
356 pipeLoop phase stop_phase input_fn orig_basename orig_suff
357 get_output_fn maybe_loc
359 | phase == stop_phase = return (input_fn, maybe_loc) -- all done
361 | not (phase `happensBefore` stop_phase) =
362 -- Something has gone wrong. We'll try to cover all the cases when
363 -- this could happen, so if we reach here it is a panic.
364 -- eg. it might happen if the -C flag is used on a source file that
365 -- has {-# OPTIONS -fasm #-}.
366 panic ("pipeLoop: at phase " ++ show phase ++
367 " but I wanted to stop at phase " ++ show stop_phase)
370 maybe_next_phase <- runPhase phase orig_basename orig_suff input_fn
371 get_output_fn maybe_loc
372 case maybe_next_phase of
373 (Nothing, maybe_loc, output_fn) -> do
374 -- we stopped early, but return the *final* filename
375 -- (it presumably already exists)
376 final_fn <- get_output_fn stop_phase maybe_loc
377 return (final_fn, maybe_loc)
378 (Just next_phase, maybe_loc, output_fn) ->
379 pipeLoop next_phase stop_phase output_fn
380 orig_basename orig_suff get_output_fn maybe_loc
383 genOutputFilenameFunc :: Bool -> Maybe FilePath -> Phase -> String
384 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
385 genOutputFilenameFunc keep_final_output maybe_output_filename
388 hcsuf <- readIORef v_HC_suf
389 odir <- readIORef v_Output_dir
390 osuf <- readIORef v_Object_suf
391 keep_hc <- readIORef v_Keep_hc_files
393 keep_il <- readIORef v_Keep_il_files
394 keep_ilx <- readIORef v_Keep_ilx_files
396 keep_raw_s <- readIORef v_Keep_raw_s_files
397 keep_s <- readIORef v_Keep_s_files
399 myPhaseInputExt HCc | Just s <- hcsuf = s
400 myPhaseInputExt Ln = osuf
401 myPhaseInputExt other = phaseInputExt other
403 func next_phase maybe_location
404 | is_last_phase, Just f <- maybe_output_filename = return f
405 | is_last_phase && keep_final_output = persistent_fn
406 | keep_this_output = persistent_fn
407 | otherwise = newTempName suffix
410 is_last_phase = next_phase == stop_phase
412 -- sometimes, we keep output from intermediate stages
416 Mangle | keep_raw_s -> True
418 HCc | keep_hc -> True
421 suffix = myPhaseInputExt next_phase
423 -- persistent object files get put in odir
425 | Ln <- next_phase = return odir_persistent
426 | otherwise = return persistent
428 persistent = basename ++ '.':suffix
431 | Just loc <- maybe_location = ml_obj_file loc
432 | Just d <- odir = replaceFilenameDirectory persistent d
433 | otherwise = persistent
438 -- -----------------------------------------------------------------------------
439 -- Each phase in the pipeline returns the next phase to execute, and the
440 -- name of the file in which the output was placed.
442 -- We must do things dynamically this way, because we often don't know
443 -- what the rest of the phases will be until part-way through the
444 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
445 -- of a source file can change the latter stages of the pipeline from
446 -- taking the via-C route to using the native code generator.
449 -> String -- basename of original input source
450 -> String -- its extension
451 -> FilePath -- name of file which contains the input to this phase.
452 -> (Phase -> Maybe ModLocation -> IO FilePath)
453 -- how to calculate the output filename
454 -> Maybe ModLocation -- the ModLocation, if we have one
455 -> IO (Maybe Phase, -- next phase
456 Maybe ModLocation, -- the ModLocation, if we have one
457 FilePath) -- output filename
459 -------------------------------------------------------------------------------
462 runPhase Unlit _basename _suff input_fn get_output_fn maybe_loc
463 = do unlit_flags <- getOpts opt_L
464 -- The -h option passes the file name for unlit to put in a #line directive
465 output_fn <- get_output_fn Cpp maybe_loc
467 SysTools.runUnlit (map SysTools.Option unlit_flags ++
468 [ SysTools.Option "-h"
469 , SysTools.Option input_fn
470 , SysTools.FileOption "" input_fn
471 , SysTools.FileOption "" output_fn
474 return (Just Cpp, maybe_loc, output_fn)
476 -------------------------------------------------------------------------------
479 runPhase Cpp basename suff input_fn get_output_fn maybe_loc
480 = do src_opts <- getOptionsFromSource input_fn
481 unhandled_flags <- processArgs dynamic_flags src_opts []
482 checkProcessArgsResult unhandled_flags basename suff
484 do_cpp <- dynFlag cppFlag
486 -- no need to preprocess CPP, just pass input file along
487 -- to the next phase of the pipeline.
488 return (Just HsPp, maybe_loc, input_fn)
490 hscpp_opts <- getOpts opt_P
491 hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
493 cmdline_include_paths <- readIORef v_Include_paths
495 pkg_include_dirs <- getPackageIncludePath []
496 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
497 (cmdline_include_paths ++ pkg_include_dirs)
500 (md_c_flags, _) <- machdepCCOpts
502 output_fn <- get_output_fn HsPp maybe_loc
504 SysTools.runCpp ([SysTools.Option verb]
505 ++ map SysTools.Option include_paths
506 ++ map SysTools.Option hs_src_cpp_opts
507 ++ map SysTools.Option hscpp_opts
508 ++ map SysTools.Option md_c_flags
509 ++ [ SysTools.Option "-x"
510 , SysTools.Option "c"
511 , SysTools.Option input_fn
512 -- We hackily use Option instead of FileOption here, so that the file
513 -- name is not back-slashed on Windows. cpp is capable of
514 -- dealing with / in filenames, so it works fine. Furthermore
515 -- if we put in backslashes, cpp outputs #line directives
516 -- with *double* backslashes. And that in turn means that
517 -- our error messages get double backslashes in them.
518 -- In due course we should arrange that the lexer deals
519 -- with these \\ escapes properly.
520 , SysTools.Option "-o"
521 , SysTools.FileOption "" output_fn
524 return (Just HsPp, maybe_loc, output_fn)
526 -------------------------------------------------------------------------------
529 runPhase HsPp basename suff input_fn get_output_fn maybe_loc
530 = do do_pp <- dynFlag ppFlag
532 -- no need to preprocess, just pass input file along
533 -- to the next phase of the pipeline.
534 return (Just Hsc, maybe_loc, input_fn)
536 hspp_opts <- getOpts opt_F
537 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
538 let orig_fn = basename ++ '.':suff
539 output_fn <- get_output_fn Hsc maybe_loc
540 SysTools.runPp ( [ SysTools.Option orig_fn
541 , SysTools.Option input_fn
542 , SysTools.FileOption "" output_fn
544 map SysTools.Option hs_src_pp_opts ++
545 map SysTools.Option hspp_opts
547 return (Just Hsc, maybe_loc, output_fn)
549 -----------------------------------------------------------------------------
552 -- Compilation of a single module, in "legacy" mode (_not_ under
553 -- the direction of the compilation manager).
554 runPhase Hsc basename suff input_fn get_output_fn _maybe_loc = do
555 todo <- readIORef v_GhcMode
556 if todo == DoMkDependHS then do
557 locn <- doMkDependHSPhase basename suff input_fn
558 return (Nothing, Just locn, input_fn) -- Ln is a dummy stop phase
561 -- normal Hsc mode, not mkdependHS
563 -- we add the current directory (i.e. the directory in which
564 -- the .hs files resides) to the import path, since this is
565 -- what gcc does, and it's probably what you want.
566 let current_dir = directoryOf basename
568 paths <- readIORef v_Include_paths
569 writeIORef v_Include_paths (current_dir : paths)
571 -- gather the imports and module name
573 if isExtCoreFilename ('.':suff)
575 -- no explicit imports in ExtCore input.
576 m <- getCoreModuleName input_fn
577 return ([], [], mkModuleName m)
579 getImportsFromFile input_fn
581 -- build a ModLocation to pass to hscMain.
582 (mod, location') <- mkHomeModLocation mod_name (basename ++ '.':suff)
584 -- take -ohi into account if present
585 ohi <- readIORef v_Output_hi
586 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
587 | otherwise = location'
589 -- figure out if the source has changed, for recompilation avoidance.
590 -- only do this if we're eventually going to generate a .o file.
591 -- (ToDo: do when generating .hc files too?)
593 -- Setting source_unchanged to True means that M.o seems
594 -- to be up to date wrt M.hs; so no need to recompile unless imports have
595 -- changed (which the compiler itself figures out).
596 -- Setting source_unchanged to False tells the compiler that M.o is out of
597 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
598 do_recomp <- readIORef v_Recomp
599 expl_o_file <- readIORef v_Output_file
601 let o_file -- if the -o option is given and IT IS THE OBJECT FILE FOR
602 -- THIS COMPILATION, then use that to determine if the
603 -- source is unchanged.
604 | Just x <- expl_o_file, todo == StopBefore Ln = x
605 | otherwise = ml_obj_file location
608 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
610 else do t1 <- getModificationTime (basename ++ '.':suff)
611 o_file_exists <- doesFileExist o_file
613 then return False -- Need to recompile
614 else do t2 <- getModificationTime o_file
620 dyn_flags <- getDynFlags
621 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
622 next_phase <- hscNextPhase hsc_lang
623 output_fn <- get_output_fn next_phase (Just location)
625 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
626 hscOutName = output_fn,
627 hscStubCOutName = basename ++ "_stub.c",
628 hscStubHOutName = basename ++ "_stub.h",
629 extCoreName = basename ++ ".hcr" }
630 hsc_env <- newHscEnv OneShot dyn_flags'
633 result <- hscMain hsc_env mod
634 location{ ml_hspp_file=Just input_fn }
641 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
643 HscNoRecomp details iface -> do
644 SysTools.touch "Touching object file" o_file
645 return (Nothing, Just location, output_fn)
647 HscRecomp _details _rdr_env _iface
648 stub_h_exists stub_c_exists
649 _maybe_interpreted_code -> do
652 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
655 Just stub_o -> add v_Ld_inputs stub_o
656 case hscLang dyn_flags of
657 HscNothing -> return (Nothing, Just location, output_fn)
658 _ -> return (Just next_phase, Just location, output_fn)
660 -----------------------------------------------------------------------------
663 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
664 -- way too many hacks, and I can't say I've ever used it anyway.
666 runPhase cc_phase basename suff input_fn get_output_fn maybe_loc
667 | cc_phase == Cc || cc_phase == HCc
668 = do cc_opts <- getOpts opt_c
669 cmdline_include_paths <- readIORef v_Include_paths
671 split <- readIORef v_Split_object_files
672 mangle <- readIORef v_Do_asm_mangling
674 let hcc = cc_phase == HCc
677 | hcc && mangle = Mangle
680 output_fn <- get_output_fn next_phase maybe_loc
682 -- HC files have the dependent packages stamped into them
683 pkgs <- if hcc then getHCFilePackages input_fn else return []
685 -- add package include paths even if we're just compiling .c
686 -- files; this is the Value Add(TM) that using ghc instead of
688 pkg_include_dirs <- getPackageIncludePath pkgs
689 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
690 (cmdline_include_paths ++ pkg_include_dirs)
692 mangle <- readIORef v_Do_asm_mangling
693 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
697 pkg_extra_cc_opts <- getPackageExtraCcOpts pkgs
699 split_objs <- readIORef v_Split_object_files
700 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
703 excessPrecision <- readIORef v_Excess_precision
705 -- force the C compiler to interpret this file as C when
706 -- compiling .hc files, by adding the -x c option.
708 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
711 SysTools.runCc (langopt ++
712 [ SysTools.FileOption "" input_fn
713 , SysTools.Option "-o"
714 , SysTools.FileOption "" output_fn
716 ++ map SysTools.Option (
718 ++ (if cc_phase == HCc && mangle
721 ++ [ verb, "-S", "-Wimplicit", "-O" ]
722 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
725 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
730 return (Just next_phase, maybe_loc, output_fn)
732 -- ToDo: postprocess the output from gcc
734 -----------------------------------------------------------------------------
737 runPhase Mangle _basename _suff input_fn get_output_fn maybe_loc
738 = do mangler_opts <- getOpts opt_m
739 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
740 then do n_regs <- dynFlag stolen_x86_regs
741 return [ show n_regs ]
744 split <- readIORef v_Split_object_files
746 | split = SplitMangle
748 output_fn <- get_output_fn next_phase maybe_loc
750 SysTools.runMangle (map SysTools.Option mangler_opts
751 ++ [ SysTools.FileOption "" input_fn
752 , SysTools.FileOption "" output_fn
754 ++ map SysTools.Option machdep_opts)
756 return (Just next_phase, maybe_loc, output_fn)
758 -----------------------------------------------------------------------------
761 runPhase SplitMangle _basename _suff input_fn get_output_fn maybe_loc
762 = do -- tmp_pfx is the prefix used for the split .s files
763 -- We also use it as the file to contain the no. of split .s files (sigh)
764 split_s_prefix <- SysTools.newTempName "split"
765 let n_files_fn = split_s_prefix
767 SysTools.runSplit [ SysTools.FileOption "" input_fn
768 , SysTools.FileOption "" split_s_prefix
769 , SysTools.FileOption "" n_files_fn
772 -- Save the number of split files for future references
773 s <- readFile n_files_fn
774 let n_files = read s :: Int
775 writeIORef v_Split_info (split_s_prefix, n_files)
777 -- Remember to delete all these files
778 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
781 return (Just SplitAs, maybe_loc, "**splitmangle**")
782 -- we don't use the filename
784 -----------------------------------------------------------------------------
787 runPhase As _basename _suff input_fn get_output_fn maybe_loc
788 = do as_opts <- getOpts opt_a
789 cmdline_include_paths <- readIORef v_Include_paths
791 output_fn <- get_output_fn Ln maybe_loc
793 -- we create directories for the object file, because it
794 -- might be a hierarchical module.
795 createDirectoryHierarchy (directoryOf output_fn)
797 SysTools.runAs (map SysTools.Option as_opts
798 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
799 ++ [ SysTools.Option "-c"
800 , SysTools.FileOption "" input_fn
801 , SysTools.Option "-o"
802 , SysTools.FileOption "" output_fn
805 return (Just Ln, maybe_loc, output_fn)
808 runPhase SplitAs basename _suff _input_fn get_output_fn maybe_loc
809 = do as_opts <- getOpts opt_a
811 (split_s_prefix, n) <- readIORef v_Split_info
813 odir <- readIORef v_Output_dir
814 let real_odir = case odir of
815 Nothing -> basename ++ "_split"
819 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
820 let output_o = replaceFilenameDirectory
821 (basename ++ "__" ++ show n ++ ".o")
823 real_o <- osuf_ify output_o
824 SysTools.runAs (map SysTools.Option as_opts ++
825 [ SysTools.Option "-c"
826 , SysTools.Option "-o"
827 , SysTools.FileOption "" real_o
828 , SysTools.FileOption "" input_s
831 mapM_ assemble_file [1..n]
833 output_fn <- get_output_fn Ln maybe_loc
834 return (Just Ln, maybe_loc, output_fn)
837 -----------------------------------------------------------------------------
839 -- Run ilx2il over the ILX output, getting an IL file
841 runPhase Ilx2Il _basename _suff input_fn get_output_fn maybe_loc
842 = do ilx2il_opts <- getOpts opt_I
843 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
844 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
845 SysTools.Option "mscorlib",
846 SysTools.Option "-o",
847 SysTools.FileOption "" output_fn,
848 SysTools.FileOption "" input_fn ])
851 -----------------------------------------------------------------------------
853 -- Run ilasm over the IL, getting a DLL
855 runPhase Ilasm _basename _suff input_fn get_output_fn maybe_loc
856 = do ilasm_opts <- getOpts opt_i
857 SysTools.runIlasm (map SysTools.Option ilasm_opts
858 ++ [ SysTools.Option "/QUIET",
859 SysTools.Option "/DLL",
860 SysTools.FileOption "/OUT=" output_fn,
861 SysTools.FileOption "" input_fn ])
866 -----------------------------------------------------------------------------
867 -- MoveBinary sort-of-phase
868 -- After having produced a binary, move it somewhere else and generate a
869 -- wrapper script calling the binary. Currently, we need this only in
870 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
871 -- central directory.
872 -- This is called from staticLink below, after linking. I haven't made it
873 -- a separate phase to minimise interfering with other modules, and
874 -- we don't need the generality of a phase (MoveBinary is always
875 -- done after linking and makes only sense in a parallel setup) -- HWL
877 runPhase_MoveBinary input_fn
880 pvm_root <- getEnv "PVM_ROOT"
881 pvm_arch <- getEnv "PVM_ARCH"
883 pvm_executable_base = "=" ++ input_fn
884 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
885 -- nuke old binary; maybe use configur'ed names for cp and rm?
886 system ("rm -f " ++ pvm_executable)
887 -- move the newly created binary into PVM land
888 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
889 -- generate a wrapper script for running a parallel prg under PVM
890 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
893 -- generates a Perl skript starting a parallel prg under PVM
894 mk_pvm_wrapper_script :: String -> String -> String -> String
895 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
897 "eval 'exec perl -S $0 ${1+\"$@\"}'",
898 " if $running_under_some_shell;",
899 "# =!=!=!=!=!=!=!=!=!=!=!",
900 "# This script is automatically generated: DO NOT EDIT!!!",
901 "# Generated by Glasgow Haskell Compiler",
902 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
904 "$pvm_executable = '" ++ pvm_executable ++ "';",
905 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
906 "$SysMan = '" ++ sysMan ++ "';",
908 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
909 "# first, some magical shortcuts to run "commands" on the binary",
910 "# (which is hidden)",
911 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
912 " local($cmd) = $1;",
913 " system("$cmd $pvm_executable");",
914 " exit(0); # all done",
917 "# Now, run the real binary; process the args first",
918 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
920 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
921 "@nonPVM_args = ();",
924 "args: while ($a = shift(@ARGV)) {",
925 " if ( $a eq '+RTS' ) {",
926 " $in_RTS_args = 1;",
927 " } elsif ( $a eq '-RTS' ) {",
928 " $in_RTS_args = 0;",
930 " if ( $a eq '-d' && $in_RTS_args ) {",
932 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
933 " $nprocessors = $1;",
934 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
935 " $nprocessors = $1;",
937 " push(@nonPVM_args, $a);",
941 "local($return_val) = 0;",
942 "# Start the parallel execution by calling SysMan",
943 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
945 "# ToDo: fix race condition moving files and flushing them!!",
946 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
950 -----------------------------------------------------------------------------
951 -- Complain about non-dynamic flags in OPTIONS pragmas
953 checkProcessArgsResult flags basename suff
954 = do when (notNull flags) (throwDyn (ProgramError (
955 showSDoc (hang (text basename <> text ('.':suff) <> char ':')
956 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
957 hsep (map text flags)))
960 -----------------------------------------------------------------------------
961 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
963 getHCFilePackages :: FilePath -> IO [PackageName]
964 getHCFilePackages filename =
965 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
968 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
969 return (map mkPackageName (words rest))
973 -----------------------------------------------------------------------------
974 -- Static linking, of .o files
976 -- The list of packages passed to link is the list of packages on
977 -- which this program depends, as discovered by the compilation
978 -- manager. It is combined with the list of packages that the user
979 -- specifies on the command line with -package flags.
981 -- In one-shot linking mode, we can't discover the package
982 -- dependencies (because we haven't actually done any compilation or
983 -- read any interface files), so the user must explicitly specify all
986 staticLink :: [FilePath] -> [PackageName] -> IO ()
987 staticLink o_files dep_packages = do
989 static <- readIORef v_Static
990 no_hs_main <- readIORef v_NoHsMain
992 -- get the full list of packages to link with, by combining the
993 -- explicit packages with the auto packages and all of their
994 -- dependencies, and eliminating duplicates.
996 o_file <- readIORef v_Output_file
997 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
999 pkg_lib_paths <- getPackageLibraryPath dep_packages
1000 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1002 lib_paths <- readIORef v_Library_paths
1003 let lib_path_opts = map ("-L"++) lib_paths
1005 pkg_link_opts <- getPackageLinkOpts dep_packages
1007 #ifdef darwin_TARGET_OS
1008 pkg_framework_paths <- getPackageFrameworkPath dep_packages
1009 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1011 framework_paths <- readIORef v_Framework_paths
1012 let framework_path_opts = map ("-F"++) framework_paths
1014 pkg_frameworks <- getPackageFrameworks dep_packages
1015 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1017 frameworks <- readIORef v_Cmdline_frameworks
1018 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1019 -- reverse because they're added in reverse order from the cmd line
1022 -- probably _stub.o files
1023 extra_ld_inputs <- readIORef v_Ld_inputs
1025 -- opts from -optl-<blah> (including -l<blah> options)
1026 extra_ld_opts <- getStaticOpts v_Opt_l
1028 [rts_pkg, std_pkg] <- getPackageDetails [rtsPackage, basePackage]
1030 let extra_os = if static || no_hs_main
1032 else [ head (library_dirs rts_pkg) ++ "/Main.dll_o",
1033 head (library_dirs std_pkg) ++ "/PrelMain.dll_o" ]
1035 (md_c_flags, _) <- machdepCCOpts
1036 SysTools.runLink ( [ SysTools.Option verb
1037 , SysTools.Option "-o"
1038 , SysTools.FileOption "" output_fn
1040 ++ map SysTools.Option (
1047 #ifdef darwin_TARGET_OS
1048 ++ framework_path_opts
1051 ++ pkg_lib_path_opts
1053 #ifdef darwin_TARGET_OS
1054 ++ pkg_framework_path_opts
1055 ++ pkg_framework_opts
1059 -- parallel only: move binary to another dir -- HWL
1060 ways_ <- readIORef v_Ways
1061 when (WayPar `elem` ways_)
1062 (do success <- runPhase_MoveBinary output_fn
1063 if success then return ()
1064 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1066 -----------------------------------------------------------------------------
1067 -- Making a DLL (only for Win32)
1069 doMkDLL :: [String] -> [PackageName] -> IO ()
1070 doMkDLL o_files dep_packages = do
1072 static <- readIORef v_Static
1073 no_hs_main <- readIORef v_NoHsMain
1075 o_file <- readIORef v_Output_file
1076 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1078 pkg_lib_paths <- getPackageLibraryPath dep_packages
1079 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1081 lib_paths <- readIORef v_Library_paths
1082 let lib_path_opts = map ("-L"++) lib_paths
1084 pkg_link_opts <- getPackageLinkOpts dep_packages
1086 -- probably _stub.o files
1087 extra_ld_inputs <- readIORef v_Ld_inputs
1089 -- opts from -optdll-<blah>
1090 extra_ld_opts <- getStaticOpts v_Opt_dll
1092 [rts_pkg, std_pkg] <- getPackageDetails [rtsPackage, basePackage]
1094 let extra_os = if static || no_hs_main
1096 else [ head (library_dirs rts_pkg) ++ "/Main.dll_o",
1097 head (library_dirs std_pkg) ++ "/PrelMain.dll_o" ]
1099 (md_c_flags, _) <- machdepCCOpts
1101 ([ SysTools.Option verb
1102 , SysTools.Option "-o"
1103 , SysTools.FileOption "" output_fn
1105 ++ map SysTools.Option (
1109 ++ [ "--target=i386-mingw32" ]
1113 ++ pkg_lib_path_opts
1115 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1117 else [ "--export-all" ])
1120 -- -----------------------------------------------------------------------------
1123 hscNextPhase :: HscLang -> IO Phase
1124 hscNextPhase hsc_lang = do
1125 split <- readIORef v_Split_object_files
1126 return (case hsc_lang of
1128 HscAsm | split -> SplitMangle
1130 HscNothing -> HCc -- dummy (no output will be generated)
1131 HscInterpreted -> HCc -- "" ""
1132 _other -> HCc -- "" ""
1135 hscMaybeAdjustLang :: HscLang -> IO HscLang
1136 hscMaybeAdjustLang current_hsc_lang = do
1137 todo <- readIORef v_GhcMode
1138 keep_hc <- readIORef v_Keep_hc_files
1140 -- don't change the lang if we're interpreting
1141 | current_hsc_lang == HscInterpreted = current_hsc_lang
1142 -- force -fvia-C if we are being asked for a .hc file
1143 | todo == StopBefore HCc || keep_hc = HscC
1144 -- force -fvia-C when profiling or ticky-ticky is on
1145 | opt_SccProfilingOn || opt_DoTickyProfiling = HscC
1146 -- otherwise, stick to the plan
1147 | otherwise = current_hsc_lang