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