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