[project @ 2005-02-14 13:27:52 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/ghcconfig.h"
10
11 module DriverPipeline (
12
13         -- Interfaces for the batch-mode driver
14    compileFile, staticLink,
15
16         -- Interfaces for the compilation manager (interpreted/batch-mode)
17    preprocess, 
18    compile, CompResult(..), 
19    link, 
20
21         -- DLL building
22    doMkDLL
23   ) where
24
25 #include "HsVersions.h"
26
27 import Packages
28 import GetImports
29 import DriverState
30 import DriverUtil
31 import DriverPhases
32 import DriverFlags
33 import SysTools         ( newTempName, addFilesToClean, getSysMan, copy )
34 import qualified SysTools       
35 import HscMain
36 import Finder
37 import HscTypes
38 import Outputable
39 import Module
40 import ErrUtils
41 import CmdLineOpts
42 import Config
43 import RdrName          ( GlobalRdrEnv )
44 import Panic
45 import Util
46 import StringBuffer     ( hGetStringBuffer )
47 import BasicTypes       ( SuccessFlag(..) )
48 import Maybes           ( expectJust )
49
50 import ParserCoreUtils ( getCoreModuleName )
51
52 import EXCEPTION
53 import DATA_IOREF       ( readIORef, writeIORef )
54
55 import Directory
56 import System
57 import IO
58 import Monad
59 import Maybe
60
61
62 -- ---------------------------------------------------------------------------
63 -- Pre-process
64
65 -- Just preprocess a file, put the result in a temp. file (used by the
66 -- compilation manager during the summary phase).
67 --
68 -- We return the augmented DynFlags, because they contain the result
69 -- of slurping in the OPTIONS pragmas
70
71 preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
72 preprocess dflags filename =
73   ASSERT2(isHaskellSrcFilename filename, text filename) 
74   runPipeline anyHsc "preprocess"  dflags
75         False{-temporary output file-}
76         Nothing{-no specific output file-}
77         filename
78         Nothing{-no ModLocation-}
79
80
81
82 -- ---------------------------------------------------------------------------
83 --              Compile a file
84 --      This is used in batch mode 
85 compileFile :: GhcMode -> DynFlags -> FilePath -> IO FilePath
86 compileFile mode dflags src = do
87    exists <- doesFileExist src
88    when (not exists) $ 
89         throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
90    
91    split    <- readIORef v_Split_object_files
92    o_file   <- readIORef v_Output_file
93    ghc_link <- readIORef v_GhcLink      -- Set by -c or -no-link
94         -- When linking, the -o argument refers to the linker's output. 
95         -- otherwise, we use it as the name for the pipeline's output.
96    let maybe_o_file
97          | isLinkMode mode && not (isNoLink ghc_link) = Nothing
98                 -- -o foo applies to linker
99          | otherwise = o_file
100                 -- -o foo applies to the file we are compiling now
101
102        stop_phase = case mode of 
103                         StopBefore As | split -> SplitAs
104                         StopBefore phase      -> phase
105                         other                 -> StopLn
106
107    mode_flag_string <- readIORef v_GhcModeFlag
108    (_, out_file) <- runPipeline stop_phase mode_flag_string dflags
109                          True maybe_o_file src Nothing{-no ModLocation-}
110    return out_file
111
112
113 -- ---------------------------------------------------------------------------
114 -- Compile
115
116 -- Compile a single module, under the control of the compilation manager.
117 --
118 -- This is the interface between the compilation manager and the
119 -- compiler proper (hsc), where we deal with tedious details like
120 -- reading the OPTIONS pragma from the source file, and passing the
121 -- output of hsc through the C compiler.
122
123 -- The driver sits between 'compile' and 'hscMain', translating calls
124 -- to the former into calls to the latter, and results from the latter
125 -- into results from the former.  It does things like preprocessing
126 -- the .hs file if necessary, and compiling up the .stub_c files to
127 -- generate Linkables.
128
129 -- NB.  No old interface can also mean that the source has changed.
130
131 compile :: HscEnv
132         -> ModSummary
133         -> Bool                 -- True <=> source unchanged
134         -> Bool                 -- True <=> have object
135         -> Maybe ModIface       -- Old interface, if available
136         -> IO CompResult
137
138 data CompResult
139    = CompOK   ModDetails                -- New details
140               ModIface                  -- New iface
141               (Maybe Linkable)  -- New code; Nothing => compilation was not reqd
142                                 --                      (old code is still valid)
143
144    | CompErrs 
145
146
147 compile hsc_env mod_summary
148         source_unchanged have_object old_iface = do 
149
150    let dyn_flags   = hsc_dflags hsc_env
151        this_mod    = ms_mod mod_summary
152        src_flavour = ms_hsc_src mod_summary
153
154    showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
155
156    let verb       = verbosity dyn_flags
157    let location   = ms_location mod_summary
158    let input_fn   = expectJust "compile:hs" (ml_hs_file location) 
159    let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
160
161    when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
162
163    -- Add in the OPTIONS from the source file
164    -- This is nasty: we've done this once already, in the compilation manager
165    -- It might be better to cache the flags in the ml_hspp_file field,say
166    opts <- getOptionsFromSource input_fnpp
167    (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
168    checkProcessArgsResult unhandled_flags input_fn
169
170    let (basename, _) = splitFilename input_fn
171
172   -- We add the directory in which the .hs files resides) to the import path.
173   -- This is needed when we try to compile the .hc file later, if it
174   -- imports a _stub.h file that we created here.
175    let current_dir = directoryOf basename
176    old_paths <- readIORef v_Include_paths
177    writeIORef v_Include_paths (current_dir : old_paths)
178    -- put back the old include paths afterward.
179    later (writeIORef v_Include_paths old_paths) $ do
180
181    -- Figure out what lang we're generating
182    hsc_lang <- hscMaybeAdjustTarget StopLn src_flavour (hscTarget dyn_flags)
183    -- ... and what the next phase should be
184    next_phase <- hscNextPhase src_flavour hsc_lang
185    -- ... and what file to generate the output into
186    get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
187    output_fn     <- get_output_fn next_phase (Just location)
188
189    let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
190                                 hscOutName = output_fn,
191                                 hscStubCOutName = basename ++ "_stub.c",
192                                 hscStubHOutName = basename ++ "_stub.h",
193                                 extCoreName = basename ++ ".hcr" }
194
195    -- -no-recomp should also work with --make
196    let do_recomp = recompFlag dyn_flags
197        source_unchanged' = source_unchanged && do_recomp
198        hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
199
200    -- run the compiler
201    hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
202                          source_unchanged' have_object old_iface
203
204    case hsc_result of
205       HscFail -> return CompErrs
206
207       HscNoRecomp details iface -> return (CompOK details iface Nothing)
208
209       HscRecomp details iface
210                 stub_h_exists stub_c_exists maybe_interpreted_code 
211
212         | isHsBoot src_flavour  -- No further compilation to do
213         -> return (CompOK details iface Nothing)
214
215         | otherwise             -- Normal Haskell source files
216         -> do
217            let 
218            maybe_stub_o <- compileStub dyn_flags' stub_c_exists
219            let stub_unlinked = case maybe_stub_o of
220                                   Nothing -> []
221                                   Just stub_o -> [ DotO stub_o ]
222
223            (hs_unlinked, unlinked_time) <-
224              case hsc_lang of
225
226                 -- in interpreted mode, just return the compiled code
227                 -- as our "unlinked" object.
228                 HscInterpreted -> 
229                     case maybe_interpreted_code of
230 #ifdef GHCI
231                        Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
232                         -- Why do we use the timestamp of the source file here,
233                         -- rather than the current time?  This works better in
234                         -- the case where the local clock is out of sync
235                         -- with the filesystem's clock.  It's just as accurate:
236                         -- if the source is modified, then the linkable will
237                         -- be out of date.
238 #endif
239                        Nothing -> panic "compile: no interpreted code"
240
241                 -- we're in batch mode: finish the compilation pipeline.
242                 _other -> do
243                    let object_filename = ml_obj_file location
244
245                    runPipeline StopLn "" dyn_flags
246                                True Nothing output_fn (Just location)
247                         -- the object filename comes from the ModLocation
248
249                    o_time <- getModificationTime object_filename
250                    return ([DotO object_filename], o_time)
251
252            let linkable = LM unlinked_time this_mod
253                              (hs_unlinked ++ stub_unlinked)
254
255            return (CompOK details iface (Just linkable))
256
257 -----------------------------------------------------------------------------
258 -- stub .h and .c files (for foreign export support)
259
260 compileStub dflags stub_c_exists
261   | not stub_c_exists = return Nothing
262   | stub_c_exists = do
263         -- compile the _stub.c file w/ gcc
264         let stub_c = hscStubCOutName dflags
265         (_, stub_o) <- runPipeline StopLn "stub-compile" dflags
266                             True{-persistent output-} 
267                             Nothing{-no specific output file-}
268                             stub_c
269                             Nothing{-no ModLocation-}
270         return (Just stub_o)
271
272
273 -- ---------------------------------------------------------------------------
274 -- Link
275
276 link :: GhciMode                -- interactive or batch
277      -> DynFlags                -- dynamic flags
278      -> Bool                    -- attempt linking in batch mode?
279      -> HomePackageTable        -- what to link
280      -> IO SuccessFlag
281
282 -- For the moment, in the batch linker, we don't bother to tell doLink
283 -- which packages to link -- it just tries all that are available.
284 -- batch_attempt_linking should only be *looked at* in batch mode.  It
285 -- should only be True if the upsweep was successful and someone
286 -- exports main, i.e., we have good reason to believe that linking
287 -- will succeed.
288
289 #ifdef GHCI
290 link Interactive dflags batch_attempt_linking hpt
291     = do -- Not Linking...(demand linker will do the job)
292          return Succeeded
293 #endif
294
295 link Batch dflags batch_attempt_linking hpt
296    | batch_attempt_linking
297    = do 
298         let 
299             home_mod_infos = moduleEnvElts hpt
300
301             -- the packages we depend on
302             pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
303
304             -- the linkables to link
305             linkables = map hm_linkable home_mod_infos
306
307         when (verb >= 3) $ do
308              hPutStrLn stderr "link: linkables are ..."
309              hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
310
311         -- check for the -no-link flag
312         ghc_link <- readIORef v_GhcLink
313         if isNoLink ghc_link
314           then do when (verb >= 3) $
315                     hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
316                   return Succeeded
317           else do
318
319         when (verb >= 1) $
320              hPutStrLn stderr "Linking ..."
321
322         let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
323             obj_files = concatMap getOfiles linkables
324
325         -- Don't showPass in Batch mode; doLink will do that for us.
326         staticLink dflags obj_files pkg_deps
327
328         when (verb >= 3) (hPutStrLn stderr "link: done")
329
330         -- staticLink only returns if it succeeds
331         return Succeeded
332
333    | otherwise
334    = do when (verb >= 3) $ do
335             hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
336             hPutStrLn stderr "   Main.main not exported; not linking."
337         return Succeeded
338    where
339       verb = verbosity dflags
340       
341 -- ---------------------------------------------------------------------------
342 -- Run a compilation pipeline, consisting of multiple phases.
343
344 -- The DynFlags can be modified by phases in the pipeline (eg. by
345 -- OPTIONS pragmas), and the changes affect later phases in the
346 -- pipeline, but we throw away the resulting DynFlags at the end.
347
348 runPipeline
349   :: Phase              -- When to stop
350   -> String             -- "GhcMode" flag as a string
351   -> DynFlags           -- Dynamic flags
352   -> Bool               -- Final output is persistent?
353   -> Maybe FilePath     -- Where to put the output, optionally
354   -> FilePath           -- Input filename
355   -> Maybe ModLocation  -- A ModLocation for this module, if we have one
356   -> IO (DynFlags, FilePath)    -- (final flags, output filename)
357
358 runPipeline stop_phase mode_flag_string dflags keep_output 
359   maybe_output_filename input_fn maybe_loc
360   = do
361   let (basename, suffix) = splitFilename input_fn
362       start_phase = startPhase suffix
363
364   -- We want to catch cases of "you can't get there from here" before
365   -- we start the pipeline, because otherwise it will just run off the
366   -- end.
367   --
368   -- There is a partial ordering on phases, where A < B iff A occurs
369   -- before B in a normal compilation pipeline.
370
371   when (not (start_phase `happensBefore` stop_phase)) $
372         throwDyn (UsageError 
373                     ("flag `" ++ mode_flag_string
374                      ++ "' is incompatible with source file `"
375                      ++ input_fn ++ "'"))
376
377   -- generate a function which will be used to calculate output file names
378   -- as we go along.
379   get_output_fn <- genOutputFilenameFunc stop_phase keep_output 
380                                          maybe_output_filename basename
381
382   -- Execute the pipeline...
383   (dflags', output_fn, maybe_loc) <- pipeLoop dflags start_phase stop_phase input_fn 
384                                               basename suffix get_output_fn maybe_loc
385
386   -- Sometimes, a compilation phase doesn't actually generate any output
387   -- (eg. the CPP phase when -fcpp is not turned on).  If we end on this
388   -- stage, but we wanted to keep the output, then we have to explicitly
389   -- copy the file.
390   if keep_output 
391         then do final_fn <- get_output_fn stop_phase maybe_loc
392                 when (final_fn /= output_fn) $
393                   copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
394                         ++ "'") output_fn final_fn
395                 return (dflags', final_fn)
396         else
397                 return (dflags', output_fn)
398
399
400 pipeLoop :: DynFlags -> Phase -> Phase 
401          -> FilePath  -> String -> Suffix
402          -> (Phase -> Maybe ModLocation -> IO FilePath)
403          -> Maybe ModLocation
404          -> IO (DynFlags, FilePath, Maybe ModLocation)
405
406 pipeLoop dflags phase stop_phase 
407          input_fn orig_basename orig_suff 
408          orig_get_output_fn maybe_loc
409
410   | phase `eqPhase` stop_phase            -- All done
411   = return (dflags, input_fn, maybe_loc)
412
413   | not (phase `happensBefore` stop_phase)
414         -- Something has gone wrong.  We'll try to cover all the cases when
415         -- this could happen, so if we reach here it is a panic.
416         -- eg. it might happen if the -C flag is used on a source file that
417         -- has {-# OPTIONS -fasm #-}.
418   = panic ("pipeLoop: at phase " ++ show phase ++ 
419            " but I wanted to stop at phase " ++ show stop_phase)
420
421   | otherwise 
422   = do  { (next_phase, dflags', maybe_loc, output_fn)
423                 <- runPhase phase stop_phase dflags orig_basename 
424                             orig_suff input_fn orig_get_output_fn maybe_loc
425         ; pipeLoop dflags' next_phase stop_phase output_fn
426                    orig_basename orig_suff orig_get_output_fn maybe_loc }
427
428 genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
429   -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
430 genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
431  = do
432    hcsuf      <- readIORef v_HC_suf
433    odir       <- readIORef v_Output_dir
434    osuf       <- readIORef v_Object_suf
435    keep_hc    <- readIORef v_Keep_hc_files
436 #ifdef ILX
437    keep_il    <- readIORef v_Keep_il_files
438    keep_ilx   <- readIORef v_Keep_ilx_files
439 #endif
440    keep_raw_s <- readIORef v_Keep_raw_s_files
441    keep_s     <- readIORef v_Keep_s_files
442    let
443         myPhaseInputExt HCc    = hcsuf
444         myPhaseInputExt StopLn = osuf
445         myPhaseInputExt other  = phaseInputExt other
446
447         func next_phase maybe_location
448                 | is_last_phase, Just f <- maybe_output_filename = return f
449                 | is_last_phase && keep_final_output = persistent_fn
450                 | keep_this_output                   = persistent_fn
451                 | otherwise                          = newTempName suffix
452
453            where
454                 is_last_phase = next_phase `eqPhase` stop_phase
455
456                 -- sometimes, we keep output from intermediate stages
457                 keep_this_output = 
458                      case next_phase of
459                              StopLn              -> True
460                              Mangle | keep_raw_s -> True
461                              As     | keep_s     -> True
462                              HCc    | keep_hc    -> True
463                              _other              -> False
464
465                 suffix = myPhaseInputExt next_phase
466
467                 -- persistent object files get put in odir
468                 persistent_fn 
469                    | StopLn <- next_phase = return odir_persistent
470                    | otherwise            = return persistent
471
472                 persistent = basename ++ '.':suffix
473
474                 odir_persistent
475                    | Just loc <- maybe_location = ml_obj_file loc
476                    | Just d <- odir = replaceFilenameDirectory persistent d
477                    | otherwise      = persistent
478
479    return func
480
481
482 -- -----------------------------------------------------------------------------
483 -- Each phase in the pipeline returns the next phase to execute, and the
484 -- name of the file in which the output was placed.
485 --
486 -- We must do things dynamically this way, because we often don't know
487 -- what the rest of the phases will be until part-way through the
488 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
489 -- of a source file can change the latter stages of the pipeline from
490 -- taking the via-C route to using the native code generator.
491
492 runPhase :: Phase       -- Do this phase first
493          -> Phase       -- Stop just before this phase
494          -> DynFlags
495          -> String      -- basename of original input source
496          -> String      -- its extension
497          -> FilePath    -- name of file which contains the input to this phase.
498          -> (Phase -> Maybe ModLocation -> IO FilePath)
499                         -- how to calculate the output filename
500          -> Maybe ModLocation           -- the ModLocation, if we have one
501          -> IO (Phase,                  -- next phase
502                 DynFlags,               -- new dynamic flags
503                 Maybe ModLocation,      -- the ModLocation, if we have one
504                 FilePath)               -- output filename
505
506         -- Invariant: the output filename always contains the output
507         -- Interesting case: Hsc when there is no recompilation to do
508         --                   Then the output filename is still a .o file 
509
510 -------------------------------------------------------------------------------
511 -- Unlit phase 
512
513 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
514   = do let unlit_flags = getOpts dflags opt_L
515        -- The -h option passes the file name for unlit to put in a #line directive
516        output_fn <- get_output_fn (Cpp sf) maybe_loc
517
518        SysTools.runUnlit dflags 
519                 (map SysTools.Option unlit_flags ++
520                           [ SysTools.Option     "-h"
521                           , SysTools.Option     input_fn
522                           , SysTools.FileOption "" input_fn
523                           , SysTools.FileOption "" output_fn
524                           ])
525
526        return (Cpp sf, dflags, maybe_loc, output_fn)
527
528 -------------------------------------------------------------------------------
529 -- Cpp phase : (a) gets OPTIONS out of file
530 --             (b) runs cpp if necessary
531
532 runPhase (Cpp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
533   = do src_opts <- getOptionsFromSource input_fn
534        (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
535        checkProcessArgsResult unhandled_flags (basename++'.':suff)
536
537        if not (cppFlag dflags) then
538            -- no need to preprocess CPP, just pass input file along
539            -- to the next phase of the pipeline.
540           return (HsPp sf, dflags, maybe_loc, input_fn)
541         else do
542             output_fn <- get_output_fn (HsPp sf) maybe_loc
543             doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
544             return (HsPp sf, dflags, maybe_loc, output_fn)
545
546 -------------------------------------------------------------------------------
547 -- HsPp phase 
548
549 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
550   = do if not (ppFlag dflags) then
551            -- no need to preprocess, just pass input file along
552            -- to the next phase of the pipeline.
553           return (Hsc sf, dflags, maybe_loc, input_fn)
554         else do
555             let hspp_opts = getOpts dflags opt_F
556             hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
557             let orig_fn = basename ++ '.':suff
558             output_fn <- get_output_fn (Hsc sf) maybe_loc
559             SysTools.runPp dflags
560                            ( [ SysTools.Option     orig_fn
561                              , SysTools.Option     input_fn
562                              , SysTools.FileOption "" output_fn
563                              ] ++
564                              map SysTools.Option hs_src_pp_opts ++
565                              map SysTools.Option hspp_opts
566                            )
567             return (Hsc sf, dflags, maybe_loc, output_fn)
568
569 -----------------------------------------------------------------------------
570 -- Hsc phase
571
572 -- Compilation of a single module, in "legacy" mode (_not_ under
573 -- the direction of the compilation manager).
574 runPhase (Hsc src_flavour) stop dflags basename suff input_fn get_output_fn _maybe_loc 
575  = do   -- normal Hsc mode, not mkdependHS
576
577   -- we add the current directory (i.e. the directory in which
578   -- the .hs files resides) to the import path, since this is
579   -- what gcc does, and it's probably what you want.
580         let current_dir = directoryOf basename
581         
582         paths <- readIORef v_Include_paths
583         writeIORef v_Include_paths (current_dir : paths)
584         
585   -- gather the imports and module name
586         (hspp_buf,mod_name) <- 
587             case src_flavour of
588                 ExtCoreFile -> do {  -- no explicit imports in ExtCore input.
589                                   ; m <- getCoreModuleName input_fn
590                                   ; return (Nothing, mkModule m) }
591
592                 other -> do { buf <- hGetStringBuffer input_fn
593                             ; (_,_,mod_name) <- getImports dflags buf input_fn
594                             ; return (Just buf, mod_name) }
595
596   -- Build a ModLocation to pass to hscMain.
597   -- The source filename is rather irrelevant by now, but it's used
598   -- by hscMain for messages.  hscMain also needs 
599   -- the .hi and .o filenames, and this is as good a way
600   -- as any to generate them, and better than most. (e.g. takes 
601   -- into accout the -osuf flags)
602         location1 <- mkHomeModLocation2 mod_name basename suff
603
604   -- Boot-ify it if necessary
605         let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
606                       | otherwise            = location1 
607                                         
608
609   -- Take -ohi into account if present
610   -- This can't be done in mkHomeModuleLocation because
611   -- it only applies to the module being compiles
612         ohi <- readIORef v_Output_hi
613         let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
614                       | otherwise      = location2
615
616   -- Take -o into account if present
617   -- Very like -ohi, but we must *only* do this if we aren't linking
618   -- (If we're linking then the -o applies to the linked thing, not to
619   -- the object file for one module.)
620   -- Note the nasty duplication with the same computation in compileFile above
621         expl_o_file <- readIORef v_Output_file
622         ghc_link     <- readIORef v_GhcLink
623         let location4 | Just ofile <- expl_o_file
624                       , isNoLink ghc_link 
625                       = location3 { ml_obj_file = ofile }
626                       | otherwise = location3
627
628   -- Tell the finder cache about this module
629         addHomeModuleToFinder mod_name location4
630
631   -- Make the ModSummary to hand to hscMain
632         src_timestamp <- getModificationTime (basename ++ '.':suff)
633         let
634             unused_field = panic "runPhase:ModSummary field"
635                 -- Some fields are not looked at by hscMain
636             mod_summary = ModSummary {  ms_mod       = mod_name, 
637                                         ms_hsc_src   = src_flavour,
638                                         ms_hspp_file = Just input_fn,
639                                         ms_hspp_buf  = hspp_buf,
640                                         ms_location  = location4,
641                                         ms_hs_date   = src_timestamp,
642                                         ms_imps      = unused_field,
643                                         ms_srcimps   = unused_field }
644
645             o_file = ml_obj_file location4      -- The real object file
646
647
648   -- Figure out if the source has changed, for recompilation avoidance.
649   --
650   -- Setting source_unchanged to True means that M.o seems
651   -- to be up to date wrt M.hs; so no need to recompile unless imports have
652   -- changed (which the compiler itself figures out).
653   -- Setting source_unchanged to False tells the compiler that M.o is out of
654   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
655         let do_recomp = recompFlag dflags
656         source_unchanged <- 
657           if not do_recomp || not (isStopLn stop)
658                 -- Set source_unchanged to False unconditionally if
659                 --      (a) recompilation checker is off, or
660                 --      (b) we aren't going all the way to .o file (e.g. ghc -S)
661              then return False  
662                 -- Otherwise look at file modification dates
663              else do o_file_exists <- doesFileExist o_file
664                      if not o_file_exists
665                         then return False       -- Need to recompile
666                         else do t2 <- getModificationTime o_file
667                                 if t2 > src_timestamp
668                                   then return True
669                                   else return False
670
671   -- get the DynFlags
672         hsc_lang   <- hscMaybeAdjustTarget stop src_flavour (hscTarget dflags)
673         next_phase <- hscNextPhase src_flavour hsc_lang
674         output_fn  <- get_output_fn next_phase (Just location4)
675
676         let dflags' = dflags { hscTarget = hsc_lang,
677                                hscOutName = output_fn,
678                                hscStubCOutName = basename ++ "_stub.c",
679                                hscStubHOutName = basename ++ "_stub.h",
680                                extCoreName = basename ++ ".hcr" }
681
682         hsc_env <- newHscEnv OneShot dflags'
683
684   -- run the compiler!
685         result <- hscMain hsc_env printErrorsAndWarnings
686                           mod_summary source_unchanged 
687                           False         -- No object file
688                           Nothing       -- No iface
689
690         case result of
691
692             HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
693
694             HscNoRecomp details iface -> do
695                 SysTools.touch dflags' "Touching object file" o_file
696                 return (StopLn, dflags', Just location4, o_file)
697
698             HscRecomp _details _iface 
699                       stub_h_exists stub_c_exists
700                       _maybe_interpreted_code -> do
701
702                 -- Deal with stubs 
703                 maybe_stub_o <- compileStub dflags' stub_c_exists
704                 case maybe_stub_o of
705                       Nothing     -> return ()
706                       Just stub_o -> add v_Ld_inputs stub_o
707
708                 -- In the case of hs-boot files, generate a dummy .o-boot 
709                 -- stamp file for the benefit of Make
710                 case src_flavour of
711                   HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
712                   other      -> return ()
713
714                 return (next_phase, dflags', Just location4, output_fn)
715
716 -----------------------------------------------------------------------------
717 -- Cmm phase
718
719 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
720   = do
721        output_fn <- get_output_fn Cmm maybe_loc
722        doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn 
723        return (Cmm, dflags, maybe_loc, output_fn)
724
725 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
726   = do
727         hsc_lang <- hscMaybeAdjustTarget stop HsSrcFile (hscTarget dflags)
728         next_phase <- hscNextPhase HsSrcFile hsc_lang
729         output_fn <- get_output_fn next_phase maybe_loc
730
731         let dflags' = dflags { hscTarget = hsc_lang,
732                                hscOutName = output_fn,
733                                hscStubCOutName = basename ++ "_stub.c",
734                                hscStubHOutName = basename ++ "_stub.h",
735                                extCoreName = basename ++ ".hcr" }
736
737         ok <- hscCmmFile dflags' input_fn
738
739         when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
740
741         return (next_phase, dflags, maybe_loc, output_fn)
742
743 -----------------------------------------------------------------------------
744 -- Cc phase
745
746 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
747 -- way too many hacks, and I can't say I've ever used it anyway.
748
749 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
750    | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
751    = do let cc_opts = getOpts dflags opt_c
752             hcc = cc_phase `eqPhase` HCc
753
754         cmdline_include_paths <- readIORef v_Include_paths
755
756         -- HC files have the dependent packages stamped into them
757         pkgs <- if hcc then getHCFilePackages input_fn else return []
758
759         -- add package include paths even if we're just compiling .c
760         -- files; this is the Value Add(TM) that using ghc instead of
761         -- gcc gives you :)
762         pkg_include_dirs <- getPackageIncludePath dflags pkgs
763         let include_paths = foldr (\ x xs -> "-I" : x : xs) []
764                               (cmdline_include_paths ++ pkg_include_dirs)
765
766         (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
767         pic_c_flags <- picCCOpts dflags
768
769         let verb = getVerbFlag dflags
770
771         pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
772
773         split_objs <- readIORef v_Split_object_files
774         let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
775                       | otherwise         = [ ]
776
777         excessPrecision <- readIORef v_Excess_precision
778
779         -- Decide next phase
780         mangle <- readIORef v_Do_asm_mangling
781         let next_phase
782                 | hcc && mangle     = Mangle
783                 | otherwise         = As
784         output_fn <- get_output_fn next_phase maybe_loc
785
786         -- force the C compiler to interpret this file as C when
787         -- compiling .hc files, by adding the -x c option.
788         let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
789                     | otherwise = [ ]
790
791         SysTools.runCc dflags (langopt ++
792                         [ SysTools.FileOption "" input_fn
793                         , SysTools.Option "-o"
794                         , SysTools.FileOption "" output_fn
795                         ]
796                        ++ map SysTools.Option (
797                           md_c_flags
798                        ++ pic_c_flags
799                        ++ (if hcc && mangle
800                              then md_regd_c_flags
801                              else [])
802                        ++ [ verb, "-S", "-Wimplicit", "-O" ]
803                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
804                        ++ cc_opts
805                        ++ split_opt
806                        ++ (if excessPrecision then [] else [ "-ffloat-store" ])
807                        ++ include_paths
808                        ++ pkg_extra_cc_opts
809                        ))
810
811         return (next_phase, dflags, maybe_loc, output_fn)
812
813         -- ToDo: postprocess the output from gcc
814
815 -----------------------------------------------------------------------------
816 -- Mangle phase
817
818 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
819    = do let mangler_opts = getOpts dflags opt_m
820
821 #if i386_TARGET_ARCH
822         machdep_opts <- return [ show (stolen_x86_regs dflags) ]
823 #else
824         machdep_opts <- return []
825 #endif
826
827         split <- readIORef v_Split_object_files
828         let next_phase
829                 | split = SplitMangle
830                 | otherwise = As
831         output_fn <- get_output_fn next_phase maybe_loc
832
833         SysTools.runMangle dflags (map SysTools.Option mangler_opts
834                           ++ [ SysTools.FileOption "" input_fn
835                              , SysTools.FileOption "" output_fn
836                              ]
837                           ++ map SysTools.Option machdep_opts)
838
839         return (next_phase, dflags, maybe_loc, output_fn)
840
841 -----------------------------------------------------------------------------
842 -- Splitting phase
843
844 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
845   = do  -- tmp_pfx is the prefix used for the split .s files
846         -- We also use it as the file to contain the no. of split .s files (sigh)
847         split_s_prefix <- SysTools.newTempName "split"
848         let n_files_fn = split_s_prefix
849
850         SysTools.runSplit dflags
851                           [ SysTools.FileOption "" input_fn
852                           , SysTools.FileOption "" split_s_prefix
853                           , SysTools.FileOption "" n_files_fn
854                           ]
855
856         -- Save the number of split files for future references
857         s <- readFile n_files_fn
858         let n_files = read s :: Int
859         writeIORef v_Split_info (split_s_prefix, n_files)
860
861         -- Remember to delete all these files
862         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
863                         | n <- [1..n_files]]
864
865         return (SplitAs, dflags, maybe_loc, "**splitmangle**")
866           -- we don't use the filename
867
868 -----------------------------------------------------------------------------
869 -- As phase
870
871 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
872   = do  let as_opts =  getOpts dflags opt_a
873         cmdline_include_paths <- readIORef v_Include_paths
874
875         output_fn <- get_output_fn StopLn maybe_loc
876
877         -- we create directories for the object file, because it
878         -- might be a hierarchical module.
879         createDirectoryHierarchy (directoryOf output_fn)
880
881         SysTools.runAs dflags   
882                        (map SysTools.Option as_opts
883                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
884                        ++ [ SysTools.Option "-c"
885                           , SysTools.FileOption "" input_fn
886                           , SysTools.Option "-o"
887                           , SysTools.FileOption "" output_fn
888                           ])
889
890         return (StopLn, dflags, maybe_loc, output_fn)
891
892
893 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
894   = do  let as_opts = getOpts dflags opt_a
895
896         (split_s_prefix, n) <- readIORef v_Split_info
897
898         odir <- readIORef v_Output_dir
899         let real_odir = case odir of
900                                 Nothing -> basename ++ "_split"
901                                 Just d  -> d
902
903         let assemble_file n
904               = do  let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
905                     let output_o = replaceFilenameDirectory
906                                         (basename ++ "__" ++ show n ++ ".o")
907                                          real_odir
908                     real_o <- osuf_ify output_o
909                     SysTools.runAs dflags
910                                  (map SysTools.Option as_opts ++
911                                     [ SysTools.Option "-c"
912                                     , SysTools.Option "-o"
913                                     , SysTools.FileOption "" real_o
914                                     , SysTools.FileOption "" input_s
915                                     ])
916         
917         mapM_ assemble_file [1..n]
918
919         output_fn <- get_output_fn StopLn maybe_loc
920         return (StopLn, dflags, maybe_loc, output_fn)
921
922 #ifdef ILX
923 -----------------------------------------------------------------------------
924 -- Ilx2Il phase
925 -- Run ilx2il over the ILX output, getting an IL file
926
927 runPhase Ilx2Il stop dflags _basename _suff input_fn get_output_fn maybe_loc
928   = do  let ilx2il_opts = getOpts dflags opt_I
929         SysTools.runIlx2il (map SysTools.Option ilx2il_opts
930                            ++ [ SysTools.Option "--no-add-suffix-to-assembly",
931                                 SysTools.Option "mscorlib",
932                                 SysTools.Option "-o",
933                                 SysTools.FileOption "" output_fn,
934                                 SysTools.FileOption "" input_fn ])
935         return True
936
937 -----------------------------------------------------------------------------
938 -- Ilasm phase
939 -- Run ilasm over the IL, getting a DLL
940
941 runPhase Ilasm stop dflags _basename _suff input_fn get_output_fn maybe_loc
942   = do  let ilasm_opts = getOpts dflags opt_i
943         SysTools.runIlasm (map SysTools.Option ilasm_opts
944                            ++ [ SysTools.Option "/QUIET",
945                                 SysTools.Option "/DLL",
946                                 SysTools.FileOption "/OUT=" output_fn,
947                                 SysTools.FileOption "" input_fn ])
948         return True
949
950 #endif /* ILX */
951
952 -----------------------------------------------------------------------------
953 -- MoveBinary sort-of-phase
954 -- After having produced a binary, move it somewhere else and generate a
955 -- wrapper script calling the binary. Currently, we need this only in 
956 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
957 -- central directory.
958 -- This is called from staticLink below, after linking. I haven't made it
959 -- a separate phase to minimise interfering with other modules, and
960 -- we don't need the generality of a phase (MoveBinary is always
961 -- done after linking and makes only sense in a parallel setup)   -- HWL
962
963 runPhase_MoveBinary input_fn
964   = do  
965         sysMan   <- getSysMan
966         pvm_root <- getEnv "PVM_ROOT"
967         pvm_arch <- getEnv "PVM_ARCH"
968         let 
969            pvm_executable_base = "=" ++ input_fn
970            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
971         -- nuke old binary; maybe use configur'ed names for cp and rm?
972         system ("rm -f " ++ pvm_executable)
973         -- move the newly created binary into PVM land
974         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
975         -- generate a wrapper script for running a parallel prg under PVM
976         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
977         return True
978
979 -- generates a Perl skript starting a parallel prg under PVM
980 mk_pvm_wrapper_script :: String -> String -> String -> String
981 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
982  [
983   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
984   "  if $running_under_some_shell;",
985   "# =!=!=!=!=!=!=!=!=!=!=!",
986   "# This script is automatically generated: DO NOT EDIT!!!",
987   "# Generated by Glasgow Haskell Compiler",
988   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
989   "#",
990   "$pvm_executable      = '" ++ pvm_executable ++ "';",
991   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
992   "$SysMan = '" ++ sysMan ++ "';",
993   "",
994   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
995   "# first, some magical shortcuts to run "commands" on the binary",
996   "# (which is hidden)",
997   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
998   "    local($cmd) = $1;",
999   "    system("$cmd $pvm_executable");",
1000   "    exit(0); # all done",
1001   "}", -}
1002   "",
1003   "# Now, run the real binary; process the args first",
1004   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
1005   "$debug = '';",
1006   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1007   "@nonPVM_args = ();",
1008   "$in_RTS_args = 0;",
1009   "",
1010   "args: while ($a = shift(@ARGV)) {",
1011   "    if ( $a eq '+RTS' ) {",
1012   "     $in_RTS_args = 1;",
1013   "    } elsif ( $a eq '-RTS' ) {",
1014   "     $in_RTS_args = 0;",
1015   "    }",
1016   "    if ( $a eq '-d' && $in_RTS_args ) {",
1017   "     $debug = '-';",
1018   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1019   "     $nprocessors = $1;",
1020   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1021   "     $nprocessors = $1;",
1022   "    } else {",
1023   "     push(@nonPVM_args, $a);",
1024   "    }",
1025   "}",
1026   "",
1027   "local($return_val) = 0;",
1028   "# Start the parallel execution by calling SysMan",
1029   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1030   "$return_val = $?;",
1031   "# ToDo: fix race condition moving files and flushing them!!",
1032   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1033   "exit($return_val);"
1034  ]
1035
1036 -----------------------------------------------------------------------------
1037 -- Complain about non-dynamic flags in OPTIONS pragmas
1038
1039 checkProcessArgsResult flags filename
1040   = do when (notNull flags) (throwDyn (ProgramError (
1041           showSDoc (hang (text filename <> char ':')
1042                       4 (text "unknown flags in  {-# OPTIONS #-} pragma:" <+>
1043                           hsep (map text flags)))
1044         )))
1045
1046 -----------------------------------------------------------------------------
1047 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1048
1049 getHCFilePackages :: FilePath -> IO [PackageId]
1050 getHCFilePackages filename =
1051   EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1052     l <- hGetLine h
1053     case l of
1054       '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1055           return (map stringToPackageId (words rest))
1056       _other ->
1057           return []
1058
1059 -----------------------------------------------------------------------------
1060 -- Static linking, of .o files
1061
1062 -- The list of packages passed to link is the list of packages on
1063 -- which this program depends, as discovered by the compilation
1064 -- manager.  It is combined with the list of packages that the user
1065 -- specifies on the command line with -package flags.  
1066 --
1067 -- In one-shot linking mode, we can't discover the package
1068 -- dependencies (because we haven't actually done any compilation or
1069 -- read any interface files), so the user must explicitly specify all
1070 -- the packages.
1071
1072 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1073 staticLink dflags o_files dep_packages = do
1074     let verb = getVerbFlag dflags
1075     static     <- readIORef v_Static
1076     no_hs_main <- readIORef v_NoHsMain
1077
1078     -- get the full list of packages to link with, by combining the
1079     -- explicit packages with the auto packages and all of their
1080     -- dependencies, and eliminating duplicates.
1081
1082     o_file <- readIORef v_Output_file
1083 #if defined(mingw32_HOST_OS)
1084     let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1085 #else
1086     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1087 #endif
1088
1089     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1090     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1091
1092     lib_paths <- readIORef v_Library_paths
1093     let lib_path_opts = map ("-L"++) lib_paths
1094
1095     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1096
1097 #ifdef darwin_TARGET_OS
1098     pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1099     let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1100
1101     framework_paths <- readIORef v_Framework_paths
1102     let framework_path_opts = map ("-F"++) framework_paths
1103
1104     pkg_frameworks <- getPackageFrameworks dflags dep_packages
1105     let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1106     frameworks <- readIORef v_Cmdline_frameworks
1107     let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1108          -- reverse because they're added in reverse order from the cmd line
1109 #endif
1110
1111         -- probably _stub.o files
1112     extra_ld_inputs <- readIORef v_Ld_inputs
1113
1114         -- opts from -optl-<blah> (including -l<blah> options)
1115     extra_ld_opts <- getStaticOpts v_Opt_l
1116
1117     ways <- readIORef v_Ways
1118
1119     -- Here are some libs that need to be linked at the *end* of
1120     -- the command line, because they contain symbols that are referred to
1121     -- by the RTS.  We can't therefore use the ordinary way opts for these.
1122     let
1123         debug_opts | WayDebug `elem` ways = [ 
1124 #if defined(HAVE_LIBBFD)
1125                         "-lbfd", "-liberty"
1126 #endif
1127                          ]
1128                    | otherwise            = []
1129
1130     let
1131         thread_opts | WayThreaded `elem` ways = [ 
1132 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1133                         "-lpthread"
1134 #endif
1135 #if defined(osf3_TARGET_OS)
1136                         , "-lexc"
1137 #endif
1138                         ]
1139                     | otherwise               = []
1140
1141     (md_c_flags, _) <- machdepCCOpts dflags
1142     SysTools.runLink dflags ( 
1143                        [ SysTools.Option verb
1144                        , SysTools.Option "-o"
1145                        , SysTools.FileOption "" output_fn
1146                        ]
1147                       ++ map SysTools.Option (
1148                          md_c_flags
1149                       ++ o_files
1150                       ++ extra_ld_inputs
1151                       ++ lib_path_opts
1152                       ++ extra_ld_opts
1153 #ifdef darwin_TARGET_OS
1154                       ++ framework_path_opts
1155                       ++ framework_opts
1156 #endif
1157                       ++ pkg_lib_path_opts
1158                       ++ pkg_link_opts
1159 #ifdef darwin_TARGET_OS
1160                       ++ pkg_framework_path_opts
1161                       ++ pkg_framework_opts
1162 #endif
1163                       ++ debug_opts
1164                       ++ thread_opts
1165                     ))
1166
1167     -- parallel only: move binary to another dir -- HWL
1168     ways_ <- readIORef v_Ways
1169     when (WayPar `elem` ways_)
1170          (do success <- runPhase_MoveBinary output_fn
1171              if success then return ()
1172                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1173
1174 -----------------------------------------------------------------------------
1175 -- Making a DLL (only for Win32)
1176
1177 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1178 doMkDLL dflags o_files dep_packages = do
1179     let verb = getVerbFlag dflags
1180     static     <- readIORef v_Static
1181     no_hs_main <- readIORef v_NoHsMain
1182
1183     o_file <- readIORef v_Output_file
1184     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1185
1186     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1187     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1188
1189     lib_paths <- readIORef v_Library_paths
1190     let lib_path_opts = map ("-L"++) lib_paths
1191
1192     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1193
1194         -- probably _stub.o files
1195     extra_ld_inputs <- readIORef v_Ld_inputs
1196
1197         -- opts from -optdll-<blah>
1198     extra_ld_opts <- getStaticOpts v_Opt_dll
1199
1200     let pstate = pkgState dflags
1201         rts_id | ExtPackage id <- rtsPackageId pstate = id
1202                | otherwise = panic "staticLink: rts package missing"
1203         base_id | ExtPackage id <- basePackageId pstate = id
1204                 | otherwise = panic "staticLink: base package missing"
1205         rts_pkg  = getPackageDetails pstate rts_id
1206         base_pkg = getPackageDetails pstate base_id
1207
1208     let extra_os = if static || no_hs_main
1209                    then []
1210                    else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1211                           head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1212
1213     (md_c_flags, _) <- machdepCCOpts dflags
1214     SysTools.runMkDLL dflags
1215          ([ SysTools.Option verb
1216           , SysTools.Option "-o"
1217           , SysTools.FileOption "" output_fn
1218           ]
1219          ++ map SysTools.Option (
1220             md_c_flags
1221          ++ o_files
1222          ++ extra_os
1223          ++ [ "--target=i386-mingw32" ]
1224          ++ extra_ld_inputs
1225          ++ lib_path_opts
1226          ++ extra_ld_opts
1227          ++ pkg_lib_path_opts
1228          ++ pkg_link_opts
1229          ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1230                then [ "" ]
1231                else [ "--export-all" ])
1232         ))
1233
1234 -- -----------------------------------------------------------------------------
1235 -- Misc.
1236
1237 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1238 doCpp dflags raw include_cc_opts input_fn output_fn = do
1239     let hscpp_opts = getOpts dflags opt_P
1240
1241     cmdline_include_paths <- readIORef v_Include_paths
1242
1243     pkg_include_dirs <- getPackageIncludePath dflags []
1244     let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1245                           (cmdline_include_paths ++ pkg_include_dirs)
1246
1247     let verb = getVerbFlag dflags
1248
1249     cc_opts <- if not include_cc_opts 
1250                   then return []
1251                   else do let optc = getOpts dflags opt_c
1252                           (md_c_flags, _) <- machdepCCOpts dflags
1253                           return (optc ++ md_c_flags)
1254
1255     let cpp_prog args | raw       = SysTools.runCpp dflags args
1256                       | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1257
1258     let target_defs = 
1259           [ "-D" ++ HOST_OS     ++ "_BUILD_OS=1",
1260             "-D" ++ HOST_ARCH   ++ "_BUILD_ARCH=1",
1261             "-D" ++ TARGET_OS   ++ "_HOST_OS=1",
1262             "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1263         -- remember, in code we *compile*, the HOST is the same our TARGET,
1264         -- and BUILD is the same as our HOST.
1265
1266     cpp_prog       ([SysTools.Option verb]
1267                     ++ map SysTools.Option include_paths
1268                     ++ map SysTools.Option hsSourceCppOpts
1269                     ++ map SysTools.Option hscpp_opts
1270                     ++ map SysTools.Option cc_opts
1271                     ++ map SysTools.Option target_defs
1272                     ++ [ SysTools.Option     "-x"
1273                        , SysTools.Option     "c"
1274                        , SysTools.Option     input_fn
1275         -- We hackily use Option instead of FileOption here, so that the file
1276         -- name is not back-slashed on Windows.  cpp is capable of
1277         -- dealing with / in filenames, so it works fine.  Furthermore
1278         -- if we put in backslashes, cpp outputs #line directives
1279         -- with *double* backslashes.   And that in turn means that
1280         -- our error messages get double backslashes in them.
1281         -- In due course we should arrange that the lexer deals
1282         -- with these \\ escapes properly.
1283                        , SysTools.Option     "-o"
1284                        , SysTools.FileOption "" output_fn
1285                        ])
1286
1287 -- -----------------------------------------------------------------------------
1288 -- Misc.
1289
1290 hscNextPhase :: HscSource -> HscTarget -> IO Phase
1291 hscNextPhase HsBootFile hsc_lang 
1292   = return StopLn
1293
1294 hscNextPhase other hsc_lang = do
1295   split <- readIORef v_Split_object_files
1296   return (case hsc_lang of
1297                 HscC -> HCc
1298                 HscAsm | split -> SplitMangle
1299                        | otherwise -> As
1300                 HscNothing     -> StopLn
1301                 HscInterpreted -> StopLn
1302                 _other         -> StopLn
1303         )
1304
1305 hscMaybeAdjustTarget :: Phase -> HscSource -> HscTarget -> IO HscTarget
1306 hscMaybeAdjustTarget stop HsBootFile current_hsc_lang 
1307   = return HscNothing           -- No output (other than Foo.hi-boot) for hs-boot files
1308 hscMaybeAdjustTarget stop other current_hsc_lang 
1309   = do  { keep_hc <- readIORef v_Keep_hc_files
1310         ; let hsc_lang
1311                 -- don't change the lang if we're interpreting
1312                  | current_hsc_lang == HscInterpreted = current_hsc_lang
1313
1314                 -- force -fvia-C if we are being asked for a .hc file
1315                  | HCc <- stop = HscC
1316                  | keep_hc     = HscC
1317                 -- otherwise, stick to the plan
1318                  | otherwise = current_hsc_lang
1319         ; return hsc_lang }