[project @ 2002-01-04 16:02:03 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / DriverPipeline.hs
1 -----------------------------------------------------------------------------
2 --
3 -- GHC Driver
4 --
5 -- (c) The University of Glasgow 2002
6 --
7 -----------------------------------------------------------------------------
8
9 #include "../includes/config.h"
10
11 module DriverPipeline (
12
13         -- interfaces for the batch-mode driver
14    genPipeline, runPipeline, pipeLoop,
15
16         -- interfaces for the compilation manager (interpreted/batch-mode)
17    preprocess, compile, CompResult(..),
18
19         -- batch-mode linking interface
20    doLink,
21         -- DLL building
22    doMkDLL
23   ) where
24
25 #include "HsVersions.h"
26
27 import Packages
28 import CmTypes
29 import GetImports
30 import DriverState
31 import DriverUtil
32 import DriverMkDepend
33 import DriverPhases
34 import DriverFlags
35 import SysTools         ( newTempName, addFilesToClean, getSysMan, copy )
36 import qualified SysTools       
37 import HscMain
38 import Finder
39 import HscTypes
40 import Outputable
41 import Module
42 import ErrUtils
43 import CmdLineOpts
44 import Config
45 import Panic
46 import Util
47
48 import Time             ( getClockTime )
49 import Directory
50 import System
51 import IOExts
52 import Exception
53
54 import IO
55 import Monad
56 import Maybe
57
58 import PackedString
59 import MatchPS
60
61 -----------------------------------------------------------------------------
62 -- genPipeline
63 --
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.
67
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
73 -- driver.
74
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
79 -- compiler).
80
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.
87
88 data IntermediateFileType
89   = Temporary
90   | Persistent
91   deriving (Eq, Show)
92
93 genPipeline
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
100              (Phase,
101               IntermediateFileType,  -- keep the output from this phase?
102               String)                -- output file suffix
103          ]      
104
105 genPipeline todo stop_flag persistent_output lang (filename,suffix)
106  = do
107    split      <- readIORef v_Split_object_files
108    mangle     <- readIORef v_Do_asm_mangling
109    keep_hc    <- readIORef v_Keep_hc_files
110 #ifdef ILX
111    keep_il    <- readIORef v_Keep_il_files
112    keep_ilx   <- readIORef v_Keep_ilx_files
113 #endif
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
118
119    let
120    ----------- -----  ----   ---   --   --  -  -  -
121     start = startPhase suffix
122
123       -- special case for mkdependHS: .hspp files go through MkDependHS
124     start_phase | todo == DoMkDependHS && start == Hsc  = MkDependHS
125                 | otherwise = start
126
127     haskellish = haskellish_suffix suffix
128     cish = cish_suffix suffix
129
130        -- for a .hc file we need to force lang to HscC
131     real_lang | start_phase == HCc || start_phase == Mangle = HscC
132               | otherwise                                   = lang
133
134    let
135    ----------- -----  ----   ---   --   --  -  -  -
136     pipeline = preprocess ++ compile
137
138     preprocess
139         | haskellish = [ Unlit, Cpp, HsPp ]
140         | otherwise  = [ ]
141
142     compile
143       | todo == DoMkDependHS = [ MkDependHS ]
144
145       | cish = [ Cc, As ]
146
147       | haskellish = 
148        case real_lang of
149         HscC    | split && mangle -> [ Hsc, HCc, Mangle, SplitMangle, SplitAs ]
150                 | mangle          -> [ Hsc, HCc, Mangle, As ]
151                 | split           -> not_valid
152                 | otherwise       -> [ Hsc, HCc, As ]
153
154         HscAsm  | split           -> [ Hsc, SplitMangle, SplitAs ]
155                 | otherwise       -> [ Hsc, As ]
156
157         HscJava | split           -> not_valid
158                 | otherwise       -> error "not implemented: compiling via Java"
159 #ifdef ILX
160         HscILX  | split           -> not_valid
161                 | otherwise       -> [ Hsc, Ilx2Il, Ilasm ]
162 #endif
163         HscNothing                -> [ Hsc, HCc ] -- HCc is a dummy stop phase
164
165       | otherwise = [ ]  -- just pass this file through to the linker
166
167         -- ToDo: this is somewhat cryptic
168     not_valid = throwDyn (UsageError ("invalid option combination"))
169
170     stop_phase = case todo of 
171                         StopBefore As | split -> SplitAs
172 #ifdef ILX
173                                       | real_lang == HscILX -> Ilasm
174 #endif
175                         StopBefore phase      -> phase
176                         DoMkDependHS          -> Ln
177                         DoLink                -> Ln
178                         DoMkDLL               -> Ln
179    ----------- -----  ----   ---   --   --  -  -  -
180
181         -- this shouldn't happen.
182    when (start_phase /= Ln && start_phase `notElem` pipeline)
183         (throwDyn (CmdLineError ("can't find starting phase for "
184                                  ++ filename)))
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)))
195    let
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
200
201       annotatePipeline
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
210           where
211                 keep_this_output
212                      | next_phase == stop 
213                      = if persistent_output then Persistent else Temporary
214                      | otherwise
215                      = case next_phase of
216                              Ln -> Persistent
217                              Mangle | keep_raw_s -> Persistent
218                              As     | keep_s     -> Persistent
219                              HCc    | keep_hc    -> Persistent
220 #ifdef ILX
221                              Ilx2Il | keep_ilx   -> Persistent
222                              Ilasm  | keep_il    -> Persistent
223 #endif
224                              _other              -> Temporary
225
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.
230
231       annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
232
233       phase_ne p (p1,_,_) = (p1 /= p)
234    ----------- -----  ----   ---   --   --  -  -  -
235
236    return (
237      takeWhile (phase_ne stop_phase ) $
238      dropWhile (phase_ne start_phase) $
239      annotated_pipeline
240     )
241
242
243 runPipeline
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
249
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
253
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
257   = do
258
259      output_fn <- outputFileName (null phases) keep o_suffix
260
261      mbCarryOn <- run_phase phase orig_basename orig_suffix
262                             input_fn output_fn 
263         -- sometimes we bail out early, eg. when the compiler's recompilation
264         -- checker has determined that recompilation isn't necessary.
265      case mbCarryOn of
266        Nothing -> do
267               let (_,keep,final_suffix) = last all_phases
268               ofile <- outputFileName True keep final_suffix
269               return (ofile, final_suffix)
270           -- carry on ...
271        Just fn -> do
272                 {-
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).
276                   
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
279                   expected to end up.
280                 -}
281               atEnd <- finalStage (null phases)
282               when (atEnd && fn == input_fn)
283                    (copy "Saving away compilation pipeline's output"
284                          input_fn
285                          output_fn)
286               {-
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
292                suffix in reality.
293                
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.
298
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]
301                
302               -}
303               pipeLoop phases (fn, o_suffix) do_linking use_ofile
304                         orig_basename orig_suffix
305   where
306      finalStage lastPhase = do
307        o_file <- readIORef v_Output_file
308        return (lastPhase && not do_linking && use_ofile && isJust o_file)
309
310      outputFileName last_phase keep suffix
311         = do o_file <- readIORef v_Output_file
312              atEnd  <- finalStage last_phase
313              if atEnd
314                then case o_file of 
315                        Just s  -> return s
316                        Nothing -> error "outputFileName"
317                else if keep == Persistent
318                            then odir_ify (orig_basename ++ '.':suffix)
319                            else newTempName suffix
320
321 run_phase :: Phase
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 -------------------------------------------------------------------------------
331 -- Unlit phase 
332
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
341                           ])
342        return (Just output_fn)
343
344 -------------------------------------------------------------------------------
345 -- Cpp phase 
346
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
351
352        do_cpp <- dynFlag cppFlag
353        if not do_cpp then
354            -- no need to preprocess CPP, just pass input file along
355            -- to the next phase of the pipeline.
356           return (Just input_fn)
357         else do
358             hscpp_opts      <- getOpts opt_P
359             hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
360
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)
365
366             verb <- getVerbFlag
367             (md_c_flags, _) <- machdepCCOpts
368
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
387                                ])
388             return (Just output_fn)
389
390 -------------------------------------------------------------------------------
391 -- HsPp phase 
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
396
397        let orig_fn = basename ++ '.':suff
398        do_pp   <- dynFlag ppFlag
399        if not do_pp then
400            -- no need to preprocess, just pass input file along
401            -- to the next phase of the pipeline.
402           return (Just input_fn)
403         else do
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
409                              ] ++
410                              map SysTools.Option hs_src_pp_opts ++
411                              map SysTools.Option hspp_opts
412                            )
413             return (Just output_fn)
414
415 -----------------------------------------------------------------------------
416 -- MkDependHS phase
417
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
425
426       osuf_opt <- readIORef v_Object_suf
427       let osuf = case osuf_opt of
428                    Nothing -> phaseInputExt Ln
429                    Just s  -> s
430
431       extra_suffixes <- readIORef v_Dep_suffixes
432       let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
433           ofiles = map (\suf -> basename ++ '.':suf) suffixes
434
435       objs <- mapM odir_ify ofiles
436
437         -- Handle for file that accumulates dependencies 
438       hdl <- readIORef v_Dep_tmp_hdl
439
440         -- std dependency of the object(s) on the source file
441       hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
442
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)
452
453       sequence_ (map genDep [ d | Just d <- deps ])
454       return (Just output_fn)
455
456 -- add the lines to dep_makefile:
457            -- always:
458                    -- this.o : this.hs
459
460            -- if the dependency is on something other than a .hi file:
461                    -- this.o this.p_o ... : dep
462            -- otherwise
463                    -- if the import is {-# SOURCE #-}
464                            -- this.o this.p_o ... : dep.hi-boot[-$vers]
465                            
466                    -- else
467                            -- this.o ...   : dep.hi
468                            -- this.p_o ... : dep.p_hi
469                            -- ...
470    
471            -- (where .o is $osuf, and the other suffixes come from
472            -- the cmdline -s options).
473    
474 -----------------------------------------------------------------------------
475 -- Hsc phase
476
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
480   = do
481         
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
486         
487         paths <- readIORef v_Include_paths
488         writeIORef v_Include_paths (current_dir : paths)
489         
490   -- figure out which header files to #include in a generated .hc file
491         c_includes <- getPackageCIncludes
492         cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
493
494         let cc_injects = unlines (map mk_include 
495                                  (c_includes ++ reverse cmdline_includes))
496             mk_include h_file = 
497                 case h_file of 
498                    '"':_{-"-} -> "#include "++h_file
499                    '<':_      -> "#include "++h_file
500                    _          -> "#include \""++h_file++"\""
501
502         writeIORef v_HCHeader cc_injects
503
504   -- gather the imports and module name
505         (srcimps,imps,mod_name) <- getImportsFromFile input_fn
506
507   -- build a ModuleLocation to pass to hscMain.
508         (mod, location')
509            <- mkHomeModuleLocn mod_name basename (basename ++ '.':suff)
510
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'
515
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?)
519   --
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
528         let o_file = 
529                 case expl_o_file of
530                   Nothing -> unJust "source_unchanged" (ml_obj_file location)
531                   Just x  -> x
532         source_unchanged <- 
533           if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
534              then return False
535              else do t1 <- getModificationTime (basename ++ '.':suff)
536                      o_file_exists <- doesFileExist o_file
537                      if not o_file_exists
538                         then return False       -- Need to recompile
539                         else do t2 <- getModificationTime o_file
540                                 if t2 > t1
541                                   then return True
542                                   else return False
543
544   -- get the DynFlags
545         dyn_flags <- getDynFlags
546
547         let dyn_flags' = dyn_flags { hscOutName = output_fn,
548                                      hscStubCOutName = basename ++ "_stub.c",
549                                      hscStubHOutName = basename ++ "_stub.h",
550                                      extCoreName = basename ++ ".hcr" }
551
552   -- run the compiler!
553         pcs <- initPersistentCompilerState
554         result <- hscMain OneShot
555                           dyn_flags' mod
556                           location{ ml_hspp_file=Just input_fn }
557                           source_unchanged
558                           False
559                           Nothing        -- no iface
560                           emptyModuleEnv -- HomeSymbolTable
561                           emptyModuleEnv -- HomeIfaceTable
562                           pcs
563
564         case result of {
565
566             HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
567
568             HscNoRecomp pcs details iface -> do { SysTools.touch "Touching object file" o_file
569                                                 ; return Nothing } ;
570
571             HscRecomp pcs details iface stub_h_exists stub_c_exists
572                       _maybe_interpreted_code -> do
573
574                             -- deal with stubs
575                             maybe_stub_o <- compileStub dyn_flags' stub_c_exists
576                             case maybe_stub_o of
577                               Nothing -> return ()
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)
582     }
583
584 -----------------------------------------------------------------------------
585 -- Cc phase
586
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.
589
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
594
595         let hcc = cc_phase == HCc
596
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)
603
604         mangle <- readIORef v_Do_asm_mangling
605         (md_c_flags, md_regd_c_flags) <- machdepCCOpts
606
607         verb <- getVerbFlag
608
609         o2 <- readIORef v_minus_o2_for_C
610         let opt_flag | o2        = "-O2"
611                      | otherwise = "-O"
612
613         pkg_extra_cc_opts <- getPackageExtraCcOpts
614
615         split_objs <- readIORef v_Split_object_files
616
617         excessPrecision <- readIORef v_Excess_precision
618
619         -- force the C compiler to interpret this file as C when
620         -- compiling .hc files, by adding the -x c option.
621         let langopt
622                 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
623                 | otherwise       = [ ]
624
625         SysTools.runCc (langopt ++
626                         [ SysTools.FileOption "" input_fn
627                         , SysTools.Option "-o"
628                         , SysTools.FileOption "" output_fn
629                         ]
630                        ++ map SysTools.Option (
631                           md_c_flags
632                        ++ (if cc_phase == HCc && mangle
633                              then md_regd_c_flags
634                              else [])
635                        ++ [ verb, "-S", "-Wimplicit", opt_flag ]
636                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
637                        ++ cc_opts
638                        ++ (if excessPrecision then [] else [ "-ffloat-store" ])
639                        ++ include_paths
640                        ++ pkg_extra_cc_opts
641                        ))
642         return (Just output_fn)
643
644         -- ToDo: postprocess the output from gcc
645
646 -----------------------------------------------------------------------------
647 -- Mangle phase
648
649 run_phase Mangle _basename _suff input_fn output_fn
650   = do mangler_opts <- getOpts opt_m
651        machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
652                        then do n_regs <- dynFlag stolen_x86_regs
653                                return [ show n_regs ]
654                        else return []
655
656        SysTools.runMangle (map SysTools.Option mangler_opts
657                           ++ [ SysTools.FileOption "" input_fn
658                              , SysTools.FileOption "" output_fn
659                              ]
660                           ++ map SysTools.Option machdep_opts)
661        return (Just output_fn)
662
663 -----------------------------------------------------------------------------
664 -- Splitting phase
665
666 run_phase SplitMangle _basename _suff input_fn output_fn
667   = do  -- tmp_pfx is the prefix used for the split .s files
668         -- We also use it as the file to contain the no. of split .s files (sigh)
669         split_s_prefix <- SysTools.newTempName "split"
670         let n_files_fn = split_s_prefix
671
672         SysTools.runSplit [ SysTools.FileOption "" input_fn
673                           , SysTools.FileOption "" split_s_prefix
674                           , SysTools.FileOption "" n_files_fn
675                           ]
676
677         -- Save the number of split files for future references
678         s <- readFile n_files_fn
679         let n_files = read s :: Int
680         writeIORef v_Split_info (split_s_prefix, n_files)
681
682         -- Remember to delete all these files
683         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
684                         | n <- [1..n_files]]
685
686         return (Just output_fn)
687
688 -----------------------------------------------------------------------------
689 -- As phase
690
691 run_phase As _basename _suff input_fn output_fn
692   = do  as_opts               <- getOpts opt_a
693         cmdline_include_paths <- readIORef v_Include_paths
694
695         SysTools.runAs (map SysTools.Option as_opts
696                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
697                        ++ [ SysTools.Option "-c"
698                           , SysTools.FileOption "" input_fn
699                           , SysTools.Option "-o"
700                           , SysTools.FileOption "" output_fn
701                           ])
702         return (Just output_fn)
703
704 run_phase SplitAs basename _suff _input_fn output_fn
705   = do  as_opts <- getOpts opt_a
706
707         (split_s_prefix, n) <- readIORef v_Split_info
708
709         odir <- readIORef v_Output_dir
710         let real_odir = case odir of
711                                 Nothing -> basename
712                                 Just d  -> d
713
714         let assemble_file n
715               = do  let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
716                     let output_o = newdir real_odir 
717                                         (basename ++ "__" ++ show n ++ ".o")
718                     real_o <- osuf_ify output_o
719                     SysTools.runAs (map SysTools.Option as_opts ++
720                                     [ SysTools.Option "-c"
721                                     , SysTools.Option "-o"
722                                     , SysTools.FileOption "" real_o
723                                     , SysTools.FileOption "" input_s
724                                     ])
725         
726         mapM_ assemble_file [1..n]
727         return (Just output_fn)
728
729 #ifdef ILX
730 -----------------------------------------------------------------------------
731 -- Ilx2Il phase
732 -- Run ilx2il over the ILX output, getting an IL file
733
734 run_phase Ilx2Il _basename _suff input_fn output_fn
735   = do  ilx2il_opts <- getOpts opt_I
736         SysTools.runIlx2il (map SysTools.Option ilx2il_opts
737                            ++ [ SysTools.Option "--no-add-suffix-to-assembly",
738                                 SysTools.Option "mscorlib",
739                                 SysTools.Option "-o",
740                                 SysTools.FileOption "" output_fn,
741                                 SysTools.FileOption "" input_fn ])
742         return (Just output_fn)
743
744 -----------------------------------------------------------------------------
745 -- Ilasm phase
746 -- Run ilasm over the IL, getting a DLL
747
748 run_phase Ilasm _basename _suff input_fn output_fn
749   = do  ilasm_opts <- getOpts opt_i
750         SysTools.runIlasm (map SysTools.Option ilasm_opts
751                            ++ [ SysTools.Option "/QUIET",
752                                 SysTools.Option "/DLL",
753                                 SysTools.FileOption "/OUT=" output_fn,
754                                 SysTools.FileOption "" input_fn ])
755         return (Just output_fn)
756
757 #endif -- ILX
758
759 -----------------------------------------------------------------------------
760 -- MoveBinary sort-of-phase
761 -- After having produced a binary, move it somewhere else and generate a
762 -- wrapper script calling the binary. Currently, we need this only in 
763 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
764 -- central directory.
765 -- This is called from doLink below, after linking. I haven't made it
766 -- a separate phase to minimise interfering with other modules, and
767 -- we don't need the generality of a phase (MoveBinary is always
768 -- done after linking and makes only sense in a parallel setup)   -- HWL
769
770 run_phase_MoveBinary input_fn
771   = do  
772         sysMan   <- getSysMan
773         pvm_root <- getEnv "PVM_ROOT"
774         pvm_arch <- getEnv "PVM_ARCH"
775         let 
776            pvm_executable_base = "=" ++ input_fn
777            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
778         -- nuke old binary; maybe use configur'ed names for cp and rm?
779         system ("rm -f " ++ pvm_executable)
780         -- move the newly created binary into PVM land
781         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
782         -- generate a wrapper script for running a parallel prg under PVM
783         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
784         return True
785
786 -- generates a Perl skript starting a parallel prg under PVM
787 mk_pvm_wrapper_script :: String -> String -> String -> String
788 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
789  [
790   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
791   "  if $running_under_some_shell;",
792   "# =!=!=!=!=!=!=!=!=!=!=!",
793   "# This script is automatically generated: DO NOT EDIT!!!",
794   "# Generated by Glasgow Haskell Compiler",
795   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
796   "#",
797   "$pvm_executable      = '" ++ pvm_executable ++ "';",
798   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
799   "$SysMan = '" ++ sysMan ++ "';",
800   "",
801   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
802   "# first, some magical shortcuts to run "commands" on the binary",
803   "# (which is hidden)",
804   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
805   "    local($cmd) = $1;",
806   "    system("$cmd $pvm_executable");",
807   "    exit(0); # all done",
808   "}", -}
809   "",
810   "# Now, run the real binary; process the args first",
811   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
812   "$debug = '';",
813   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
814   "@nonPVM_args = ();",
815   "$in_RTS_args = 0;",
816   "",
817   "args: while ($a = shift(@ARGV)) {",
818   "    if ( $a eq '+RTS' ) {",
819   "     $in_RTS_args = 1;",
820   "    } elsif ( $a eq '-RTS' ) {",
821   "     $in_RTS_args = 0;",
822   "    }",
823   "    if ( $a eq '-d' && $in_RTS_args ) {",
824   "     $debug = '-';",
825   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
826   "     $nprocessors = $1;",
827   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
828   "     $nprocessors = $1;",
829   "    } else {",
830   "     push(@nonPVM_args, $a);",
831   "    }",
832   "}",
833   "",
834   "local($return_val) = 0;",
835   "# Start the parallel execution by calling SysMan",
836   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
837   "$return_val = $?;",
838   "# ToDo: fix race condition moving files and flushing them!!",
839   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
840   "exit($return_val);"
841  ]
842
843 -----------------------------------------------------------------------------
844 -- Complain about non-dynamic flags in OPTIONS pragmas
845
846 checkProcessArgsResult flags basename suff
847   = do when (not (null flags)) (throwDyn (ProgramError (
848            basename ++ "." ++ suff 
849            ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t" 
850            ++ unwords flags)) (ExitFailure 1))
851
852 -----------------------------------------------------------------------------
853 -- Linking
854
855 doLink :: [String] -> IO ()
856 doLink o_files = do
857     verb       <- getVerbFlag
858     static     <- readIORef v_Static
859     no_hs_main <- readIORef v_NoHsMain
860
861     o_file <- readIORef v_Output_file
862     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
863
864     pkg_lib_paths <- getPackageLibraryPath
865     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
866
867     lib_paths <- readIORef v_Library_paths
868     let lib_path_opts = map ("-L"++) lib_paths
869
870     pkg_libs <- getPackageLibraries
871     let imp          = if static then "" else "_imp"
872         pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
873
874     libs <- readIORef v_Cmdline_libraries
875     let lib_opts = map ("-l"++) (reverse libs)
876          -- reverse because they're added in reverse order from the cmd line
877
878     pkg_extra_ld_opts <- getPackageExtraLdOpts
879
880         -- probably _stub.o files
881     extra_ld_inputs <- readIORef v_Ld_inputs
882
883         -- opts from -optl-<blah>
884     extra_ld_opts <- getStaticOpts v_Opt_l
885
886     rts_pkg <- getPackageDetails ["rts"]
887     std_pkg <- getPackageDetails ["std"]
888     let extra_os = if static || no_hs_main
889                    then []
890                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
891                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
892
893     (md_c_flags, _) <- machdepCCOpts
894     SysTools.runLink ( [ SysTools.Option verb
895                        , SysTools.Option "-o"
896                        , SysTools.FileOption "" output_fn
897                        ]
898                       ++ map SysTools.Option (
899                          md_c_flags
900                       ++ o_files
901                       ++ extra_os
902                       ++ extra_ld_inputs
903                       ++ lib_path_opts
904                       ++ lib_opts
905                       ++ pkg_lib_path_opts
906                       ++ pkg_lib_opts
907                       ++ pkg_extra_ld_opts
908                       ++ extra_ld_opts
909                       ++ if static && not no_hs_main then
910                             [ "-u", prefixUnderscore "PrelMain_mainIO_closure",
911                               "-u", prefixUnderscore "__stginit_PrelMain"] 
912                          else []))
913
914     -- parallel only: move binary to another dir -- HWL
915     ways_ <- readIORef v_Ways
916     when (WayPar `elem` ways_)
917          (do success <- run_phase_MoveBinary output_fn
918              if success then return ()
919                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
920
921 -----------------------------------------------------------------------------
922 -- Making a DLL (only for Win32)
923
924 doMkDLL :: [String] -> IO ()
925 doMkDLL o_files = do
926     verb       <- getVerbFlag
927     static     <- readIORef v_Static
928     no_hs_main <- readIORef v_NoHsMain
929
930     o_file <- readIORef v_Output_file
931     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
932
933     pkg_lib_paths <- getPackageLibraryPath
934     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
935
936     lib_paths <- readIORef v_Library_paths
937     let lib_path_opts = map ("-L"++) lib_paths
938
939     pkg_libs <- getPackageLibraries
940     let imp = if static then "" else "_imp"
941         pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
942
943     libs <- readIORef v_Cmdline_libraries
944     let lib_opts = map ("-l"++) (reverse libs)
945          -- reverse because they're added in reverse order from the cmd line
946
947     pkg_extra_ld_opts <- getPackageExtraLdOpts
948
949         -- probably _stub.o files
950     extra_ld_inputs <- readIORef v_Ld_inputs
951
952         -- opts from -optdll-<blah>
953     extra_ld_opts <- getStaticOpts v_Opt_dll
954
955     rts_pkg <- getPackageDetails ["rts"]
956     std_pkg <- getPackageDetails ["std"]
957
958     let extra_os = if static || no_hs_main
959                    then []
960                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
961                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
962
963     (md_c_flags, _) <- machdepCCOpts
964     SysTools.runMkDLL
965          ([ SysTools.Option verb
966           , SysTools.Option "-o"
967           , SysTools.FileOption "" output_fn
968           ]
969          ++ map SysTools.Option (
970             md_c_flags
971          ++ o_files
972          ++ extra_os
973          ++ [ "--target=i386-mingw32" ]
974          ++ extra_ld_inputs
975          ++ lib_path_opts
976          ++ lib_opts
977          ++ pkg_lib_path_opts
978          ++ pkg_lib_opts
979          ++ pkg_extra_ld_opts
980          ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
981                Nothing -> [ "--export-all" ]
982                Just _  -> [ "" ])
983          ++ extra_ld_opts
984         ))
985
986 -----------------------------------------------------------------------------
987 -- Just preprocess a file, put the result in a temp. file (used by the
988 -- compilation manager during the summary phase).
989
990 preprocess :: FilePath -> IO FilePath
991 preprocess filename =
992   ASSERT(haskellish_src_file filename) 
993   do restoreDynFlags    -- Restore to state of last save
994      let fInfo = (filename, getFileSuffix filename)
995      pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False 
996                              defaultHscLang fInfo
997      (fn,_)   <- runPipeline pipeline fInfo
998                              False{-no linking-} False{-no -o flag-}
999      return fn
1000
1001 -----------------------------------------------------------------------------
1002 -- Compile a single module, under the control of the compilation manager.
1003 --
1004 -- This is the interface between the compilation manager and the
1005 -- compiler proper (hsc), where we deal with tedious details like
1006 -- reading the OPTIONS pragma from the source file, and passing the
1007 -- output of hsc through the C compiler.
1008
1009 -- The driver sits between 'compile' and 'hscMain', translating calls
1010 -- to the former into calls to the latter, and results from the latter
1011 -- into results from the former.  It does things like preprocessing
1012 -- the .hs file if necessary, and compiling up the .stub_c files to
1013 -- generate Linkables.
1014
1015 -- NB.  No old interface can also mean that the source has changed.
1016
1017 compile :: GhciMode                -- distinguish batch from interactive
1018         -> ModSummary              -- summary, including source
1019         -> Bool                    -- True <=> source unchanged
1020         -> Bool                    -- True <=> have object
1021         -> Maybe ModIface          -- old interface, if available
1022         -> HomeSymbolTable         -- for home module ModDetails
1023         -> HomeIfaceTable          -- for home module Ifaces
1024         -> PersistentCompilerState -- persistent compiler state
1025         -> IO CompResult
1026
1027 data CompResult
1028    = CompOK   PersistentCompilerState   -- updated PCS
1029               ModDetails  -- new details (HST additions)
1030               ModIface    -- new iface   (HIT additions)
1031               (Maybe Linkable)
1032                        -- new code; Nothing => compilation was not reqd
1033                        -- (old code is still valid)
1034
1035    | CompErrs PersistentCompilerState   -- updated PCS
1036
1037
1038 compile ghci_mode summary source_unchanged have_object 
1039         old_iface hst hit pcs = do 
1040    dyn_flags <- restoreDynFlags         -- Restore to the state of the last save
1041
1042
1043    showPass dyn_flags 
1044         (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
1045
1046    let verb       = verbosity dyn_flags
1047    let location   = ms_location summary
1048    let input_fn   = unJust "compile:hs" (ml_hs_file location) 
1049    let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
1050
1051    when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
1052
1053    opts <- getOptionsFromSource input_fnpp
1054    processArgs dynamic_flags opts []
1055    dyn_flags <- getDynFlags
1056
1057    let hsc_lang      = hscLang dyn_flags
1058        (basename, _) = splitFilename input_fn
1059        
1060    keep_hc <- readIORef v_Keep_hc_files
1061 #ifdef ILX
1062    keep_il <- readIORef v_Keep_il_files
1063 #endif
1064    keep_s  <- readIORef v_Keep_s_files
1065
1066    output_fn <- 
1067         case hsc_lang of
1068            HscAsm  | keep_s    -> return (basename ++ '.':phaseInputExt As)
1069                    | otherwise -> newTempName (phaseInputExt As)
1070            HscC    | keep_hc   -> return (basename ++ '.':phaseInputExt HCc)
1071                    | otherwise -> newTempName (phaseInputExt HCc)
1072            HscJava             -> newTempName "java" -- ToDo
1073 #ifdef ILX
1074            HscILX  | keep_il   -> return (basename ++ '.':phaseInputExt Ilasm)
1075                    | otherwise -> newTempName (phaseInputExt Ilx2Il)    
1076 #endif
1077            HscInterpreted      -> return (error "no output file")
1078            HscNothing          -> return (error "no output file")
1079
1080    let dyn_flags' = dyn_flags { hscOutName = output_fn,
1081                                 hscStubCOutName = basename ++ "_stub.c",
1082                                 hscStubHOutName = basename ++ "_stub.h",
1083                                 extCoreName = basename ++ ".hcr" }
1084
1085    -- figure out which header files to #include in a generated .hc file
1086    c_includes <- getPackageCIncludes
1087    cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
1088
1089    let cc_injects = unlines (map mk_include 
1090                                  (c_includes ++ reverse cmdline_includes))
1091        mk_include h_file = 
1092         case h_file of 
1093            '"':_{-"-} -> "#include "++h_file
1094            '<':_      -> "#include "++h_file
1095            _          -> "#include \""++h_file++"\""
1096
1097    writeIORef v_HCHeader cc_injects
1098
1099    -- -no-recomp should also work with --make
1100    do_recomp <- readIORef v_Recomp
1101    let source_unchanged' = source_unchanged && do_recomp
1102
1103    -- run the compiler
1104    hsc_result <- hscMain ghci_mode dyn_flags'
1105                          (ms_mod summary) location
1106                          source_unchanged' have_object old_iface hst hit pcs
1107
1108    case hsc_result of
1109       HscFail pcs -> return (CompErrs pcs)
1110
1111       HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
1112
1113       HscRecomp pcs details iface
1114         stub_h_exists stub_c_exists maybe_interpreted_code -> do
1115            
1116            let 
1117            maybe_stub_o <- compileStub dyn_flags' stub_c_exists
1118            let stub_unlinked = case maybe_stub_o of
1119                                   Nothing -> []
1120                                   Just stub_o -> [ DotO stub_o ]
1121
1122            (hs_unlinked, unlinked_time) <-
1123              case hsc_lang of
1124
1125                 -- in interpreted mode, just return the compiled code
1126                 -- as our "unlinked" object.
1127                 HscInterpreted -> 
1128                     case maybe_interpreted_code of
1129 #ifdef GHCI
1130                        Just (bcos,itbl_env) -> do tm <- getClockTime 
1131                                                   return ([BCOs bcos itbl_env], tm)
1132 #endif
1133                        Nothing -> panic "compile: no interpreted code"
1134
1135                 -- we're in batch mode: finish the compilation pipeline.
1136                 _other -> do pipe <- genPipeline (StopBefore Ln) "" True 
1137                                         hsc_lang (output_fn, getFileSuffix output_fn)
1138                              -- runPipeline takes input_fn so it can split off 
1139                              -- the base name and use it as the base of 
1140                              -- the output object file.
1141                              let (basename, suffix) = splitFilename input_fn
1142                              (o_file,_) <- 
1143                                  pipeLoop pipe (output_fn, getFileSuffix output_fn)
1144                                                False False 
1145                                                basename suffix
1146                              o_time <- getModificationTime o_file
1147                              return ([DotO o_file], o_time)
1148
1149            let linkable = LM unlinked_time (moduleName (ms_mod summary)) 
1150                              (hs_unlinked ++ stub_unlinked)
1151
1152            return (CompOK pcs details iface (Just linkable))
1153
1154
1155 -----------------------------------------------------------------------------
1156 -- stub .h and .c files (for foreign export support)
1157
1158 compileStub dflags stub_c_exists
1159   | not stub_c_exists = return Nothing
1160   | stub_c_exists = do
1161         -- compile the _stub.c file w/ gcc
1162         let stub_c = hscStubCOutName dflags
1163         pipeline   <- genPipeline (StopBefore Ln) "" True defaultHscLang (stub_c,"c")
1164         (stub_o,_) <- runPipeline pipeline (stub_c,"c") False{-no linking-} 
1165                                   False{-no -o option-}
1166         return (Just stub_o)