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