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 genPipeline, runPipeline, pipeLoop,
16 -- interfaces for the compilation manager (interpreted/batch-mode)
17 preprocess, compile, CompResult(..),
19 -- batch-mode linking interface
25 #include "HsVersions.h"
35 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
36 import qualified SysTools
48 import Time ( getClockTime )
61 -----------------------------------------------------------------------------
64 -- Herein is all the magic about which phases to run in which order, whether
65 -- the intermediate files should be in TMPDIR or in the current directory,
66 -- what the suffix of the intermediate files should be, etc.
68 -- The following compilation pipeline algorithm is fairly hacky. A
69 -- better way to do this would be to express the whole compilation as a
70 -- data flow DAG, where the nodes are the intermediate files and the
71 -- edges are the compilation phases. This framework would also work
72 -- nicely if a haskell dependency generator was included in the
75 -- It would also deal much more cleanly with compilation phases that
76 -- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
77 -- possibly stub files), where some of the output files need to be
78 -- processed further (eg. the stub files need to be compiled by the C
81 -- A cool thing to do would then be to execute the data flow graph
82 -- concurrently, automatically taking advantage of extra processors on
83 -- the host machine. For example, when compiling two Haskell files
84 -- where one depends on the other, the data flow graph would determine
85 -- that the C compiler from the first compilation can be overlapped
86 -- with the hsc compilation for the second file.
88 data IntermediateFileType
94 :: GhcMode -- when to stop
95 -> String -- "stop after" flag (for error messages)
96 -> Bool -- True => output is persistent
97 -> HscLang -- preferred output language for hsc
98 -> (FilePath, String) -- original filename & its suffix
99 -> IO [ -- list of phases to run for this file
101 IntermediateFileType, -- keep the output from this phase?
102 String) -- output file suffix
105 genPipeline todo stop_flag persistent_output lang (filename,suffix)
107 split <- readIORef v_Split_object_files
108 mangle <- readIORef v_Do_asm_mangling
109 keep_hc <- readIORef v_Keep_hc_files
111 keep_il <- readIORef v_Keep_il_files
112 keep_ilx <- readIORef v_Keep_ilx_files
114 keep_raw_s <- readIORef v_Keep_raw_s_files
115 keep_s <- readIORef v_Keep_s_files
116 osuf <- readIORef v_Object_suf
117 hcsuf <- readIORef v_HC_suf
120 ----------- ----- ---- --- -- -- - - -
121 start = startPhase suffix
123 -- special case for mkdependHS: .hspp files go through MkDependHS
124 start_phase | todo == DoMkDependHS && start == Hsc = MkDependHS
127 haskellish = haskellish_suffix suffix
128 cish = cish_suffix suffix
130 -- for a .hc file we need to force lang to HscC
131 real_lang | start_phase == HCc || start_phase == Mangle = HscC
135 ----------- ----- ---- --- -- -- - - -
136 pipeline = preprocess ++ compile
139 | haskellish = [ Unlit, Cpp, HsPp ]
143 | todo == DoMkDependHS = [ MkDependHS ]
149 HscC | split && mangle -> [ Hsc, HCc, Mangle, SplitMangle, SplitAs ]
150 | mangle -> [ Hsc, HCc, Mangle, As ]
152 | otherwise -> [ Hsc, HCc, As ]
154 HscAsm | split -> [ Hsc, SplitMangle, SplitAs ]
155 | otherwise -> [ Hsc, As ]
157 HscJava | split -> not_valid
158 | otherwise -> error "not implemented: compiling via Java"
160 HscILX | split -> not_valid
161 | otherwise -> [ Hsc, Ilx2Il, Ilasm ]
163 HscNothing -> [ Hsc, HCc ] -- HCc is a dummy stop phase
165 | otherwise = [ ] -- just pass this file through to the linker
167 -- ToDo: this is somewhat cryptic
168 not_valid = throwDyn (UsageError ("invalid option combination"))
170 stop_phase = case todo of
171 StopBefore As | split -> SplitAs
173 | real_lang == HscILX -> Ilasm
175 StopBefore phase -> phase
179 ----------- ----- ---- --- -- -- - - -
181 -- this shouldn't happen.
182 when (start_phase /= Ln && start_phase `notElem` pipeline)
183 (throwDyn (CmdLineError ("can't find starting phase for "
185 -- if we can't find the phase we're supposed to stop before,
186 -- something has gone wrong. This test carefully avoids the
187 -- case where we aren't supposed to do any compilation, because the file
188 -- is already in linkable form (for example).
189 when (start_phase `elem` pipeline &&
190 (stop_phase /= Ln && stop_phase `notElem` pipeline))
191 (throwDyn (UsageError
192 ("flag `" ++ stop_flag
193 ++ "' is incompatible with source file `"
194 ++ filename ++ "'" ++ show pipeline ++ show stop_phase)))
196 -- .o and .hc suffixes can be overriden by command-line options:
197 myPhaseInputExt Ln | Just s <- osuf = s
198 myPhaseInputExt HCc | Just s <- hcsuf = s
199 myPhaseInputExt other = phaseInputExt other
202 :: [Phase] -- raw pipeline
203 -> Phase -- phase to stop before
204 -> [(Phase, IntermediateFileType, String{-file extension-})]
205 annotatePipeline [] _ = []
206 annotatePipeline (Ln:_) _ = []
207 annotatePipeline (phase:next_phase:ps) stop =
208 (phase, keep_this_output, myPhaseInputExt next_phase)
209 : annotatePipeline (next_phase:ps) stop
213 = if persistent_output then Persistent else Temporary
217 Mangle | keep_raw_s -> Persistent
218 As | keep_s -> Persistent
219 HCc | keep_hc -> Persistent
221 Ilx2Il | keep_ilx -> Persistent
222 Ilasm | keep_il -> Persistent
226 -- add information about output files to the pipeline
227 -- the suffix on an output file is determined by the next phase
228 -- in the pipeline, so we add linking to the end of the pipeline
229 -- to force the output from the final phase to be a .o file.
231 annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
233 phase_ne p (p1,_,_) = (p1 /= p)
234 ----------- ----- ---- --- -- -- - - -
237 takeWhile (phase_ne stop_phase ) $
238 dropWhile (phase_ne start_phase) $
244 :: [ (Phase, IntermediateFileType, String) ] -- phases to run
245 -> (String,String) -- input file
246 -> Bool -- doing linking afterward?
247 -> Bool -- take into account -o when generating output?
248 -> IO (String, String) -- return final filename
250 runPipeline pipeline (input_fn,suffix) do_linking use_ofile
251 = pipeLoop pipeline (input_fn,suffix) do_linking use_ofile basename suffix
252 where (basename, _) = splitFilename input_fn
254 pipeLoop [] input_fn _ _ _ _ = return input_fn
255 pipeLoop (all_phases@((phase, keep, o_suffix):phases))
256 (input_fn,real_suff) do_linking use_ofile orig_basename orig_suffix
259 output_fn <- outputFileName (null phases) keep o_suffix
261 mbCarryOn <- run_phase phase orig_basename orig_suffix
263 -- sometimes we bail out early, eg. when the compiler's recompilation
264 -- checker has determined that recompilation isn't necessary.
267 let (_,keep,final_suffix) = last all_phases
268 ofile <- outputFileName True keep final_suffix
269 return (ofile, final_suffix)
273 Check to see whether we've reached the end of the
274 pipeline, but did so with an ineffective last stage.
275 (i.e., it returned the input_fn as the output filename).
277 If we did and the output is persistent, copy the contents
278 of input_fn into the file where the pipeline's output is
281 atEnd <- finalStage (null phases)
282 when (atEnd && fn == input_fn)
283 (copy "Saving away compilation pipeline's output"
287 Notice that in order to keep the invariant that we can
288 determine a compilation pipeline's 'start phase' just
289 by looking at the input filename, the input filename
290 to the next stage/phase is associated here with the suffix
291 of the output file, *even* if it does not have that
294 Why is this important? Because we may run a compilation
295 pipeline in stages (cf. Main.main.compileFile's two stages),
296 so when generating the next stage we need to be precise
297 about what kind of file (=> suffix) is given as input.
299 [Not having to generate a pipeline in stages seems like
300 the right way to go, but I've punted on this for now --sof]
303 pipeLoop phases (fn, o_suffix) do_linking use_ofile
304 orig_basename orig_suffix
306 finalStage lastPhase = do
307 o_file <- readIORef v_Output_file
308 return (lastPhase && not do_linking && use_ofile && isJust o_file)
310 outputFileName last_phase keep suffix
311 = do o_file <- readIORef v_Output_file
312 atEnd <- finalStage last_phase
316 Nothing -> error "outputFileName"
317 else if keep == Persistent
318 then odir_ify (orig_basename ++ '.':suffix)
319 else newTempName suffix
322 -> String -- basename of original input source
323 -> String -- its extension
324 -> FilePath -- name of file which contains the input to this phase.
325 -> FilePath -- where to stick the result.
326 -> IO (Maybe FilePath)
327 -- Nothing => stop the compilation pipeline
328 -- Just fn => the result of this phase can be found in 'fn'
329 -- (this can either be 'input_fn' or 'output_fn').
330 -------------------------------------------------------------------------------
333 run_phase Unlit _basename _suff input_fn output_fn
334 = do unlit_flags <- getOpts opt_L
335 -- The -h option passes the file name for unlit to put in a #line directive
336 SysTools.runUnlit (map SysTools.Option unlit_flags ++
337 [ SysTools.Option "-h"
338 , SysTools.Option input_fn
339 , SysTools.FileOption "" input_fn
340 , SysTools.FileOption "" output_fn
342 return (Just output_fn)
344 -------------------------------------------------------------------------------
347 run_phase Cpp basename suff input_fn output_fn
348 = do src_opts <- getOptionsFromSource input_fn
349 unhandled_flags <- processArgs dynamic_flags src_opts []
350 checkProcessArgsResult unhandled_flags basename suff
352 do_cpp <- dynFlag cppFlag
354 -- no need to preprocess CPP, just pass input file along
355 -- to the next phase of the pipeline.
356 return (Just input_fn)
358 hscpp_opts <- getOpts opt_P
359 hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
361 cmdline_include_paths <- readIORef v_Include_paths
362 pkg_include_dirs <- getPackageIncludePath
363 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
364 (cmdline_include_paths ++ pkg_include_dirs)
367 (md_c_flags, _) <- machdepCCOpts
369 SysTools.runCpp ([SysTools.Option verb]
370 ++ map SysTools.Option include_paths
371 ++ map SysTools.Option hs_src_cpp_opts
372 ++ map SysTools.Option hscpp_opts
373 ++ map SysTools.Option md_c_flags
374 ++ [ SysTools.Option "-x"
375 , SysTools.Option "c"
376 , SysTools.Option input_fn
377 -- We hackily use Option instead of FileOption here, so that the file
378 -- name is not back-slashed on Windows. cpp is capable of
379 -- dealing with / in filenames, so it works fine. Furthermore
380 -- if we put in backslashes, cpp outputs #line directives
381 -- with *double* backslashes. And that in turn means that
382 -- our error messages get double backslashes in them.
383 -- In due course we should arrange that the lexer deals
384 -- with these \\ escapes properly.
385 , SysTools.Option "-o"
386 , SysTools.FileOption "" output_fn
388 return (Just output_fn)
390 -------------------------------------------------------------------------------
392 run_phase HsPp basename suff input_fn output_fn
393 = do src_opts <- getOptionsFromSource input_fn
394 unhandled_flags <- processArgs dynamic_flags src_opts []
395 checkProcessArgsResult unhandled_flags basename suff
397 let orig_fn = basename ++ '.':suff
398 do_pp <- dynFlag ppFlag
400 -- no need to preprocess, just pass input file along
401 -- to the next phase of the pipeline.
402 return (Just input_fn)
404 hspp_opts <- getOpts opt_F
405 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
406 SysTools.runPp ( [ SysTools.Option orig_fn
407 , SysTools.Option input_fn
408 , SysTools.FileOption "" output_fn
410 map SysTools.Option hs_src_pp_opts ++
411 map SysTools.Option hspp_opts
413 return (Just output_fn)
415 -----------------------------------------------------------------------------
418 run_phase MkDependHS basename suff input_fn output_fn
419 = do src <- readFile input_fn
420 let (import_sources, import_normals, _) = getImports src
421 let orig_fn = basename ++ '.':suff
422 deps_sources <- mapM (findDependency True orig_fn) import_sources
423 deps_normals <- mapM (findDependency False orig_fn) import_normals
424 let deps = deps_sources ++ deps_normals
426 osuf_opt <- readIORef v_Object_suf
427 let osuf = case osuf_opt of
428 Nothing -> phaseInputExt Ln
431 extra_suffixes <- readIORef v_Dep_suffixes
432 let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
433 ofiles = map (\suf -> basename ++ '.':suf) suffixes
435 objs <- mapM odir_ify ofiles
437 -- Handle for file that accumulates dependencies
438 hdl <- readIORef v_Dep_tmp_hdl
440 -- std dependency of the object(s) on the source file
441 hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
443 let genDep (dep, False {- not an hi file -}) =
444 hPutStrLn hdl (unwords objs ++ " : " ++ dep)
445 genDep (dep, True {- is an hi file -}) = do
446 hisuf <- readIORef v_Hi_suf
447 let dep_base = remove_suffix '.' dep
448 deps = (dep_base ++ hisuf)
449 : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
450 -- length objs should be == length deps
451 sequence_ (zipWith (\o d -> hPutStrLn hdl (o ++ " : " ++ d)) objs deps)
453 sequence_ (map genDep [ d | Just d <- deps ])
454 return (Just output_fn)
456 -- add the lines to dep_makefile:
460 -- if the dependency is on something other than a .hi file:
461 -- this.o this.p_o ... : dep
463 -- if the import is {-# SOURCE #-}
464 -- this.o this.p_o ... : dep.hi-boot[-$vers]
467 -- this.o ... : dep.hi
468 -- this.p_o ... : dep.p_hi
471 -- (where .o is $osuf, and the other suffixes come from
472 -- the cmdline -s options).
474 -----------------------------------------------------------------------------
477 -- Compilation of a single module, in "legacy" mode (_not_ under
478 -- the direction of the compilation manager).
479 run_phase Hsc basename suff input_fn output_fn
482 -- we add the current directory (i.e. the directory in which
483 -- the .hs files resides) to the import path, since this is
484 -- what gcc does, and it's probably what you want.
485 let current_dir = getdir basename
487 paths <- readIORef v_Include_paths
488 writeIORef v_Include_paths (current_dir : paths)
490 -- figure out which header files to #include in a generated .hc file
491 c_includes <- getPackageCIncludes
492 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
494 let cc_injects = unlines (map mk_include
495 (c_includes ++ reverse cmdline_includes))
498 '"':_{-"-} -> "#include "++h_file
499 '<':_ -> "#include "++h_file
500 _ -> "#include \""++h_file++"\""
502 writeIORef v_HCHeader cc_injects
504 -- gather the imports and module name
505 (srcimps,imps,mod_name) <- getImportsFromFile input_fn
507 -- build a ModuleLocation to pass to hscMain.
509 <- mkHomeModuleLocn mod_name basename (basename ++ '.':suff)
511 -- take -ohi into account if present
512 ohi <- readIORef v_Output_hi
513 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
514 | otherwise = location'
516 -- figure out if the source has changed, for recompilation avoidance.
517 -- only do this if we're eventually going to generate a .o file.
518 -- (ToDo: do when generating .hc files too?)
520 -- Setting source_unchanged to True means that M.o seems
521 -- to be up to date wrt M.hs; so no need to recompile unless imports have
522 -- changed (which the compiler itself figures out).
523 -- Setting source_unchanged to False tells the compiler that M.o is out of
524 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
525 do_recomp <- readIORef v_Recomp
526 todo <- readIORef v_GhcMode
527 expl_o_file <- readIORef v_Output_file
530 Nothing -> unJust "source_unchanged" (ml_obj_file location)
533 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
535 else do t1 <- getModificationTime (basename ++ '.':suff)
536 o_file_exists <- doesFileExist o_file
538 then return False -- Need to recompile
539 else do t2 <- getModificationTime o_file
545 dyn_flags <- getDynFlags
547 let dyn_flags' = dyn_flags { hscOutName = output_fn,
548 hscStubCOutName = basename ++ "_stub.c",
549 hscStubHOutName = basename ++ "_stub.h",
550 extCoreName = basename ++ ".hcr" }
553 pcs <- initPersistentCompilerState
554 result <- hscMain OneShot
556 location{ ml_hspp_file=Just input_fn }
560 emptyModuleEnv -- HomeSymbolTable
561 emptyModuleEnv -- HomeIfaceTable
566 HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
568 HscNoRecomp pcs details iface -> do { SysTools.touch "Touching object file" o_file
571 HscRecomp pcs details iface stub_h_exists stub_c_exists
572 _maybe_interpreted_code -> do
575 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
578 Just stub_o -> add v_Ld_inputs stub_o
579 case hscLang dyn_flags of
580 HscNothing -> return Nothing
581 _ -> return (Just output_fn)
584 -----------------------------------------------------------------------------
587 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
588 -- way too many hacks, and I can't say I've ever used it anyway.
590 run_phase cc_phase basename suff input_fn output_fn
591 | cc_phase == Cc || cc_phase == HCc
592 = do cc_opts <- getOpts opt_c
593 cmdline_include_paths <- readIORef v_Include_paths
595 let hcc = cc_phase == HCc
597 -- add package include paths even if we're just compiling
598 -- .c files; this is the Value Add(TM) that using
599 -- ghc instead of gcc gives you :)
600 pkg_include_dirs <- getPackageIncludePath
601 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
602 (cmdline_include_paths ++ pkg_include_dirs)
604 mangle <- readIORef v_Do_asm_mangling
605 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
609 o2 <- readIORef v_minus_o2_for_C
610 let opt_flag | o2 = "-O2"
613 pkg_extra_cc_opts <- getPackageExtraCcOpts
615 split_objs <- readIORef v_Split_object_files
616 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
619 excessPrecision <- readIORef v_Excess_precision
621 -- force the C compiler to interpret this file as C when
622 -- compiling .hc files, by adding the -x c option.
624 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
627 SysTools.runCc (langopt ++
628 [ SysTools.FileOption "" input_fn
629 , SysTools.Option "-o"
630 , SysTools.FileOption "" output_fn
632 ++ map SysTools.Option (
634 ++ (if cc_phase == HCc && mangle
637 ++ [ verb, "-S", "-Wimplicit", opt_flag ]
638 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
641 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
645 return (Just output_fn)
647 -- ToDo: postprocess the output from gcc
649 -----------------------------------------------------------------------------
652 run_phase Mangle _basename _suff input_fn output_fn
653 = do mangler_opts <- getOpts opt_m
654 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
655 then do n_regs <- dynFlag stolen_x86_regs
656 return [ show n_regs ]
659 SysTools.runMangle (map SysTools.Option mangler_opts
660 ++ [ SysTools.FileOption "" input_fn
661 , SysTools.FileOption "" output_fn
663 ++ map SysTools.Option machdep_opts)
664 return (Just output_fn)
666 -----------------------------------------------------------------------------
669 run_phase SplitMangle _basename _suff input_fn output_fn
670 = do -- tmp_pfx is the prefix used for the split .s files
671 -- We also use it as the file to contain the no. of split .s files (sigh)
672 split_s_prefix <- SysTools.newTempName "split"
673 let n_files_fn = split_s_prefix
675 SysTools.runSplit [ SysTools.FileOption "" input_fn
676 , SysTools.FileOption "" split_s_prefix
677 , SysTools.FileOption "" n_files_fn
680 -- Save the number of split files for future references
681 s <- readFile n_files_fn
682 let n_files = read s :: Int
683 writeIORef v_Split_info (split_s_prefix, n_files)
685 -- Remember to delete all these files
686 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
689 return (Just output_fn)
691 -----------------------------------------------------------------------------
694 run_phase As _basename _suff input_fn output_fn
695 = do as_opts <- getOpts opt_a
696 cmdline_include_paths <- readIORef v_Include_paths
698 SysTools.runAs (map SysTools.Option as_opts
699 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
700 ++ [ SysTools.Option "-c"
701 , SysTools.FileOption "" input_fn
702 , SysTools.Option "-o"
703 , SysTools.FileOption "" output_fn
705 return (Just output_fn)
707 run_phase SplitAs basename _suff _input_fn output_fn
708 = do as_opts <- getOpts opt_a
710 (split_s_prefix, n) <- readIORef v_Split_info
712 odir <- readIORef v_Output_dir
713 let real_odir = case odir of
718 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
719 let output_o = newdir real_odir
720 (basename ++ "__" ++ show n ++ ".o")
721 real_o <- osuf_ify output_o
722 SysTools.runAs (map SysTools.Option as_opts ++
723 [ SysTools.Option "-c"
724 , SysTools.Option "-o"
725 , SysTools.FileOption "" real_o
726 , SysTools.FileOption "" input_s
729 mapM_ assemble_file [1..n]
730 return (Just output_fn)
733 -----------------------------------------------------------------------------
735 -- Run ilx2il over the ILX output, getting an IL file
737 run_phase Ilx2Il _basename _suff input_fn output_fn
738 = do ilx2il_opts <- getOpts opt_I
739 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
740 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
741 SysTools.Option "mscorlib",
742 SysTools.Option "-o",
743 SysTools.FileOption "" output_fn,
744 SysTools.FileOption "" input_fn ])
745 return (Just output_fn)
747 -----------------------------------------------------------------------------
749 -- Run ilasm over the IL, getting a DLL
751 run_phase Ilasm _basename _suff input_fn output_fn
752 = do ilasm_opts <- getOpts opt_i
753 SysTools.runIlasm (map SysTools.Option ilasm_opts
754 ++ [ SysTools.Option "/QUIET",
755 SysTools.Option "/DLL",
756 SysTools.FileOption "/OUT=" output_fn,
757 SysTools.FileOption "" input_fn ])
758 return (Just output_fn)
762 -----------------------------------------------------------------------------
763 -- MoveBinary sort-of-phase
764 -- After having produced a binary, move it somewhere else and generate a
765 -- wrapper script calling the binary. Currently, we need this only in
766 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
767 -- central directory.
768 -- This is called from doLink below, after linking. I haven't made it
769 -- a separate phase to minimise interfering with other modules, and
770 -- we don't need the generality of a phase (MoveBinary is always
771 -- done after linking and makes only sense in a parallel setup) -- HWL
773 run_phase_MoveBinary input_fn
776 pvm_root <- getEnv "PVM_ROOT"
777 pvm_arch <- getEnv "PVM_ARCH"
779 pvm_executable_base = "=" ++ input_fn
780 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
781 -- nuke old binary; maybe use configur'ed names for cp and rm?
782 system ("rm -f " ++ pvm_executable)
783 -- move the newly created binary into PVM land
784 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
785 -- generate a wrapper script for running a parallel prg under PVM
786 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
789 -- generates a Perl skript starting a parallel prg under PVM
790 mk_pvm_wrapper_script :: String -> String -> String -> String
791 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
793 "eval 'exec perl -S $0 ${1+\"$@\"}'",
794 " if $running_under_some_shell;",
795 "# =!=!=!=!=!=!=!=!=!=!=!",
796 "# This script is automatically generated: DO NOT EDIT!!!",
797 "# Generated by Glasgow Haskell Compiler",
798 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
800 "$pvm_executable = '" ++ pvm_executable ++ "';",
801 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
802 "$SysMan = '" ++ sysMan ++ "';",
804 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
805 "# first, some magical shortcuts to run "commands" on the binary",
806 "# (which is hidden)",
807 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
808 " local($cmd) = $1;",
809 " system("$cmd $pvm_executable");",
810 " exit(0); # all done",
813 "# Now, run the real binary; process the args first",
814 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
816 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
817 "@nonPVM_args = ();",
820 "args: while ($a = shift(@ARGV)) {",
821 " if ( $a eq '+RTS' ) {",
822 " $in_RTS_args = 1;",
823 " } elsif ( $a eq '-RTS' ) {",
824 " $in_RTS_args = 0;",
826 " if ( $a eq '-d' && $in_RTS_args ) {",
828 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
829 " $nprocessors = $1;",
830 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
831 " $nprocessors = $1;",
833 " push(@nonPVM_args, $a);",
837 "local($return_val) = 0;",
838 "# Start the parallel execution by calling SysMan",
839 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
841 "# ToDo: fix race condition moving files and flushing them!!",
842 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
846 -----------------------------------------------------------------------------
847 -- Complain about non-dynamic flags in OPTIONS pragmas
849 checkProcessArgsResult flags basename suff
850 = do when (not (null flags)) (throwDyn (ProgramError (
851 basename ++ "." ++ suff
852 ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t"
853 ++ unwords flags)) (ExitFailure 1))
855 -----------------------------------------------------------------------------
858 doLink :: [String] -> IO ()
861 static <- readIORef v_Static
862 no_hs_main <- readIORef v_NoHsMain
864 o_file <- readIORef v_Output_file
865 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
867 pkg_lib_paths <- getPackageLibraryPath
868 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
870 lib_paths <- readIORef v_Library_paths
871 let lib_path_opts = map ("-L"++) lib_paths
873 pkg_libs <- getPackageLibraries
874 let imp = if static then "" else "_imp"
875 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
877 libs <- readIORef v_Cmdline_libraries
878 let lib_opts = map ("-l"++) (reverse libs)
879 -- reverse because they're added in reverse order from the cmd line
881 pkg_extra_ld_opts <- getPackageExtraLdOpts
883 -- probably _stub.o files
884 extra_ld_inputs <- readIORef v_Ld_inputs
886 -- opts from -optl-<blah>
887 extra_ld_opts <- getStaticOpts v_Opt_l
889 rts_pkg <- getPackageDetails ["rts"]
890 std_pkg <- getPackageDetails ["std"]
891 let extra_os = if static || no_hs_main
893 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
894 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
896 (md_c_flags, _) <- machdepCCOpts
897 SysTools.runLink ( [ SysTools.Option verb
898 , SysTools.Option "-o"
899 , SysTools.FileOption "" output_fn
901 ++ map SysTools.Option (
912 ++ if static && not no_hs_main then
913 [ "-u", prefixUnderscore "PrelMain_mainIO_closure",
914 "-u", prefixUnderscore "__stginit_PrelMain"]
917 -- parallel only: move binary to another dir -- HWL
918 ways_ <- readIORef v_Ways
919 when (WayPar `elem` ways_)
920 (do success <- run_phase_MoveBinary output_fn
921 if success then return ()
922 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
924 -----------------------------------------------------------------------------
925 -- Making a DLL (only for Win32)
927 doMkDLL :: [String] -> IO ()
930 static <- readIORef v_Static
931 no_hs_main <- readIORef v_NoHsMain
933 o_file <- readIORef v_Output_file
934 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
936 pkg_lib_paths <- getPackageLibraryPath
937 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
939 lib_paths <- readIORef v_Library_paths
940 let lib_path_opts = map ("-L"++) lib_paths
942 pkg_libs <- getPackageLibraries
943 let imp = if static then "" else "_imp"
944 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
946 libs <- readIORef v_Cmdline_libraries
947 let lib_opts = map ("-l"++) (reverse libs)
948 -- reverse because they're added in reverse order from the cmd line
950 pkg_extra_ld_opts <- getPackageExtraLdOpts
952 -- probably _stub.o files
953 extra_ld_inputs <- readIORef v_Ld_inputs
955 -- opts from -optdll-<blah>
956 extra_ld_opts <- getStaticOpts v_Opt_dll
958 rts_pkg <- getPackageDetails ["rts"]
959 std_pkg <- getPackageDetails ["std"]
961 let extra_os = if static || no_hs_main
963 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
964 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
966 (md_c_flags, _) <- machdepCCOpts
968 ([ SysTools.Option verb
969 , SysTools.Option "-o"
970 , SysTools.FileOption "" output_fn
972 ++ map SysTools.Option (
976 ++ [ "--target=i386-mingw32" ]
983 ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
984 Nothing -> [ "--export-all" ]
989 -----------------------------------------------------------------------------
990 -- Just preprocess a file, put the result in a temp. file (used by the
991 -- compilation manager during the summary phase).
993 preprocess :: FilePath -> IO FilePath
994 preprocess filename =
995 ASSERT(haskellish_src_file filename)
996 do restoreDynFlags -- Restore to state of last save
997 let fInfo = (filename, getFileSuffix filename)
998 pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False
1000 (fn,_) <- runPipeline pipeline fInfo
1001 False{-no linking-} False{-no -o flag-}
1004 -----------------------------------------------------------------------------
1005 -- Compile a single module, under the control of the compilation manager.
1007 -- This is the interface between the compilation manager and the
1008 -- compiler proper (hsc), where we deal with tedious details like
1009 -- reading the OPTIONS pragma from the source file, and passing the
1010 -- output of hsc through the C compiler.
1012 -- The driver sits between 'compile' and 'hscMain', translating calls
1013 -- to the former into calls to the latter, and results from the latter
1014 -- into results from the former. It does things like preprocessing
1015 -- the .hs file if necessary, and compiling up the .stub_c files to
1016 -- generate Linkables.
1018 -- NB. No old interface can also mean that the source has changed.
1020 compile :: GhciMode -- distinguish batch from interactive
1021 -> ModSummary -- summary, including source
1022 -> Bool -- True <=> source unchanged
1023 -> Bool -- True <=> have object
1024 -> Maybe ModIface -- old interface, if available
1025 -> HomeSymbolTable -- for home module ModDetails
1026 -> HomeIfaceTable -- for home module Ifaces
1027 -> PersistentCompilerState -- persistent compiler state
1031 = CompOK PersistentCompilerState -- updated PCS
1032 ModDetails -- new details (HST additions)
1033 ModIface -- new iface (HIT additions)
1035 -- new code; Nothing => compilation was not reqd
1036 -- (old code is still valid)
1038 | CompErrs PersistentCompilerState -- updated PCS
1041 compile ghci_mode summary source_unchanged have_object
1042 old_iface hst hit pcs = do
1043 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
1047 (showSDoc (text "Compiling" <+> ppr (modSummaryName summary)))
1049 let verb = verbosity dyn_flags
1050 let location = ms_location summary
1051 let input_fn = unJust "compile:hs" (ml_hs_file location)
1052 let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
1054 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
1056 opts <- getOptionsFromSource input_fnpp
1057 processArgs dynamic_flags opts []
1058 dyn_flags <- getDynFlags
1060 let hsc_lang = hscLang dyn_flags
1061 (basename, _) = splitFilename input_fn
1063 keep_hc <- readIORef v_Keep_hc_files
1065 keep_il <- readIORef v_Keep_il_files
1067 keep_s <- readIORef v_Keep_s_files
1071 HscAsm | keep_s -> return (basename ++ '.':phaseInputExt As)
1072 | otherwise -> newTempName (phaseInputExt As)
1073 HscC | keep_hc -> return (basename ++ '.':phaseInputExt HCc)
1074 | otherwise -> newTempName (phaseInputExt HCc)
1075 HscJava -> newTempName "java" -- ToDo
1077 HscILX | keep_il -> return (basename ++ '.':phaseInputExt Ilasm)
1078 | otherwise -> newTempName (phaseInputExt Ilx2Il)
1080 HscInterpreted -> return (error "no output file")
1081 HscNothing -> return (error "no output file")
1083 let dyn_flags' = dyn_flags { hscOutName = output_fn,
1084 hscStubCOutName = basename ++ "_stub.c",
1085 hscStubHOutName = basename ++ "_stub.h",
1086 extCoreName = basename ++ ".hcr" }
1088 -- figure out which header files to #include in a generated .hc file
1089 c_includes <- getPackageCIncludes
1090 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
1092 let cc_injects = unlines (map mk_include
1093 (c_includes ++ reverse cmdline_includes))
1096 '"':_{-"-} -> "#include "++h_file
1097 '<':_ -> "#include "++h_file
1098 _ -> "#include \""++h_file++"\""
1100 writeIORef v_HCHeader cc_injects
1102 -- -no-recomp should also work with --make
1103 do_recomp <- readIORef v_Recomp
1104 let source_unchanged' = source_unchanged && do_recomp
1107 hsc_result <- hscMain ghci_mode dyn_flags'
1108 (ms_mod summary) location
1109 source_unchanged' have_object old_iface hst hit pcs
1112 HscFail pcs -> return (CompErrs pcs)
1114 HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
1116 HscRecomp pcs details iface
1117 stub_h_exists stub_c_exists maybe_interpreted_code -> do
1120 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
1121 let stub_unlinked = case maybe_stub_o of
1123 Just stub_o -> [ DotO stub_o ]
1125 (hs_unlinked, unlinked_time) <-
1128 -- in interpreted mode, just return the compiled code
1129 -- as our "unlinked" object.
1131 case maybe_interpreted_code of
1133 Just (bcos,itbl_env) -> do tm <- getClockTime
1134 return ([BCOs bcos itbl_env], tm)
1136 Nothing -> panic "compile: no interpreted code"
1138 -- we're in batch mode: finish the compilation pipeline.
1139 _other -> do pipe <- genPipeline (StopBefore Ln) "" True
1140 hsc_lang (output_fn, getFileSuffix output_fn)
1141 -- runPipeline takes input_fn so it can split off
1142 -- the base name and use it as the base of
1143 -- the output object file.
1144 let (basename, suffix) = splitFilename input_fn
1146 pipeLoop pipe (output_fn, getFileSuffix output_fn)
1149 o_time <- getModificationTime o_file
1150 return ([DotO o_file], o_time)
1152 let linkable = LM unlinked_time (modSummaryName summary)
1153 (hs_unlinked ++ stub_unlinked)
1155 return (CompOK pcs details iface (Just linkable))
1158 -----------------------------------------------------------------------------
1159 -- stub .h and .c files (for foreign export support)
1161 compileStub dflags stub_c_exists
1162 | not stub_c_exists = return Nothing
1163 | stub_c_exists = do
1164 -- compile the _stub.c file w/ gcc
1165 let stub_c = hscStubCOutName dflags
1166 pipeline <- genPipeline (StopBefore Ln) "" True defaultHscLang (stub_c,"c")
1167 (stub_o,_) <- runPipeline pipeline (stub_c,"c") False{-no linking-}
1168 False{-no -o option-}
1169 return (Just stub_o)