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