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