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