[project @ 2002-01-08 14:55:50 by sof]
[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         let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
617                       | otherwise         = [ ]
618
619         excessPrecision <- readIORef v_Excess_precision
620
621         -- force the C compiler to interpret this file as C when
622         -- compiling .hc files, by adding the -x c option.
623         let langopt
624                 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
625                 | otherwise       = [ ]
626
627         SysTools.runCc (langopt ++
628                         [ SysTools.FileOption "" input_fn
629                         , SysTools.Option "-o"
630                         , SysTools.FileOption "" output_fn
631                         ]
632                        ++ map SysTools.Option (
633                           md_c_flags
634                        ++ (if cc_phase == HCc && mangle
635                              then md_regd_c_flags
636                              else [])
637                        ++ [ verb, "-S", "-Wimplicit", opt_flag ]
638                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
639                        ++ cc_opts
640                        ++ split_opt
641                        ++ (if excessPrecision then [] else [ "-ffloat-store" ])
642                        ++ include_paths
643                        ++ pkg_extra_cc_opts
644                        ))
645         return (Just output_fn)
646
647         -- ToDo: postprocess the output from gcc
648
649 -----------------------------------------------------------------------------
650 -- Mangle phase
651
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 ]
657                        else return []
658
659        SysTools.runMangle (map SysTools.Option mangler_opts
660                           ++ [ SysTools.FileOption "" input_fn
661                              , SysTools.FileOption "" output_fn
662                              ]
663                           ++ map SysTools.Option machdep_opts)
664        return (Just output_fn)
665
666 -----------------------------------------------------------------------------
667 -- Splitting phase
668
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
674
675         SysTools.runSplit [ SysTools.FileOption "" input_fn
676                           , SysTools.FileOption "" split_s_prefix
677                           , SysTools.FileOption "" n_files_fn
678                           ]
679
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)
684
685         -- Remember to delete all these files
686         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
687                         | n <- [1..n_files]]
688
689         return (Just output_fn)
690
691 -----------------------------------------------------------------------------
692 -- As phase
693
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
697
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
704                           ])
705         return (Just output_fn)
706
707 run_phase SplitAs basename _suff _input_fn output_fn
708   = do  as_opts <- getOpts opt_a
709
710         (split_s_prefix, n) <- readIORef v_Split_info
711
712         odir <- readIORef v_Output_dir
713         let real_odir = case odir of
714                                 Nothing -> basename
715                                 Just d  -> d
716
717         let assemble_file n
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
727                                     ])
728         
729         mapM_ assemble_file [1..n]
730         return (Just output_fn)
731
732 #ifdef ILX
733 -----------------------------------------------------------------------------
734 -- Ilx2Il phase
735 -- Run ilx2il over the ILX output, getting an IL file
736
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)
746
747 -----------------------------------------------------------------------------
748 -- Ilasm phase
749 -- Run ilasm over the IL, getting a DLL
750
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)
759
760 #endif -- ILX
761
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
772
773 run_phase_MoveBinary input_fn
774   = do  
775         sysMan   <- getSysMan
776         pvm_root <- getEnv "PVM_ROOT"
777         pvm_arch <- getEnv "PVM_ARCH"
778         let 
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)
787         return True
788
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 $
792  [
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 !!!!",
799   "#",
800   "$pvm_executable      = '" ++ pvm_executable ++ "';",
801   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
802   "$SysMan = '" ++ sysMan ++ "';",
803   "",
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",
811   "}", -}
812   "",
813   "# Now, run the real binary; process the args first",
814   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
815   "$debug = '';",
816   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
817   "@nonPVM_args = ();",
818   "$in_RTS_args = 0;",
819   "",
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;",
825   "    }",
826   "    if ( $a eq '-d' && $in_RTS_args ) {",
827   "     $debug = '-';",
828   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
829   "     $nprocessors = $1;",
830   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
831   "     $nprocessors = $1;",
832   "    } else {",
833   "     push(@nonPVM_args, $a);",
834   "    }",
835   "}",
836   "",
837   "local($return_val) = 0;",
838   "# Start the parallel execution by calling SysMan",
839   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
840   "$return_val = $?;",
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\";",
843   "exit($return_val);"
844  ]
845
846 -----------------------------------------------------------------------------
847 -- Complain about non-dynamic flags in OPTIONS pragmas
848
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))
854
855 -----------------------------------------------------------------------------
856 -- Linking
857
858 doLink :: [String] -> IO ()
859 doLink o_files = do
860     verb       <- getVerbFlag
861     static     <- readIORef v_Static
862     no_hs_main <- readIORef v_NoHsMain
863
864     o_file <- readIORef v_Output_file
865     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
866
867     pkg_lib_paths <- getPackageLibraryPath
868     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
869
870     lib_paths <- readIORef v_Library_paths
871     let lib_path_opts = map ("-L"++) lib_paths
872
873     pkg_libs <- getPackageLibraries
874     let imp          = if static then "" else "_imp"
875         pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
876
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
880
881     pkg_extra_ld_opts <- getPackageExtraLdOpts
882
883         -- probably _stub.o files
884     extra_ld_inputs <- readIORef v_Ld_inputs
885
886         -- opts from -optl-<blah>
887     extra_ld_opts <- getStaticOpts v_Opt_l
888
889     rts_pkg <- getPackageDetails ["rts"]
890     std_pkg <- getPackageDetails ["std"]
891     let extra_os = if static || no_hs_main
892                    then []
893                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
894                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
895
896     (md_c_flags, _) <- machdepCCOpts
897     SysTools.runLink ( [ SysTools.Option verb
898                        , SysTools.Option "-o"
899                        , SysTools.FileOption "" output_fn
900                        ]
901                       ++ map SysTools.Option (
902                          md_c_flags
903                       ++ o_files
904                       ++ extra_os
905                       ++ extra_ld_inputs
906                       ++ lib_path_opts
907                       ++ lib_opts
908                       ++ pkg_lib_path_opts
909                       ++ pkg_lib_opts
910                       ++ pkg_extra_ld_opts
911                       ++ extra_ld_opts
912                       ++ if static && not no_hs_main then
913                             [ "-u", prefixUnderscore "PrelMain_mainIO_closure",
914                               "-u", prefixUnderscore "__stginit_PrelMain"] 
915                          else []))
916
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")))
923
924 -----------------------------------------------------------------------------
925 -- Making a DLL (only for Win32)
926
927 doMkDLL :: [String] -> IO ()
928 doMkDLL o_files = do
929     verb       <- getVerbFlag
930     static     <- readIORef v_Static
931     no_hs_main <- readIORef v_NoHsMain
932
933     o_file <- readIORef v_Output_file
934     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
935
936     pkg_lib_paths <- getPackageLibraryPath
937     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
938
939     lib_paths <- readIORef v_Library_paths
940     let lib_path_opts = map ("-L"++) lib_paths
941
942     pkg_libs <- getPackageLibraries
943     let imp = if static then "" else "_imp"
944         pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
945
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
949
950     pkg_extra_ld_opts <- getPackageExtraLdOpts
951
952         -- probably _stub.o files
953     extra_ld_inputs <- readIORef v_Ld_inputs
954
955         -- opts from -optdll-<blah>
956     extra_ld_opts <- getStaticOpts v_Opt_dll
957
958     rts_pkg <- getPackageDetails ["rts"]
959     std_pkg <- getPackageDetails ["std"]
960
961     let extra_os = if static || no_hs_main
962                    then []
963                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
964                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
965
966     (md_c_flags, _) <- machdepCCOpts
967     SysTools.runMkDLL
968          ([ SysTools.Option verb
969           , SysTools.Option "-o"
970           , SysTools.FileOption "" output_fn
971           ]
972          ++ map SysTools.Option (
973             md_c_flags
974          ++ o_files
975          ++ extra_os
976          ++ [ "--target=i386-mingw32" ]
977          ++ extra_ld_inputs
978          ++ lib_path_opts
979          ++ lib_opts
980          ++ pkg_lib_path_opts
981          ++ pkg_lib_opts
982          ++ pkg_extra_ld_opts
983          ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
984                Nothing -> [ "--export-all" ]
985                Just _  -> [ "" ])
986          ++ extra_ld_opts
987         ))
988
989 -----------------------------------------------------------------------------
990 -- Just preprocess a file, put the result in a temp. file (used by the
991 -- compilation manager during the summary phase).
992
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 
999                              defaultHscLang fInfo
1000      (fn,_)   <- runPipeline pipeline fInfo
1001                              False{-no linking-} False{-no -o flag-}
1002      return fn
1003
1004 -----------------------------------------------------------------------------
1005 -- Compile a single module, under the control of the compilation manager.
1006 --
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.
1011
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.
1017
1018 -- NB.  No old interface can also mean that the source has changed.
1019
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
1028         -> IO CompResult
1029
1030 data CompResult
1031    = CompOK   PersistentCompilerState   -- updated PCS
1032               ModDetails  -- new details (HST additions)
1033               ModIface    -- new iface   (HIT additions)
1034               (Maybe Linkable)
1035                        -- new code; Nothing => compilation was not reqd
1036                        -- (old code is still valid)
1037
1038    | CompErrs PersistentCompilerState   -- updated PCS
1039
1040
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
1044
1045
1046    showPass dyn_flags 
1047         (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
1048
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)
1053
1054    when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
1055
1056    opts <- getOptionsFromSource input_fnpp
1057    processArgs dynamic_flags opts []
1058    dyn_flags <- getDynFlags
1059
1060    let hsc_lang      = hscLang dyn_flags
1061        (basename, _) = splitFilename input_fn
1062        
1063    keep_hc <- readIORef v_Keep_hc_files
1064 #ifdef ILX
1065    keep_il <- readIORef v_Keep_il_files
1066 #endif
1067    keep_s  <- readIORef v_Keep_s_files
1068
1069    output_fn <- 
1070         case hsc_lang of
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
1076 #ifdef ILX
1077            HscILX  | keep_il   -> return (basename ++ '.':phaseInputExt Ilasm)
1078                    | otherwise -> newTempName (phaseInputExt Ilx2Il)    
1079 #endif
1080            HscInterpreted      -> return (error "no output file")
1081            HscNothing          -> return (error "no output file")
1082
1083    let dyn_flags' = dyn_flags { hscOutName = output_fn,
1084                                 hscStubCOutName = basename ++ "_stub.c",
1085                                 hscStubHOutName = basename ++ "_stub.h",
1086                                 extCoreName = basename ++ ".hcr" }
1087
1088    -- figure out which header files to #include in a generated .hc file
1089    c_includes <- getPackageCIncludes
1090    cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
1091
1092    let cc_injects = unlines (map mk_include 
1093                                  (c_includes ++ reverse cmdline_includes))
1094        mk_include h_file = 
1095         case h_file of 
1096            '"':_{-"-} -> "#include "++h_file
1097            '<':_      -> "#include "++h_file
1098            _          -> "#include \""++h_file++"\""
1099
1100    writeIORef v_HCHeader cc_injects
1101
1102    -- -no-recomp should also work with --make
1103    do_recomp <- readIORef v_Recomp
1104    let source_unchanged' = source_unchanged && do_recomp
1105
1106    -- run the compiler
1107    hsc_result <- hscMain ghci_mode dyn_flags'
1108                          (ms_mod summary) location
1109                          source_unchanged' have_object old_iface hst hit pcs
1110
1111    case hsc_result of
1112       HscFail pcs -> return (CompErrs pcs)
1113
1114       HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
1115
1116       HscRecomp pcs details iface
1117         stub_h_exists stub_c_exists maybe_interpreted_code -> do
1118            
1119            let 
1120            maybe_stub_o <- compileStub dyn_flags' stub_c_exists
1121            let stub_unlinked = case maybe_stub_o of
1122                                   Nothing -> []
1123                                   Just stub_o -> [ DotO stub_o ]
1124
1125            (hs_unlinked, unlinked_time) <-
1126              case hsc_lang of
1127
1128                 -- in interpreted mode, just return the compiled code
1129                 -- as our "unlinked" object.
1130                 HscInterpreted -> 
1131                     case maybe_interpreted_code of
1132 #ifdef GHCI
1133                        Just (bcos,itbl_env) -> do tm <- getClockTime 
1134                                                   return ([BCOs bcos itbl_env], tm)
1135 #endif
1136                        Nothing -> panic "compile: no interpreted code"
1137
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
1145                              (o_file,_) <- 
1146                                  pipeLoop pipe (output_fn, getFileSuffix output_fn)
1147                                                False False 
1148                                                basename suffix
1149                              o_time <- getModificationTime o_file
1150                              return ([DotO o_file], o_time)
1151
1152            let linkable = LM unlinked_time (moduleName (ms_mod summary)) 
1153                              (hs_unlinked ++ stub_unlinked)
1154
1155            return (CompOK pcs details iface (Just linkable))
1156
1157
1158 -----------------------------------------------------------------------------
1159 -- stub .h and .c files (for foreign export support)
1160
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)