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