1 -----------------------------------------------------------------------------
2 -- $Id: DriverPipeline.hs,v 1.96 2001/08/10 23:08:25 sof Exp $
6 -- (c) Simon Marlow 2000
8 -----------------------------------------------------------------------------
10 #include "../includes/config.h"
12 module DriverPipeline (
14 -- interfaces for the batch-mode driver
15 GhcMode(..), getGhcMode, v_GhcMode,
16 genPipeline, runPipeline, pipeLoop,
18 -- interfaces for the compilation manager (interpreted/batch-mode)
19 preprocess, compile, CompResult(..),
21 -- batch-mode linking interface
27 #include "HsVersions.h"
37 import SysTools ( newTempName, addFilesToClean, getSysMan, unDosifyPath )
38 import qualified SysTools
50 import Time ( getClockTime )
63 -----------------------------------------------------------------------------
64 -- GHC modes of operation
66 modeFlag :: String -> Maybe GhcMode
67 modeFlag "-M" = Just $ DoMkDependHS
68 modeFlag "--mk-dll" = Just $ DoMkDLL
69 modeFlag "-E" = Just $ StopBefore Hsc
70 modeFlag "-C" = Just $ StopBefore HCc
71 modeFlag "-S" = Just $ StopBefore As
72 modeFlag "-c" = Just $ StopBefore Ln
73 modeFlag "--make" = Just $ DoMake
74 modeFlag "--interactive" = Just $ DoInteractive
77 getGhcMode :: [String]
78 -> IO ( [String] -- rest of command line
80 , String -- "GhcMode" flag
83 = case my_partition modeFlag flags of
84 ([] , rest) -> return (rest, DoLink, "") -- default is to do linking
85 ([(flag,one)], rest) -> return (rest, one, flag)
88 "only one of the flags -M, -E, -C, -S, -c, --make, --interactive, -mk-dll is allowed")
90 -----------------------------------------------------------------------------
93 -- Herein is all the magic about which phases to run in which order, whether
94 -- the intermediate files should be in TMPDIR or in the current directory,
95 -- what the suffix of the intermediate files should be, etc.
97 -- The following compilation pipeline algorithm is fairly hacky. A
98 -- better way to do this would be to express the whole compilation as a
99 -- data flow DAG, where the nodes are the intermediate files and the
100 -- edges are the compilation phases. This framework would also work
101 -- nicely if a haskell dependency generator was included in the
104 -- It would also deal much more cleanly with compilation phases that
105 -- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
106 -- possibly stub files), where some of the output files need to be
107 -- processed further (eg. the stub files need to be compiled by the C
110 -- A cool thing to do would then be to execute the data flow graph
111 -- concurrently, automatically taking advantage of extra processors on
112 -- the host machine. For example, when compiling two Haskell files
113 -- where one depends on the other, the data flow graph would determine
114 -- that the C compiler from the first compilation can be overlapped
115 -- with the hsc compilation for the second file.
117 data IntermediateFileType
123 :: GhcMode -- when to stop
124 -> String -- "stop after" flag (for error messages)
125 -> Bool -- True => output is persistent
126 -> HscLang -- preferred output language for hsc
127 -> (FilePath, String) -- original filename & its suffix
128 -> IO [ -- list of phases to run for this file
130 IntermediateFileType, -- keep the output from this phase?
131 String) -- output file suffix
134 genPipeline todo stop_flag persistent_output lang (filename,suffix)
136 split <- readIORef v_Split_object_files
137 mangle <- readIORef v_Do_asm_mangling
138 keep_hc <- readIORef v_Keep_hc_files
139 keep_raw_s <- readIORef v_Keep_raw_s_files
140 keep_s <- readIORef v_Keep_s_files
141 osuf <- readIORef v_Object_suf
142 hcsuf <- readIORef v_HC_suf
145 ----------- ----- ---- --- -- -- - - -
146 start = startPhase suffix
148 -- special case for mkdependHS: .hspp files go through MkDependHS
149 start_phase | todo == DoMkDependHS && start == Hsc = MkDependHS
152 haskellish = haskellish_suffix suffix
153 cish = cish_suffix suffix
155 -- for a .hc file we need to force lang to HscC
156 real_lang | start_phase == HCc || start_phase == Mangle = HscC
160 ----------- ----- ---- --- -- -- - - -
162 | todo == DoMkDependHS = [ Unlit, Cpp, MkDependHS ]
166 HscC | split && mangle -> [ Unlit, Cpp, Hsc, HCc, Mangle,
167 SplitMangle, SplitAs ]
168 | mangle -> [ Unlit, Cpp, Hsc, HCc, Mangle, As ]
170 | otherwise -> [ Unlit, Cpp, Hsc, HCc, As ]
172 HscAsm | split -> [ Unlit, Cpp, Hsc, SplitMangle, SplitAs ]
173 | otherwise -> [ Unlit, Cpp, Hsc, As ]
175 HscJava | split -> not_valid
176 | otherwise -> error "not implemented: compiling via Java"
177 HscILX | split -> not_valid
178 | otherwise -> [ Unlit, Cpp, Hsc ]
182 | otherwise = [ ] -- just pass this file through to the linker
184 -- ToDo: this is somewhat cryptic
185 not_valid = throwDyn (UsageError ("invalid option combination"))
187 stop_phase = case todo of
188 StopBefore As | split -> SplitAs
189 StopBefore phase -> phase
192 ----------- ----- ---- --- -- -- - - -
194 -- this shouldn't happen.
195 if start_phase /= Ln && start_phase `notElem` pipeline
196 then throwDyn (CmdLineError ("can't find starting phase for "
200 -- if we can't find the phase we're supposed to stop before,
201 -- something has gone wrong. This test carefully avoids the
202 -- case where we aren't supposed to do any compilation, because the file
203 -- is already in linkable form (for example).
204 if start_phase `elem` pipeline &&
205 (stop_phase /= Ln && stop_phase `notElem` pipeline)
206 then throwDyn (UsageError
207 ("flag " ++ stop_flag
208 ++ " is incompatible with source file `" ++ filename ++ "'"))
212 -- .o and .hc suffixes can be overriden by command-line options:
213 myPhaseInputExt Ln | Just s <- osuf = s
214 myPhaseInputExt HCc | Just s <- hcsuf = s
215 myPhaseInputExt other = phaseInputExt other
218 :: [Phase] -- raw pipeline
219 -> Phase -- phase to stop before
220 -> [(Phase, IntermediateFileType, String{-file extension-})]
221 annotatePipeline [] _ = []
222 annotatePipeline (Ln:_) _ = []
223 annotatePipeline (phase:next_phase:ps) stop =
224 (phase, keep_this_output, myPhaseInputExt next_phase)
225 : annotatePipeline (next_phase:ps) stop
229 = if persistent_output then Persistent else Temporary
233 Mangle | keep_raw_s -> Persistent
234 As | keep_s -> Persistent
235 HCc | keep_hc -> Persistent
238 -- add information about output files to the pipeline
239 -- the suffix on an output file is determined by the next phase
240 -- in the pipeline, so we add linking to the end of the pipeline
241 -- to force the output from the final phase to be a .o file.
243 annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
245 phase_ne p (p1,_,_) = (p1 /= p)
246 ----------- ----- ---- --- -- -- - - -
249 takeWhile (phase_ne stop_phase ) $
250 dropWhile (phase_ne start_phase) $
256 :: [ (Phase, IntermediateFileType, String) ] -- phases to run
257 -> (String,String) -- input file
258 -> Bool -- doing linking afterward?
259 -> Bool -- take into account -o when generating output?
260 -> IO (String, String) -- return final filename
262 runPipeline pipeline (input_fn,suffix) do_linking use_ofile
263 = pipeLoop pipeline (input_fn,suffix) do_linking use_ofile basename suffix
264 where (basename, _) = splitFilename input_fn
266 pipeLoop [] input_fn _ _ _ _ = return input_fn
267 pipeLoop ((phase, keep, o_suffix):phases)
268 (input_fn,real_suff) do_linking use_ofile orig_basename orig_suffix
271 output_fn <- outputFileName (null phases) keep o_suffix
273 mbCarryOn <- run_phase phase orig_basename orig_suffix input_fn output_fn
274 -- sometimes we bail out early, eg. when the compiler's recompilation
275 -- checker has determined that recompilation isn't necessary.
278 let (_,keep,final_suffix) = last phases
279 ofile <- outputFileName True keep final_suffix
280 return (ofile, final_suffix)
284 Notice that in order to keep the invariant that we can
285 determine a compilation pipeline's 'start phase' just
286 by looking at the input filename, the input filename
287 to the next stage/phase is associated here with the suffix
288 of the output file, *even* if it does not have that
291 Why is this important? Because we may run a compilation
292 pipeline in stages (cf. Main.main.compileFile's two stages),
293 so when generating the next stage we need to be precise
294 about what kind of file (=> suffix) is given as input.
296 [Not having to generate a pipeline in stages seems like
297 the right way to go, but I've punted on this for now --sof]
300 pipeLoop phases (fn, o_suffix) do_linking use_ofile
301 orig_basename orig_suffix
303 outputFileName last_phase keep suffix
304 = do o_file <- readIORef v_Output_file
305 if last_phase && not do_linking && use_ofile && isJust o_file
308 Nothing -> error "outputFileName"
309 else if keep == Persistent
310 then odir_ify (orig_basename ++ '.':suffix)
311 else newTempName suffix
314 -> String -- basename of original input source
315 -> String -- its extension
316 -> FilePath -- name of file which contains the input to this phase.
317 -> FilePath -- where to stick the result.
318 -> IO (Maybe FilePath)
319 -- Nothing => stop the compilation pipeline
320 -- Just fn => the result of this phase can be found in 'fn'
321 -- (this can either be 'input_fn' or 'output_fn').
322 -------------------------------------------------------------------------------
325 run_phase Unlit _basename _suff input_fn output_fn
326 = do unlit_flags <- getOpts opt_L
327 -- The -h option passes the file name for unlit to put in a #line directive;
328 -- we undosify it so that it doesn't contain backslashes in Windows, which
329 -- would disappear in error messages
330 SysTools.runUnlit (map SysTools.Option unlit_flags ++
331 [ SysTools.Option "-h"
332 , SysTools.Option input_fn
333 , SysTools.FileOption input_fn
334 , SysTools.FileOption output_fn
336 return (Just output_fn)
338 -------------------------------------------------------------------------------
341 run_phase Cpp basename suff input_fn output_fn
342 = do src_opts <- getOptionsFromSource input_fn
343 unhandled_flags <- processArgs dynamic_flags src_opts []
344 checkProcessArgsResult unhandled_flags basename suff
346 do_cpp <- dynFlag cppFlag
348 -- no need to preprocess CPP, just pass input file along
349 -- to the next phase of the pipeline.
350 return (Just input_fn)
352 hscpp_opts <- getOpts opt_P
353 hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
355 cmdline_include_paths <- readIORef v_Include_paths
356 pkg_include_dirs <- getPackageIncludePath
357 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
358 (cmdline_include_paths ++ pkg_include_dirs)
361 (md_c_flags, _) <- machdepCCOpts
363 SysTools.runCpp ([SysTools.Option verb]
364 ++ map SysTools.Option include_paths
365 ++ map SysTools.Option hs_src_cpp_opts
366 ++ map SysTools.Option hscpp_opts
367 ++ map SysTools.Option md_c_flags
368 ++ [ SysTools.Option "-x c"
369 , SysTools.FileOption input_fn
370 , SysTools.Option "-o"
371 , SysTools.FileOption output_fn
373 return (Just output_fn)
375 -----------------------------------------------------------------------------
378 run_phase MkDependHS basename suff input_fn output_fn = do
379 src <- readFile input_fn
380 let (import_sources, import_normals, _) = getImports src
382 let orig_fn = basename ++ '.':suff
383 deps_sources <- mapM (findDependency True orig_fn) import_sources
384 deps_normals <- mapM (findDependency False orig_fn) import_normals
385 let deps = deps_sources ++ deps_normals
387 osuf_opt <- readIORef v_Object_suf
388 let osuf = case osuf_opt of
389 Nothing -> phaseInputExt Ln
392 extra_suffixes <- readIORef v_Dep_suffixes
393 let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
394 ofiles = map (\suf -> basename ++ '.':suf) suffixes
396 objs <- mapM odir_ify ofiles
398 -- Handle for file that accumulates dependencies
399 hdl <- readIORef v_Dep_tmp_hdl
401 -- std dependency of the object(s) on the source file
402 hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
404 let genDep (dep, False {- not an hi file -}) =
405 hPutStrLn hdl (unwords objs ++ " : " ++ dep)
406 genDep (dep, True {- is an hi file -}) = do
407 hisuf <- readIORef v_Hi_suf
408 let dep_base = remove_suffix '.' dep
409 deps = (dep_base ++ hisuf)
410 : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
411 -- length objs should be == length deps
412 sequence_ (zipWith (\o d -> hPutStrLn hdl (o ++ " : " ++ d)) objs deps)
414 mapM genDep [ d | Just d <- deps ]
416 return (Just output_fn)
418 -- add the lines to dep_makefile:
422 -- if the dependency is on something other than a .hi file:
423 -- this.o this.p_o ... : dep
425 -- if the import is {-# SOURCE #-}
426 -- this.o this.p_o ... : dep.hi-boot[-$vers]
429 -- this.o ... : dep.hi
430 -- this.p_o ... : dep.p_hi
433 -- (where .o is $osuf, and the other suffixes come from
434 -- the cmdline -s options).
436 -----------------------------------------------------------------------------
439 -- Compilation of a single module, in "legacy" mode (_not_ under
440 -- the direction of the compilation manager).
441 run_phase Hsc basename suff input_fn output_fn
444 -- we add the current directory (i.e. the directory in which
445 -- the .hs files resides) to the import path, since this is
446 -- what gcc does, and it's probably what you want.
447 let current_dir = getdir basename
449 paths <- readIORef v_Include_paths
450 writeIORef v_Include_paths (current_dir : paths)
452 -- figure out which header files to #include in a generated .hc file
453 c_includes <- getPackageCIncludes
454 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
456 let cc_injects = unlines (map mk_include
457 (c_includes ++ reverse cmdline_includes))
460 '"':_{-"-} -> "#include "++h_file
461 '<':_ -> "#include "++h_file
462 _ -> "#include \""++h_file++"\""
464 writeIORef v_HCHeader cc_injects
466 -- gather the imports and module name
467 (srcimps,imps,mod_name) <- getImportsFromFile input_fn
469 -- build a ModuleLocation to pass to hscMain.
471 <- mkHomeModuleLocn mod_name basename (Just (basename ++ '.':suff))
473 -- take -ohi into account if present
474 ohi <- readIORef v_Output_hi
475 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
476 | otherwise = location'
478 -- figure out if the source has changed, for recompilation avoidance.
479 -- only do this if we're eventually going to generate a .o file.
480 -- (ToDo: do when generating .hc files too?)
482 -- Setting source_unchanged to True means that M.o seems
483 -- to be up to date wrt M.hs; so no need to recompile unless imports have
484 -- changed (which the compiler itself figures out).
485 -- Setting source_unchanged to False tells the compiler that M.o is out of
486 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
487 do_recomp <- readIORef v_Recomp
488 todo <- readIORef v_GhcMode
489 expl_o_file <- readIORef v_Output_file
492 Nothing -> unJust "source_unchanged" (ml_obj_file location)
495 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
497 else do t1 <- getModificationTime (basename ++ '.':suff)
498 o_file_exists <- doesFileExist o_file
500 then return False -- Need to recompile
501 else do t2 <- getModificationTime o_file
507 dyn_flags <- getDynFlags
509 let dyn_flags' = dyn_flags { hscOutName = output_fn,
510 hscStubCOutName = basename ++ "_stub.c",
511 hscStubHOutName = basename ++ "_stub.h",
512 extCoreName = basename ++ ".core" }
515 pcs <- initPersistentCompilerState
516 result <- hscMain OneShot
518 location{ ml_hspp_file=Just input_fn }
522 emptyModuleEnv -- HomeSymbolTable
523 emptyModuleEnv -- HomeIfaceTable
528 HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
530 HscNoRecomp pcs details iface -> do { SysTools.touch "Touching object file" o_file
533 HscRecomp pcs details iface stub_h_exists stub_c_exists
534 _maybe_interpreted_code -> do
537 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
540 Just stub_o -> add v_Ld_inputs stub_o
542 return (Just output_fn)
545 -----------------------------------------------------------------------------
548 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
549 -- way too many hacks, and I can't say I've ever used it anyway.
551 run_phase cc_phase basename suff input_fn output_fn
552 | cc_phase == Cc || cc_phase == HCc
553 = do cc_opts <- getOpts opt_c
554 cmdline_include_paths <- readIORef v_Include_paths
556 let hcc = cc_phase == HCc
558 -- add package include paths even if we're just compiling
559 -- .c files; this is the Value Add(TM) that using
560 -- ghc instead of gcc gives you :)
561 pkg_include_dirs <- getPackageIncludePath
562 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
563 (cmdline_include_paths ++ pkg_include_dirs)
565 mangle <- readIORef v_Do_asm_mangling
566 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
570 o2 <- readIORef v_minus_o2_for_C
571 let opt_flag | o2 = "-O2"
574 pkg_extra_cc_opts <- getPackageExtraCcOpts
576 split_objs <- readIORef v_Split_object_files
577 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
580 excessPrecision <- readIORef v_Excess_precision
581 SysTools.runCc ([ SysTools.Option "-x c"
582 , SysTools.FileOption input_fn
583 , SysTools.Option "-o"
584 , SysTools.FileOption output_fn
586 ++ map SysTools.Option (
588 ++ (if cc_phase == HCc && mangle
591 ++ [ verb, "-S", "-Wimplicit", opt_flag ]
592 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
595 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
599 return (Just output_fn)
601 -- ToDo: postprocess the output from gcc
603 -----------------------------------------------------------------------------
606 run_phase Mangle _basename _suff input_fn output_fn
607 = do mangler_opts <- getOpts opt_m
608 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
609 then do n_regs <- dynFlag stolen_x86_regs
610 return [ show n_regs ]
613 SysTools.runMangle (map SysTools.Option mangler_opts
614 ++ [ SysTools.FileOption input_fn
615 , SysTools.FileOption output_fn
617 ++ map SysTools.Option machdep_opts)
618 return (Just output_fn)
620 -----------------------------------------------------------------------------
623 run_phase SplitMangle _basename _suff input_fn output_fn
624 = do -- tmp_pfx is the prefix used for the split .s files
625 -- We also use it as the file to contain the no. of split .s files (sigh)
626 split_s_prefix <- SysTools.newTempName "split"
627 let n_files_fn = split_s_prefix
629 SysTools.runSplit [ SysTools.FileOption input_fn
630 , SysTools.FileOption split_s_prefix
631 , SysTools.FileOption n_files_fn
634 -- Save the number of split files for future references
635 s <- readFile n_files_fn
636 let n_files = read s :: Int
637 writeIORef v_Split_info (split_s_prefix, n_files)
639 -- Remember to delete all these files
640 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
643 return (Just output_fn)
645 -----------------------------------------------------------------------------
648 run_phase As _basename _suff input_fn output_fn
649 = do as_opts <- getOpts opt_a
650 cmdline_include_paths <- readIORef v_Include_paths
652 SysTools.runAs (map SysTools.Option as_opts
653 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
654 ++ [ SysTools.Option "-c"
655 , SysTools.FileOption input_fn
656 , SysTools.Option "-o"
657 , SysTools.FileOption output_fn
659 return (Just output_fn)
661 run_phase SplitAs basename _suff _input_fn output_fn
662 = do as_opts <- getOpts opt_a
664 (split_s_prefix, n) <- readIORef v_Split_info
666 odir <- readIORef v_Output_dir
667 let real_odir = case odir of
672 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
673 let output_o = newdir real_odir
674 (basename ++ "__" ++ show n ++ ".o")
675 real_o <- osuf_ify output_o
676 SysTools.runAs (map SysTools.Option as_opts ++
677 [ SysTools.Option "-c"
678 , SysTools.Option "-o"
679 , SysTools.FileOption real_o
680 , SysTools.FileOption input_s
683 mapM_ assemble_file [1..n]
684 return (Just output_fn)
686 -----------------------------------------------------------------------------
687 -- MoveBinary sort-of-phase
688 -- After having produced a binary, move it somewhere else and generate a
689 -- wrapper script calling the binary. Currently, we need this only in
690 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
691 -- central directory.
692 -- This is called from doLink below, after linking. I haven't made it
693 -- a separate phase to minimise interfering with other modules, and
694 -- we don't need the generality of a phase (MoveBinary is always
695 -- done after linking and makes only sense in a parallel setup) -- HWL
697 run_phase_MoveBinary input_fn
700 pvm_root <- getEnv "PVM_ROOT"
701 pvm_arch <- getEnv "PVM_ARCH"
703 pvm_executable_base = "=" ++ input_fn
704 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
705 -- nuke old binary; maybe use configur'ed names for cp and rm?
706 system ("rm -f " ++ pvm_executable)
707 -- move the newly created binary into PVM land
708 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
709 -- generate a wrapper script for running a parallel prg under PVM
710 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
713 -- generates a Perl skript starting a parallel prg under PVM
714 mk_pvm_wrapper_script :: String -> String -> String -> String
715 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
717 "eval 'exec perl -S $0 ${1+\"$@\"}'",
718 " if $running_under_some_shell;",
719 "# =!=!=!=!=!=!=!=!=!=!=!",
720 "# This script is automatically generated: DO NOT EDIT!!!",
721 "# Generated by Glasgow Haskell Compiler",
722 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
724 "$pvm_executable = '" ++ pvm_executable ++ "';",
725 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
726 "$SysMan = '" ++ sysMan ++ "';",
728 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
729 "# first, some magical shortcuts to run "commands" on the binary",
730 "# (which is hidden)",
731 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
732 " local($cmd) = $1;",
733 " system("$cmd $pvm_executable");",
734 " exit(0); # all done",
737 "# Now, run the real binary; process the args first",
738 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
740 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
741 "@nonPVM_args = ();",
744 "args: while ($a = shift(@ARGV)) {",
745 " if ( $a eq '+RTS' ) {",
746 " $in_RTS_args = 1;",
747 " } elsif ( $a eq '-RTS' ) {",
748 " $in_RTS_args = 0;",
750 " if ( $a eq '-d' && $in_RTS_args ) {",
752 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
753 " $nprocessors = $1;",
754 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
755 " $nprocessors = $1;",
757 " push(@nonPVM_args, $a);",
761 "local($return_val) = 0;",
762 "# Start the parallel execution by calling SysMan",
763 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
765 "# ToDo: fix race condition moving files and flushing them!!",
766 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
770 -----------------------------------------------------------------------------
771 -- Complain about non-dynamic flags in OPTIONS pragmas
773 checkProcessArgsResult flags basename suff
774 = do when (not (null flags)) (throwDyn (ProgramError (
775 basename ++ "." ++ suff
776 ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t"
777 ++ unwords flags)) (ExitFailure 1))
779 -----------------------------------------------------------------------------
782 doLink :: [String] -> IO ()
785 static <- readIORef v_Static
786 no_hs_main <- readIORef v_NoHsMain
788 o_file <- readIORef v_Output_file
789 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
791 pkg_lib_paths <- getPackageLibraryPath
792 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
794 lib_paths <- readIORef v_Library_paths
795 let lib_path_opts = map ("-L"++) lib_paths
797 pkg_libs <- getPackageLibraries
798 let imp = if static then "" else "_imp"
799 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
801 libs <- readIORef v_Cmdline_libraries
802 let lib_opts = map ("-l"++) (reverse libs)
803 -- reverse because they're added in reverse order from the cmd line
805 pkg_extra_ld_opts <- getPackageExtraLdOpts
807 -- probably _stub.o files
808 extra_ld_inputs <- readIORef v_Ld_inputs
810 -- opts from -optl-<blah>
811 extra_ld_opts <- getStaticOpts v_Opt_l
813 rts_pkg <- getPackageDetails ["rts"]
814 std_pkg <- getPackageDetails ["std"]
815 let extra_os = if static || no_hs_main
817 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
818 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
820 (md_c_flags, _) <- machdepCCOpts
821 SysTools.runLink ( [ SysTools.Option verb
822 , SysTools.Option "-o"
823 , SysTools.FileOption output_fn
825 ++ map SysTools.Option (
836 ++ if static && not no_hs_main then
837 #ifdef LEADING_UNDERSCORE
838 [ "-u", "_PrelMain_mainIO_closure" ,
839 "-u", "___init_PrelMain"]
841 [ "-u", prefixUnderscore "PrelMain_mainIO_closure" ,
842 "-u", prefixUnderscore "__init_PrelMain"]
846 -- parallel only: move binary to another dir -- HWL
847 ways_ <- readIORef v_Ways
848 when (WayPar `elem` ways_)
849 (do success <- run_phase_MoveBinary output_fn
850 if success then return ()
851 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
853 -----------------------------------------------------------------------------
854 -- Making a DLL (only for Win32)
856 doMkDLL :: [String] -> IO ()
859 static <- readIORef v_Static
860 no_hs_main <- readIORef v_NoHsMain
862 o_file <- readIORef v_Output_file
863 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
865 pkg_lib_paths <- getPackageLibraryPath
866 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
868 lib_paths <- readIORef v_Library_paths
869 let lib_path_opts = map ("-L"++) lib_paths
871 pkg_libs <- getPackageLibraries
872 let imp = if static then "" else "_imp"
873 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
875 libs <- readIORef v_Cmdline_libraries
876 let lib_opts = map ("-l"++) (reverse libs)
877 -- reverse because they're added in reverse order from the cmd line
879 pkg_extra_ld_opts <- getPackageExtraLdOpts
881 -- probably _stub.o files
882 extra_ld_inputs <- readIORef v_Ld_inputs
884 -- opts from -optdll-<blah>
885 extra_ld_opts <- getStaticOpts v_Opt_dll
887 rts_pkg <- getPackageDetails ["rts"]
888 std_pkg <- getPackageDetails ["std"]
890 let extra_os = if static || no_hs_main
892 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
893 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
895 (md_c_flags, _) <- machdepCCOpts
897 ([ SysTools.Option verb
898 , SysTools.Option "-o"
899 , SysTools.FileOption output_fn
901 ++ map SysTools.Option (
905 ++ [ "--target=i386-mingw32" ]
912 ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
913 Nothing -> [ "--export-all" ]
918 -----------------------------------------------------------------------------
919 -- Just preprocess a file, put the result in a temp. file (used by the
920 -- compilation manager during the summary phase).
922 preprocess :: FilePath -> IO FilePath
923 preprocess filename =
924 ASSERT(haskellish_src_file filename)
925 do restoreDynFlags -- Restore to state of last save
926 pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False
927 defaultHscLang (filename, getFileSuffix filename)
928 (fn,_) <- runPipeline pipeline (filename,getFileSuffix filename)
929 False{-no linking-} False{-no -o flag-}
932 -----------------------------------------------------------------------------
933 -- Compile a single module, under the control of the compilation manager.
935 -- This is the interface between the compilation manager and the
936 -- compiler proper (hsc), where we deal with tedious details like
937 -- reading the OPTIONS pragma from the source file, and passing the
938 -- output of hsc through the C compiler.
940 -- The driver sits between 'compile' and 'hscMain', translating calls
941 -- to the former into calls to the latter, and results from the latter
942 -- into results from the former. It does things like preprocessing
943 -- the .hs file if necessary, and compiling up the .stub_c files to
944 -- generate Linkables.
946 -- NB. No old interface can also mean that the source has changed.
948 compile :: GhciMode -- distinguish batch from interactive
949 -> ModSummary -- summary, including source
950 -> Bool -- True <=> source unchanged
951 -> Bool -- True <=> have object
952 -> Maybe ModIface -- old interface, if available
953 -> HomeSymbolTable -- for home module ModDetails
954 -> HomeIfaceTable -- for home module Ifaces
955 -> PersistentCompilerState -- persistent compiler state
959 = CompOK PersistentCompilerState -- updated PCS
960 ModDetails -- new details (HST additions)
961 ModIface -- new iface (HIT additions)
963 -- new code; Nothing => compilation was not reqd
964 -- (old code is still valid)
966 | CompErrs PersistentCompilerState -- updated PCS
969 compile ghci_mode summary source_unchanged have_object
970 old_iface hst hit pcs = do
971 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
975 (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
977 let verb = verbosity dyn_flags
978 let location = ms_location summary
979 let input_fn = unJust "compile:hs" (ml_hs_file location)
980 let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
982 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
984 opts <- getOptionsFromSource input_fnpp
985 processArgs dynamic_flags opts []
986 dyn_flags <- getDynFlags
988 let hsc_lang = hscLang dyn_flags
989 (basename, _) = splitFilename input_fn
991 keep_hc <- readIORef v_Keep_hc_files
992 keep_s <- readIORef v_Keep_s_files
996 HscAsm | keep_s -> return (basename ++ '.':phaseInputExt As)
997 | otherwise -> newTempName (phaseInputExt As)
998 HscC | keep_hc -> return (basename ++ '.':phaseInputExt HCc)
999 | otherwise -> newTempName (phaseInputExt HCc)
1000 HscJava -> newTempName "java" -- ToDo
1001 HscILX -> return (basename ++ ".ilx")
1002 -- newTempName "ilx" -- ToDo
1003 HscInterpreted -> return (error "no output file")
1005 let dyn_flags' = dyn_flags { hscOutName = output_fn,
1006 hscStubCOutName = basename ++ "_stub.c",
1007 hscStubHOutName = basename ++ "_stub.h",
1008 extCoreName = basename ++ ".core" }
1010 -- figure out which header files to #include in a generated .hc file
1011 c_includes <- getPackageCIncludes
1012 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
1014 let cc_injects = unlines (map mk_include
1015 (c_includes ++ reverse cmdline_includes))
1018 '"':_{-"-} -> "#include "++h_file
1019 '<':_ -> "#include "++h_file
1020 _ -> "#include \""++h_file++"\""
1022 writeIORef v_HCHeader cc_injects
1025 hsc_result <- hscMain ghci_mode dyn_flags'
1026 (ms_mod summary) location
1027 source_unchanged have_object old_iface hst hit pcs
1030 HscFail pcs -> return (CompErrs pcs)
1032 HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
1034 HscRecomp pcs details iface
1035 stub_h_exists stub_c_exists maybe_interpreted_code -> do
1038 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
1039 let stub_unlinked = case maybe_stub_o of
1041 Just stub_o -> [ DotO stub_o ]
1043 (hs_unlinked, unlinked_time) <-
1046 -- in interpreted mode, just return the compiled code
1047 -- as our "unlinked" object.
1049 case maybe_interpreted_code of
1051 Just (bcos,itbl_env) -> do tm <- getClockTime
1052 return ([BCOs bcos itbl_env], tm)
1054 Nothing -> panic "compile: no interpreted code"
1056 -- we're in batch mode: finish the compilation pipeline.
1057 _other -> do pipe <- genPipeline (StopBefore Ln) "" True
1058 hsc_lang (output_fn, getFileSuffix output_fn)
1059 -- runPipeline takes input_fn so it can split off
1060 -- the base name and use it as the base of
1061 -- the output object file.
1062 let (basename, suffix) = splitFilename input_fn
1064 pipeLoop pipe (output_fn, getFileSuffix output_fn)
1067 o_time <- getModificationTime o_file
1068 return ([DotO o_file], o_time)
1070 let linkable = LM unlinked_time (moduleName (ms_mod summary))
1071 (hs_unlinked ++ stub_unlinked)
1073 return (CompOK pcs details iface (Just linkable))
1076 -----------------------------------------------------------------------------
1077 -- stub .h and .c files (for foreign export support)
1079 compileStub dflags stub_c_exists
1080 | not stub_c_exists = return Nothing
1081 | stub_c_exists = do
1082 -- compile the _stub.c file w/ gcc
1083 let stub_c = hscStubCOutName dflags
1084 pipeline <- genPipeline (StopBefore Ln) "" True defaultHscLang (stub_c,"c")
1085 (stub_o,_) <- runPipeline pipeline (stub_c,"c") False{-no linking-}
1086 False{-no -o option-}
1087 return (Just stub_o)