Remove LazyUniqFM; fixes trac #3880
[ghc-hetmet.git] / compiler / main / DriverPipeline.hs
1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
3
4 -----------------------------------------------------------------------------
5 --
6 -- GHC Driver
7 --
8 -- (c) The University of Glasgow 2005
9 --
10 -----------------------------------------------------------------------------
11
12 module DriverPipeline (
13         -- Run a series of compilation steps in a pipeline, for a
14         -- collection of source files.
15    oneShot, compileFile,
16
17         -- Interfaces for the batch-mode driver
18    linkBinary,
19
20         -- Interfaces for the compilation manager (interpreted/batch-mode)
21    preprocess, 
22    compile, compile',
23    link, 
24
25   ) where
26
27 #include "HsVersions.h"
28
29 import Packages
30 import HeaderInfo
31 import DriverPhases
32 import SysTools
33 import HscMain
34 import Finder
35 import HscTypes
36 import Outputable
37 import Module
38 import UniqFM           ( eltsUFM )
39 import ErrUtils
40 import DynFlags
41 import StaticFlags      ( v_Ld_inputs, opt_Static, WayName(..) )
42 import Config
43 import Panic
44 import Util
45 import StringBuffer     ( hGetStringBuffer )
46 import BasicTypes       ( SuccessFlag(..) )
47 import Maybes           ( expectJust )
48 import ParserCoreUtils  ( getCoreModuleName )
49 import SrcLoc
50 import FastString
51 -- import MonadUtils
52
53 -- import Data.Either
54 import Exception
55 import Data.IORef       ( readIORef )
56 -- import GHC.Exts              ( Int(..) )
57 import System.Directory
58 import System.FilePath
59 import System.IO
60 import System.IO.Error as IO
61 import Control.Monad
62 import Data.List        ( isSuffixOf )
63 import Data.Maybe
64 import System.Environment
65
66 -- ---------------------------------------------------------------------------
67 -- Pre-process
68
69 -- | Just preprocess a file, put the result in a temp. file (used by the
70 -- compilation manager during the summary phase).
71 --
72 -- We return the augmented DynFlags, because they contain the result
73 -- of slurping in the OPTIONS pragmas
74
75 preprocess :: GhcMonad m =>
76               HscEnv
77            -> (FilePath, Maybe Phase) -- ^ filename and starting phase
78            -> m (DynFlags, FilePath)
79 preprocess hsc_env (filename, mb_phase) =
80   ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename) 
81   runPipeline anyHsc hsc_env (filename, mb_phase) 
82         Nothing Temporary Nothing{-no ModLocation-}
83
84 -- ---------------------------------------------------------------------------
85
86 -- | Compile
87 --
88 -- Compile a single module, under the control of the compilation manager.
89 --
90 -- This is the interface between the compilation manager and the
91 -- compiler proper (hsc), where we deal with tedious details like
92 -- reading the OPTIONS pragma from the source file, and passing the
93 -- output of hsc through the C compiler.
94 --
95 -- NB.  No old interface can also mean that the source has changed.
96
97 compile :: GhcMonad m =>
98            HscEnv
99         -> ModSummary      -- ^ summary for module being compiled
100         -> Int             -- ^ module N ...
101         -> Int             -- ^ ... of M
102         -> Maybe ModIface  -- ^ old interface, if we have one
103         -> Maybe Linkable  -- ^ old linkable, if we have one
104         -> m HomeModInfo   -- ^ the complete HomeModInfo, if successful
105
106 compile = compile' (hscCompileNothing, hscCompileInteractive, hscCompileBatch)
107
108 type Compiler m a = HscEnv -> ModSummary -> Bool
109                   -> Maybe ModIface -> Maybe (Int, Int)
110                   -> m a
111
112 compile' :: GhcMonad m =>
113            (Compiler m (HscStatus, ModIface, ModDetails),
114             Compiler m (InteractiveStatus, ModIface, ModDetails),
115             Compiler m (HscStatus, ModIface, ModDetails))
116         -> HscEnv
117         -> ModSummary      -- ^ summary for module being compiled
118         -> Int             -- ^ module N ...
119         -> Int             -- ^ ... of M
120         -> Maybe ModIface  -- ^ old interface, if we have one
121         -> Maybe Linkable  -- ^ old linkable, if we have one
122         -> m HomeModInfo   -- ^ the complete HomeModInfo, if successful
123
124 compile' (nothingCompiler, interactiveCompiler, batchCompiler)
125         hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
126  = do
127    let dflags0     = ms_hspp_opts summary
128        this_mod    = ms_mod summary
129        src_flavour = ms_hsc_src summary
130        location    = ms_location summary
131        input_fn    = expectJust "compile:hs" (ml_hs_file location) 
132        input_fnpp  = ms_hspp_file summary
133
134    liftIO $ debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
135
136    let basename = dropExtension input_fn
137
138   -- We add the directory in which the .hs files resides) to the import path.
139   -- This is needed when we try to compile the .hc file later, if it
140   -- imports a _stub.h file that we created here.
141    let current_dir = case takeDirectory basename of
142                      "" -> "." -- XXX Hack
143                      d -> d
144        old_paths   = includePaths dflags0
145        dflags      = dflags0 { includePaths = current_dir : old_paths }
146        hsc_env     = hsc_env0 {hsc_dflags = dflags}
147
148    -- Figure out what lang we're generating
149    let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
150    -- ... and what the next phase should be
151    let next_phase = hscNextPhase dflags src_flavour hsc_lang
152    -- ... and what file to generate the output into
153    output_fn <- liftIO $ getOutputFilename next_phase
154                         Temporary basename dflags next_phase (Just location)
155
156    let dflags' = dflags { hscTarget = hsc_lang,
157                                 hscOutName = output_fn,
158                                 extCoreName = basename ++ ".hcr" }
159    let hsc_env' = hsc_env { hsc_dflags = dflags' }
160
161    -- -fforce-recomp should also work with --make
162    let force_recomp = dopt Opt_ForceRecomp dflags
163        source_unchanged = isJust maybe_old_linkable && not force_recomp
164        object_filename = ml_obj_file location
165
166    let getStubLinkable False = return []
167        getStubLinkable True
168            = do stub_o <- compileStub hsc_env' this_mod location
169                 return [ DotO stub_o ]
170
171        handleBatch HscNoRecomp
172            = ASSERT (isJust maybe_old_linkable)
173              return maybe_old_linkable
174
175        handleBatch (HscRecomp hasStub _)
176            | isHsBoot src_flavour
177                = do when (isObjectTarget hsc_lang) $ -- interpreted reaches here too
178                        liftIO $ SysTools.touch dflags' "Touching object file"
179                                    object_filename
180                     return maybe_old_linkable
181
182            | otherwise
183                = do stub_unlinked <- getStubLinkable hasStub
184                     (hs_unlinked, unlinked_time) <-
185                         case hsc_lang of
186                           HscNothing
187                             -> return ([], ms_hs_date summary)
188                           -- We're in --make mode: finish the compilation pipeline.
189                           _other
190                             -> do _ <- runPipeline StopLn hsc_env' (output_fn,Nothing)
191                                               (Just basename)
192                                               Persistent
193                                               (Just location)
194                                   -- The object filename comes from the ModLocation
195                                   o_time <- liftIO $ getModificationTime object_filename
196                                   return ([DotO object_filename], o_time)
197                     let linkable = LM unlinked_time this_mod
198                                    (hs_unlinked ++ stub_unlinked)
199                     return (Just linkable)
200
201        handleInterpreted HscNoRecomp
202            = ASSERT (isJust maybe_old_linkable)
203              return maybe_old_linkable
204        handleInterpreted (HscRecomp _hasStub Nothing)
205            = ASSERT (isHsBoot src_flavour)
206              return maybe_old_linkable
207        handleInterpreted (HscRecomp hasStub (Just (comp_bc, modBreaks)))
208            = do stub_unlinked <- getStubLinkable hasStub
209                 let hs_unlinked = [BCOs comp_bc modBreaks]
210                     unlinked_time = ms_hs_date summary
211                   -- Why do we use the timestamp of the source file here,
212                   -- rather than the current time?  This works better in
213                   -- the case where the local clock is out of sync
214                   -- with the filesystem's clock.  It's just as accurate:
215                   -- if the source is modified, then the linkable will
216                   -- be out of date.
217                 let linkable = LM unlinked_time this_mod
218                                (hs_unlinked ++ stub_unlinked)
219                 return (Just linkable)
220
221    let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
222        --            -> m HomeModInfo
223        runCompiler compiler handle
224            = do (result, iface, details)
225                     <- compiler hsc_env' summary source_unchanged mb_old_iface
226                                 (Just (mod_index, nmods))
227                 linkable <- handle result
228                 return (HomeModInfo{ hm_details  = details,
229                                      hm_iface    = iface,
230                                      hm_linkable = linkable })
231    -- run the compiler
232    case hsc_lang of
233       HscInterpreted ->
234                 runCompiler interactiveCompiler handleInterpreted
235       HscNothing -> 
236                 runCompiler nothingCompiler handleBatch
237       _other -> 
238                 runCompiler batchCompiler handleBatch
239
240
241 -----------------------------------------------------------------------------
242 -- stub .h and .c files (for foreign export support)
243
244 -- The _stub.c file is derived from the haskell source file, possibly taking
245 -- into account the -stubdir option.
246 --
247 -- Consequently, we derive the _stub.o filename from the haskell object
248 -- filename.  
249 --
250 -- This isn't necessarily the same as the object filename we
251 -- would get if we just compiled the _stub.c file using the pipeline.
252 -- For example:
253 --
254 --    ghc src/A.hs -odir obj
255 -- 
256 -- results in obj/A.o, and src/A_stub.c.  If we compile src/A_stub.c with
257 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
258 -- obj/A_stub.o.
259
260 compileStub :: GhcMonad m => HscEnv -> Module -> ModLocation
261             -> m FilePath
262 compileStub hsc_env mod location = do
263         -- compile the _stub.c file w/ gcc
264         let (stub_c,_,stub_o) = mkStubPaths (hsc_dflags hsc_env) 
265                                    (moduleName mod) location
266
267         _ <- runPipeline StopLn hsc_env (stub_c,Nothing)  Nothing
268                 (SpecificFile stub_o) Nothing{-no ModLocation-}
269
270         return stub_o
271
272
273 -- ---------------------------------------------------------------------------
274 -- Link
275
276 link :: GhcLink                 -- interactive or batch
277      -> DynFlags                -- dynamic flags
278      -> Bool                    -- attempt linking in batch mode?
279      -> HomePackageTable        -- what to link
280      -> IO SuccessFlag
281
282 -- For the moment, in the batch linker, we don't bother to tell doLink
283 -- which packages to link -- it just tries all that are available.
284 -- batch_attempt_linking should only be *looked at* in batch mode.  It
285 -- should only be True if the upsweep was successful and someone
286 -- exports main, i.e., we have good reason to believe that linking
287 -- will succeed.
288
289 #ifdef GHCI
290 link LinkInMemory _ _ _
291     = do -- Not Linking...(demand linker will do the job)
292          return Succeeded
293 #endif
294
295 link NoLink _ _ _
296    = return Succeeded
297
298 link LinkBinary dflags batch_attempt_linking hpt
299    = link' dflags batch_attempt_linking hpt
300
301 link LinkDynLib dflags batch_attempt_linking hpt
302    = link' dflags batch_attempt_linking hpt
303
304 #ifndef GHCI
305 -- warning suppression
306 link other _ _ _ = panicBadLink other
307 #endif
308
309 panicBadLink :: GhcLink -> a
310 panicBadLink other = panic ("link: GHC not built to link this way: " ++
311                             show other)
312
313 link' :: DynFlags                -- dynamic flags
314       -> Bool                    -- attempt linking in batch mode?
315       -> HomePackageTable        -- what to link
316       -> IO SuccessFlag
317
318 link' dflags batch_attempt_linking hpt
319    | batch_attempt_linking
320    = do
321         let
322             home_mod_infos = eltsUFM hpt
323
324             -- the packages we depend on
325             pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
326
327             -- the linkables to link
328             linkables = map (expectJust "link".hm_linkable) home_mod_infos
329
330         debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
331
332         -- check for the -no-link flag
333         if isNoLink (ghcLink dflags)
334           then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
335                   return Succeeded
336           else do
337
338         let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
339             obj_files = concatMap getOfiles linkables
340
341             exe_file = exeFileName dflags
342
343         linking_needed <- linkingNeeded dflags linkables pkg_deps
344
345         if not (dopt Opt_ForceRecomp dflags) && not linking_needed
346            then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required."))
347                    return Succeeded
348            else do
349
350         debugTraceMsg dflags 1 (ptext (sLit "Linking") <+> text exe_file
351                                  <+> text "...")
352
353         -- Don't showPass in Batch mode; doLink will do that for us.
354         let link = case ghcLink dflags of
355                 LinkBinary  -> linkBinary
356                 LinkDynLib  -> linkDynLib
357                 other       -> panicBadLink other
358         link dflags obj_files pkg_deps
359
360         debugTraceMsg dflags 3 (text "link: done")
361
362         -- linkBinary only returns if it succeeds
363         return Succeeded
364
365    | otherwise
366    = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
367                                 text "   Main.main not exported; not linking.")
368         return Succeeded
369
370
371 linkingNeeded :: DynFlags -> [Linkable] -> [PackageId] -> IO Bool
372 linkingNeeded dflags linkables pkg_deps = do
373         -- if the modification time on the executable is later than the
374         -- modification times on all of the objects and libraries, then omit
375         -- linking (unless the -fforce-recomp flag was given).
376   let exe_file = exeFileName dflags
377   e_exe_time <- IO.try $ getModificationTime exe_file
378   case e_exe_time of
379     Left _  -> return True
380     Right t -> do
381         -- first check object files and extra_ld_inputs
382         extra_ld_inputs <- readIORef v_Ld_inputs
383         e_extra_times <- mapM (IO.try . getModificationTime) extra_ld_inputs
384         let (errs,extra_times) = splitEithers e_extra_times
385         let obj_times =  map linkableTime linkables ++ extra_times
386         if not (null errs) || any (t <) obj_times
387             then return True 
388             else do
389
390         -- next, check libraries. XXX this only checks Haskell libraries,
391         -- not extra_libraries or -l things from the command line.
392         let pkg_map = pkgIdMap (pkgState dflags)
393             pkg_hslibs  = [ (libraryDirs c, lib)
394                           | Just c <- map (lookupPackage pkg_map) pkg_deps,
395                             lib <- packageHsLibs dflags c ]
396
397         pkg_libfiles <- mapM (uncurry findHSLib) pkg_hslibs
398         if any isNothing pkg_libfiles then return True else do
399         e_lib_times <- mapM (IO.try . getModificationTime)
400                           (catMaybes pkg_libfiles)
401         let (lib_errs,lib_times) = splitEithers e_lib_times
402         if not (null lib_errs) || any (t <) lib_times
403            then return True
404            else return False
405
406 findHSLib :: [String] -> String -> IO (Maybe FilePath)
407 findHSLib dirs lib = do
408   let batch_lib_file = "lib" ++ lib <.> "a"
409   found <- filterM doesFileExist (map (</> batch_lib_file) dirs)
410   case found of
411     [] -> return Nothing
412     (x:_) -> return (Just x)
413
414 -- -----------------------------------------------------------------------------
415 -- Compile files in one-shot mode.
416
417 oneShot :: GhcMonad m =>
418            HscEnv -> Phase -> [(String, Maybe Phase)] -> m ()
419 oneShot hsc_env stop_phase srcs = do
420   o_files <- mapM (compileFile hsc_env stop_phase) srcs
421   liftIO $ doLink (hsc_dflags hsc_env) stop_phase o_files
422
423 compileFile :: GhcMonad m =>
424                HscEnv -> Phase -> (FilePath, Maybe Phase) -> m FilePath
425 compileFile hsc_env stop_phase (src, mb_phase) = do
426    exists <- liftIO $ doesFileExist src
427    when (not exists) $ 
428         ghcError (CmdLineError ("does not exist: " ++ src))
429    
430    let
431         dflags = hsc_dflags hsc_env
432         split     = dopt Opt_SplitObjs dflags
433         mb_o_file = outputFile dflags
434         ghc_link  = ghcLink dflags      -- Set by -c or -no-link
435
436         -- When linking, the -o argument refers to the linker's output. 
437         -- otherwise, we use it as the name for the pipeline's output.
438         output
439          | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
440                 -- -o foo applies to linker
441          | Just o_file <- mb_o_file = SpecificFile o_file
442                 -- -o foo applies to the file we are compiling now
443          | otherwise = Persistent
444
445         stop_phase' = case stop_phase of 
446                         As | split -> SplitAs
447                         _          -> stop_phase
448
449    ( _, out_file) <- runPipeline stop_phase' hsc_env
450                             (src, mb_phase) Nothing output
451                             Nothing{-no ModLocation-}
452    return out_file
453
454
455 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
456 doLink dflags stop_phase o_files
457   | not (isStopLn stop_phase)
458   = return ()           -- We stopped before the linking phase
459
460   | otherwise
461   = case ghcLink dflags of
462         NoLink     -> return ()
463         LinkBinary -> linkBinary dflags o_files link_pkgs
464         LinkDynLib -> linkDynLib dflags o_files []
465         other      -> panicBadLink other
466   where
467    -- Always link in the haskell98 package for static linking.  Other
468    -- packages have to be specified via the -package flag.
469     link_pkgs
470      | dopt Opt_AutoLinkPackages dflags = [haskell98PackageId]
471      | otherwise                        = []
472
473
474 -- ---------------------------------------------------------------------------
475
476 data PipelineOutput 
477   = Temporary
478         -- ^ Output should be to a temporary file: we're going to
479         -- run more compilation steps on this output later.
480   | Persistent
481         -- ^ We want a persistent file, i.e. a file in the current directory
482         -- derived from the input filename, but with the appropriate extension.
483         -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
484   | SpecificFile FilePath
485         -- ^ The output must go into the specified file.
486
487 -- | Run a compilation pipeline, consisting of multiple phases.
488 --
489 -- This is the interface to the compilation pipeline, which runs
490 -- a series of compilation steps on a single source file, specifying
491 -- at which stage to stop.
492 --
493 -- The DynFlags can be modified by phases in the pipeline (eg. by
494 -- OPTIONS_GHC pragmas), and the changes affect later phases in the
495 -- pipeline.
496 runPipeline
497   :: GhcMonad m =>
498      Phase                      -- ^ When to stop
499   -> HscEnv                     -- ^ Compilation environment
500   -> (FilePath,Maybe Phase)     -- ^ Input filename (and maybe -x suffix)
501   -> Maybe FilePath             -- ^ original basename (if different from ^^^)
502   -> PipelineOutput             -- ^ Output filename
503   -> Maybe ModLocation          -- ^ A ModLocation, if this is a Haskell module
504   -> m (DynFlags, FilePath)     -- ^ (final flags, output filename)
505
506 runPipeline stop_phase hsc_env0 (input_fn, mb_phase) mb_basename output maybe_loc
507   = do
508   let dflags0 = hsc_dflags hsc_env0
509       (input_basename, suffix) = splitExtension input_fn
510       suffix' = drop 1 suffix -- strip off the .
511       basename | Just b <- mb_basename = b
512                | otherwise             = input_basename
513
514       -- Decide where dump files should go based on the pipeline output
515       dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
516       hsc_env = hsc_env0 {hsc_dflags = dflags}
517
518         -- If we were given a -x flag, then use that phase to start from
519       start_phase = fromMaybe (startPhase suffix') mb_phase
520
521   -- We want to catch cases of "you can't get there from here" before
522   -- we start the pipeline, because otherwise it will just run off the
523   -- end.
524   --
525   -- There is a partial ordering on phases, where A < B iff A occurs
526   -- before B in a normal compilation pipeline.
527
528   when (not (start_phase `happensBefore` stop_phase)) $
529         ghcError (UsageError 
530                     ("cannot compile this file to desired target: "
531                        ++ input_fn))
532
533   -- this is a function which will be used to calculate output file names
534   -- as we go along (we partially apply it to some of its inputs here)
535   let get_output_fn = getOutputFilename stop_phase output basename
536
537   -- Execute the pipeline...
538   (dflags', output_fn, maybe_loc) <- 
539         pipeLoop hsc_env start_phase stop_phase input_fn 
540                  basename suffix' get_output_fn maybe_loc
541
542   -- Sometimes, a compilation phase doesn't actually generate any output
543   -- (eg. the CPP phase when -fcpp is not turned on).  If we end on this
544   -- stage, but we wanted to keep the output, then we have to explicitly
545   -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
546   -- further compilation stages can tell what the original filename was.
547   case output of
548     Temporary -> 
549         return (dflags', output_fn)
550     _other -> liftIO $
551         do final_fn <- get_output_fn dflags' stop_phase maybe_loc
552            when (final_fn /= output_fn) $ do
553               let msg = ("Copying `" ++ output_fn ++"' to `" ++ final_fn ++ "'")
554                   line_prag = Just ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}\n")
555               copyWithHeader dflags msg line_prag output_fn final_fn
556            return (dflags', final_fn)
557
558
559
560 pipeLoop :: GhcMonad m =>
561             HscEnv -> Phase -> Phase
562          -> FilePath  -> String -> Suffix
563          -> (DynFlags -> Phase -> Maybe ModLocation -> IO FilePath)
564          -> Maybe ModLocation
565          -> m (DynFlags, FilePath, Maybe ModLocation)
566
567 pipeLoop hsc_env phase stop_phase 
568          input_fn orig_basename orig_suff 
569          orig_get_output_fn maybe_loc
570
571   | phase `eqPhase` stop_phase            -- All done
572   = return (hsc_dflags hsc_env, input_fn, maybe_loc)
573
574   | not (phase `happensBefore` stop_phase)
575         -- Something has gone wrong.  We'll try to cover all the cases when
576         -- this could happen, so if we reach here it is a panic.
577         -- eg. it might happen if the -C flag is used on a source file that
578         -- has {-# OPTIONS -fasm #-}.
579   = panic ("pipeLoop: at phase " ++ show phase ++ 
580            " but I wanted to stop at phase " ++ show stop_phase)
581
582   | otherwise 
583   = do (next_phase, dflags', maybe_loc, output_fn)
584           <- runPhase phase stop_phase hsc_env orig_basename 
585                       orig_suff input_fn orig_get_output_fn maybe_loc
586        let hsc_env' = hsc_env {hsc_dflags = dflags'}
587        pipeLoop hsc_env' next_phase stop_phase output_fn
588                 orig_basename orig_suff orig_get_output_fn maybe_loc
589
590 getOutputFilename
591   :: Phase -> PipelineOutput -> String
592   -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
593 getOutputFilename stop_phase output basename
594  = func
595  where
596         func dflags next_phase maybe_location
597            | is_last_phase, Persistent <- output     = persistent_fn
598            | is_last_phase, SpecificFile f <- output = return f
599            | keep_this_output                        = persistent_fn
600            | otherwise                               = newTempName dflags suffix
601            where
602                 hcsuf      = hcSuf dflags
603                 odir       = objectDir dflags
604                 osuf       = objectSuf dflags
605                 keep_hc    = dopt Opt_KeepHcFiles dflags
606                 keep_raw_s = dopt Opt_KeepRawSFiles dflags
607                 keep_s     = dopt Opt_KeepSFiles dflags
608
609                 myPhaseInputExt HCc    = hcsuf
610                 myPhaseInputExt StopLn = osuf
611                 myPhaseInputExt other  = phaseInputExt other
612
613                 is_last_phase = next_phase `eqPhase` stop_phase
614
615                 -- sometimes, we keep output from intermediate stages
616                 keep_this_output = 
617                      case next_phase of
618                              StopLn              -> True
619                              Mangle | keep_raw_s -> True
620                              As     | keep_s     -> True
621                              HCc    | keep_hc    -> True
622                              _other              -> False
623
624                 suffix = myPhaseInputExt next_phase
625
626                 -- persistent object files get put in odir
627                 persistent_fn 
628                    | StopLn <- next_phase = return odir_persistent
629                    | otherwise            = return persistent
630
631                 persistent = basename <.> suffix
632
633                 odir_persistent
634                    | Just loc <- maybe_location = ml_obj_file loc
635                    | Just d <- odir = d </> persistent
636                    | otherwise      = persistent
637
638
639 -- -----------------------------------------------------------------------------
640 -- | Each phase in the pipeline returns the next phase to execute, and the
641 -- name of the file in which the output was placed.
642 --
643 -- We must do things dynamically this way, because we often don't know
644 -- what the rest of the phases will be until part-way through the
645 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
646 -- of a source file can change the latter stages of the pipeline from
647 -- taking the via-C route to using the native code generator.
648 --
649 runPhase :: GhcMonad m =>
650             Phase       -- ^ Do this phase first
651          -> Phase       -- ^ Stop just before this phase
652          -> HscEnv
653          -> String      -- ^ basename of original input source
654          -> String      -- ^ its extension
655          -> FilePath    -- ^ name of file which contains the input to this phase.
656          -> (DynFlags -> Phase -> Maybe ModLocation -> IO FilePath)
657                         -- ^ how to calculate the output filename
658          -> Maybe ModLocation           -- ^ the ModLocation, if we have one
659          -> m (Phase,                   -- next phase
660                DynFlags,                -- new dynamic flags
661                Maybe ModLocation,       -- the ModLocation, if we have one
662                FilePath)                -- output filename
663
664         -- Invariant: the output filename always contains the output
665         -- Interesting case: Hsc when there is no recompilation to do
666         --                   Then the output filename is still a .o file 
667
668 -------------------------------------------------------------------------------
669 -- Unlit phase 
670
671 runPhase (Unlit sf) _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
672   = do
673        let dflags = hsc_dflags hsc_env
674        output_fn <- liftIO $ get_output_fn dflags (Cpp sf) maybe_loc
675
676        let unlit_flags = getOpts dflags opt_L
677            flags = map SysTools.Option unlit_flags ++
678                    [ -- The -h option passes the file name for unlit to
679                      -- put in a #line directive
680                      SysTools.Option     "-h"
681                      -- cpp interprets \b etc as escape sequences,
682                      -- so we use / for filenames in pragmas
683                    , SysTools.Option $ reslash Forwards $ normalise input_fn
684                    , SysTools.FileOption "" input_fn
685                    , SysTools.FileOption "" output_fn
686                    ]
687
688        liftIO $ SysTools.runUnlit dflags flags
689
690        return (Cpp sf, dflags, maybe_loc, output_fn)
691
692 -------------------------------------------------------------------------------
693 -- Cpp phase : (a) gets OPTIONS out of file
694 --             (b) runs cpp if necessary
695
696 runPhase (Cpp sf) _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
697   = do let dflags0 = hsc_dflags hsc_env
698        src_opts <- liftIO $ getOptionsFromFile dflags0 input_fn
699        (dflags1, unhandled_flags, warns)
700            <- liftIO $ parseDynamicNoPackageFlags dflags0 src_opts
701        checkProcessArgsResult unhandled_flags
702
703        if not (dopt Opt_Cpp dflags1) then do
704            -- we have to be careful to emit warnings only once.
705            unless (dopt Opt_Pp dflags1) $ handleFlagWarnings dflags1 warns
706
707            -- no need to preprocess CPP, just pass input file along
708            -- to the next phase of the pipeline.
709            return (HsPp sf, dflags1, maybe_loc, input_fn)
710         else do
711             output_fn <- liftIO $ get_output_fn dflags1 (HsPp sf) maybe_loc
712             liftIO $ doCpp dflags1 True{-raw-} False{-no CC opts-} input_fn output_fn
713             -- re-read the pragmas now that we've preprocessed the file
714             -- See #2464,#3457
715             src_opts <- liftIO $ getOptionsFromFile dflags0 output_fn
716             (dflags2, unhandled_flags, warns)
717                 <- liftIO $ parseDynamicNoPackageFlags dflags0 src_opts
718             unless (dopt Opt_Pp dflags2) $ handleFlagWarnings dflags2 warns
719             -- the HsPp pass below will emit warnings
720             checkProcessArgsResult unhandled_flags
721
722             return (HsPp sf, dflags2, maybe_loc, output_fn)
723
724 -------------------------------------------------------------------------------
725 -- HsPp phase 
726
727 runPhase (HsPp sf) _stop hsc_env basename suff input_fn get_output_fn maybe_loc
728   = do let dflags = hsc_dflags hsc_env
729        if not (dopt Opt_Pp dflags) then
730            -- no need to preprocess, just pass input file along
731            -- to the next phase of the pipeline.
732           return (Hsc sf, dflags, maybe_loc, input_fn)
733         else do
734             let hspp_opts = getOpts dflags opt_F
735             let orig_fn = basename <.> suff
736             output_fn <- liftIO $ get_output_fn dflags (Hsc sf) maybe_loc
737             liftIO $ SysTools.runPp dflags
738                            ( [ SysTools.Option     orig_fn
739                              , SysTools.Option     input_fn
740                              , SysTools.FileOption "" output_fn
741                              ] ++
742                              map SysTools.Option hspp_opts
743                            )
744
745             -- re-read pragmas now that we've parsed the file (see #3674)
746             src_opts <- liftIO $ getOptionsFromFile dflags output_fn
747             (dflags1, unhandled_flags, warns)
748                 <- liftIO $ parseDynamicNoPackageFlags dflags src_opts
749             handleFlagWarnings dflags1 warns
750             checkProcessArgsResult unhandled_flags
751
752             return (Hsc sf, dflags1, maybe_loc, output_fn)
753
754 -----------------------------------------------------------------------------
755 -- Hsc phase
756
757 -- Compilation of a single module, in "legacy" mode (_not_ under
758 -- the direction of the compilation manager).
759 runPhase (Hsc src_flavour) stop hsc_env basename suff input_fn get_output_fn _maybe_loc 
760  = do   -- normal Hsc mode, not mkdependHS
761         let dflags0 = hsc_dflags hsc_env
762
763   -- we add the current directory (i.e. the directory in which
764   -- the .hs files resides) to the include path, since this is
765   -- what gcc does, and it's probably what you want.
766         let current_dir = case takeDirectory basename of
767                       "" -> "." -- XXX Hack
768                       d -> d
769         
770             paths = includePaths dflags0
771             dflags = dflags0 { includePaths = current_dir : paths }
772         
773   -- gather the imports and module name
774         (hspp_buf,mod_name,imps,src_imps) <- 
775             case src_flavour of
776                 ExtCoreFile -> do  -- no explicit imports in ExtCore input.
777                     m <- liftIO $ getCoreModuleName input_fn
778                     return (Nothing, mkModuleName m, [], [])
779
780                 _           -> do
781                     buf <- liftIO $ hGetStringBuffer input_fn
782                     (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
783                     return (Just buf, mod_name, imps, src_imps)
784
785   -- Build a ModLocation to pass to hscMain.
786   -- The source filename is rather irrelevant by now, but it's used
787   -- by hscMain for messages.  hscMain also needs 
788   -- the .hi and .o filenames, and this is as good a way
789   -- as any to generate them, and better than most. (e.g. takes 
790   -- into accout the -osuf flags)
791         location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff
792
793   -- Boot-ify it if necessary
794         let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
795                       | otherwise            = location1 
796                                         
797
798   -- Take -ohi into account if present
799   -- This can't be done in mkHomeModuleLocation because
800   -- it only applies to the module being compiles
801         let ohi = outputHi dflags
802             location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
803                       | otherwise      = location2
804
805   -- Take -o into account if present
806   -- Very like -ohi, but we must *only* do this if we aren't linking
807   -- (If we're linking then the -o applies to the linked thing, not to
808   -- the object file for one module.)
809   -- Note the nasty duplication with the same computation in compileFile above
810         let expl_o_file = outputFile dflags
811             location4 | Just ofile <- expl_o_file
812                       , isNoLink (ghcLink dflags)
813                       = location3 { ml_obj_file = ofile }
814                       | otherwise = location3
815
816             o_file = ml_obj_file location4      -- The real object file
817
818
819   -- Figure out if the source has changed, for recompilation avoidance.
820   --
821   -- Setting source_unchanged to True means that M.o seems
822   -- to be up to date wrt M.hs; so no need to recompile unless imports have
823   -- changed (which the compiler itself figures out).
824   -- Setting source_unchanged to False tells the compiler that M.o is out of
825   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
826         src_timestamp <- liftIO $ getModificationTime (basename <.> suff)
827
828         let force_recomp = dopt Opt_ForceRecomp dflags
829         source_unchanged <-
830           if force_recomp || not (isStopLn stop)
831                 -- Set source_unchanged to False unconditionally if
832                 --      (a) recompilation checker is off, or
833                 --      (b) we aren't going all the way to .o file (e.g. ghc -S)
834              then return False  
835                 -- Otherwise look at file modification dates
836              else do o_file_exists <- liftIO $ doesFileExist o_file
837                      if not o_file_exists
838                         then return False       -- Need to recompile
839                         else do t2 <- liftIO $ getModificationTime o_file
840                                 if t2 > src_timestamp
841                                   then return True
842                                   else return False
843
844   -- get the DynFlags
845         let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
846         let next_phase = hscNextPhase dflags src_flavour hsc_lang
847         output_fn  <- liftIO $ get_output_fn dflags next_phase (Just location4)
848
849         let dflags' = dflags { hscTarget = hsc_lang,
850                                hscOutName = output_fn,
851                                extCoreName = basename ++ ".hcr" }
852
853         let hsc_env' = hsc_env {hsc_dflags = dflags'}
854
855   -- Tell the finder cache about this module
856         mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location4
857
858   -- Make the ModSummary to hand to hscMain
859         let
860             mod_summary = ModSummary {  ms_mod       = mod, 
861                                         ms_hsc_src   = src_flavour,
862                                         ms_hspp_file = input_fn,
863                                         ms_hspp_opts = dflags,
864                                         ms_hspp_buf  = hspp_buf,
865                                         ms_location  = location4,
866                                         ms_hs_date   = src_timestamp,
867                                         ms_obj_date  = Nothing,
868                                         ms_imps      = imps,
869                                         ms_srcimps   = src_imps }
870
871   -- run the compiler!
872         result <- hscCompileOneShot hsc_env'
873                           mod_summary source_unchanged 
874                           Nothing       -- No iface
875                           Nothing       -- No "module i of n" progress info
876
877         case result of
878           HscNoRecomp
879               -> do liftIO $ SysTools.touch dflags' "Touching object file" o_file
880                     -- The .o file must have a later modification date
881                     -- than the source file (else we wouldn't be in HscNoRecomp)
882                     -- but we touch it anyway, to keep 'make' happy (we think).
883                     return (StopLn, dflags', Just location4, o_file)
884           (HscRecomp hasStub _)
885               -> do when hasStub $
886                          do stub_o <- compileStub hsc_env' mod location4
887                             liftIO $ consIORef v_Ld_inputs stub_o
888                     -- In the case of hs-boot files, generate a dummy .o-boot 
889                     -- stamp file for the benefit of Make
890                     when (isHsBoot src_flavour) $
891                       liftIO $ SysTools.touch dflags' "Touching object file" o_file
892                     return (next_phase, dflags', Just location4, output_fn)
893
894 -----------------------------------------------------------------------------
895 -- Cmm phase
896
897 runPhase CmmCpp _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
898   = do
899        let dflags = hsc_dflags hsc_env
900        output_fn <- liftIO $ get_output_fn dflags Cmm maybe_loc
901        liftIO $ doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
902        return (Cmm, dflags, maybe_loc, output_fn)
903
904 runPhase Cmm stop hsc_env basename _ input_fn get_output_fn maybe_loc
905   = do
906         let dflags = hsc_dflags hsc_env
907         let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
908         let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
909         output_fn <- liftIO $ get_output_fn dflags next_phase maybe_loc
910
911         let dflags' = dflags { hscTarget = hsc_lang,
912                                hscOutName = output_fn,
913                                extCoreName = basename ++ ".hcr" }
914         let hsc_env' = hsc_env {hsc_dflags = dflags'}
915
916         hscCmmFile hsc_env' input_fn
917
918         -- XXX: catch errors above and convert them into ghcError?  Original
919         -- code was:
920         --
921         --when (not ok) $ ghcError (PhaseFailed "cmm" (ExitFailure 1))
922
923         return (next_phase, dflags, maybe_loc, output_fn)
924
925 -----------------------------------------------------------------------------
926 -- Cc phase
927
928 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
929 -- way too many hacks, and I can't say I've ever used it anyway.
930
931 runPhase cc_phase _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
932    | cc_phase `eqPhase` Cc || cc_phase `eqPhase` Ccpp || cc_phase `eqPhase` HCc
933    = do let dflags = hsc_dflags hsc_env
934         let cc_opts = getOpts dflags opt_c
935             hcc = cc_phase `eqPhase` HCc
936
937         let cmdline_include_paths = includePaths dflags
938
939         -- HC files have the dependent packages stamped into them
940         pkgs <- if hcc then liftIO (getHCFilePackages input_fn) else return []
941
942         -- add package include paths even if we're just compiling .c
943         -- files; this is the Value Add(TM) that using ghc instead of
944         -- gcc gives you :)
945         pkg_include_dirs <- liftIO $ getPackageIncludePath dflags pkgs
946         let include_paths = foldr (\ x xs -> "-I" : x : xs) []
947                               (cmdline_include_paths ++ pkg_include_dirs)
948
949         let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
950         gcc_extra_viac_flags <- liftIO $ getExtraViaCOpts dflags
951         let pic_c_flags = picCCOpts dflags
952
953         let verb = getVerbFlag dflags
954
955         -- cc-options are not passed when compiling .hc files.  Our
956         -- hc code doesn't not #include any header files anyway, so these
957         -- options aren't necessary.
958         pkg_extra_cc_opts <-
959           if cc_phase `eqPhase` HCc
960              then return []
961              else liftIO $ getPackageExtraCcOpts dflags pkgs
962
963 #ifdef darwin_TARGET_OS
964         pkg_framework_paths <- liftIO $ getPackageFrameworkPath dflags pkgs
965         let cmdline_framework_paths = frameworkPaths dflags
966         let framework_paths = map ("-F"++) 
967                         (cmdline_framework_paths ++ pkg_framework_paths)
968 #endif
969
970         let split_objs = dopt Opt_SplitObjs dflags
971             split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
972                       | otherwise         = [ ]
973
974         let cc_opt | optLevel dflags >= 2 = "-O2"
975                    | otherwise            = "-O"
976
977         -- Decide next phase
978         
979         let mangle = dopt Opt_DoAsmMangling dflags
980             next_phase
981                 | hcc && mangle     = Mangle
982                 | otherwise         = As
983         output_fn <- liftIO $ get_output_fn dflags next_phase maybe_loc
984
985         let
986           more_hcc_opts =
987 #if i386_TARGET_ARCH
988                 -- on x86 the floating point regs have greater precision
989                 -- than a double, which leads to unpredictable results.
990                 -- By default, we turn this off with -ffloat-store unless
991                 -- the user specified -fexcess-precision.
992                 (if dopt Opt_ExcessPrecision dflags 
993                         then [] 
994                         else [ "-ffloat-store" ]) ++
995 #endif
996
997                 -- gcc's -fstrict-aliasing allows two accesses to memory
998                 -- to be considered non-aliasing if they have different types.
999                 -- This interacts badly with the C code we generate, which is
1000                 -- very weakly typed, being derived from C--.
1001                 ["-fno-strict-aliasing"]
1002
1003         liftIO $ SysTools.runCc dflags (
1004                 -- force the C compiler to interpret this file as C when
1005                 -- compiling .hc files, by adding the -x c option.
1006                 -- Also useful for plain .c files, just in case GHC saw a 
1007                 -- -x c option.
1008                         [ SysTools.Option "-x", if cc_phase `eqPhase` Ccpp
1009                                                 then SysTools.Option "c++" 
1010                                                 else SysTools.Option "c"] ++
1011                         [ SysTools.FileOption "" input_fn
1012                         , SysTools.Option "-o"
1013                         , SysTools.FileOption "" output_fn
1014                         ]
1015                        ++ map SysTools.Option (
1016                           md_c_flags
1017                        ++ pic_c_flags
1018
1019 #if    defined(mingw32_TARGET_OS)
1020                 -- Stub files generated for foreign exports references the runIO_closure
1021                 -- and runNonIO_closure symbols, which are defined in the base package.
1022                 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1023                 -- way we do the import depends on whether we're currently compiling
1024                 -- the base package or not.
1025                        ++ (if thisPackage dflags == basePackageId
1026                                 then [ "-DCOMPILING_BASE_PACKAGE" ]
1027                                 else [])
1028 #endif  
1029
1030 #ifdef sparc_TARGET_ARCH
1031         -- We only support SparcV9 and better because V8 lacks an atomic CAS
1032         -- instruction. Note that the user can still override this
1033         -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1034         -- regardless of the ordering.
1035         --
1036         -- This is a temporary hack.
1037                        ++ ["-mcpu=v9"]
1038 #endif
1039                        ++ (if hcc && mangle
1040                              then md_regd_c_flags
1041                              else [])
1042                        ++ (if hcc
1043                              then if mangle 
1044                                      then gcc_extra_viac_flags
1045                                      else filter (=="-fwrapv")
1046                                                 gcc_extra_viac_flags
1047                                 -- still want -fwrapv even for unreg'd
1048                              else [])
1049                        ++ (if hcc 
1050                              then more_hcc_opts
1051                              else [])
1052                        ++ [ verb, "-S", "-Wimplicit", cc_opt ]
1053                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1054 #ifdef darwin_TARGET_OS
1055                        ++ framework_paths
1056 #endif
1057                        ++ cc_opts
1058                        ++ split_opt
1059                        ++ include_paths
1060                        ++ pkg_extra_cc_opts
1061                        ))
1062
1063         return (next_phase, dflags, maybe_loc, output_fn)
1064
1065         -- ToDo: postprocess the output from gcc
1066
1067 -----------------------------------------------------------------------------
1068 -- Mangle phase
1069
1070 runPhase Mangle _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
1071    = do let dflags = hsc_dflags hsc_env
1072         let mangler_opts = getOpts dflags opt_m
1073
1074 #if i386_TARGET_ARCH
1075         machdep_opts <- return [ show (stolen_x86_regs dflags) ]
1076 #else
1077         machdep_opts <- return []
1078 #endif
1079
1080         let split = dopt Opt_SplitObjs dflags
1081             next_phase
1082                 | split = SplitMangle
1083                 | otherwise = As
1084         output_fn <- liftIO $ get_output_fn dflags next_phase maybe_loc
1085
1086         liftIO $ SysTools.runMangle dflags (map SysTools.Option mangler_opts
1087                           ++ [ SysTools.FileOption "" input_fn
1088                              , SysTools.FileOption "" output_fn
1089                              ]
1090                           ++ map SysTools.Option machdep_opts)
1091
1092         return (next_phase, dflags, maybe_loc, output_fn)
1093
1094 -----------------------------------------------------------------------------
1095 -- Splitting phase
1096
1097 runPhase SplitMangle _stop hsc_env _basename _suff input_fn _get_output_fn maybe_loc
1098   = liftIO $
1099     do  -- tmp_pfx is the prefix used for the split .s files
1100         -- We also use it as the file to contain the no. of split .s files (sigh)
1101         let dflags = hsc_dflags hsc_env
1102         split_s_prefix <- SysTools.newTempName dflags "split"
1103         let n_files_fn = split_s_prefix
1104
1105         SysTools.runSplit dflags
1106                           [ SysTools.FileOption "" input_fn
1107                           , SysTools.FileOption "" split_s_prefix
1108                           , SysTools.FileOption "" n_files_fn
1109                           ]
1110
1111         -- Save the number of split files for future references
1112         s <- readFile n_files_fn
1113         let n_files = read s :: Int
1114             dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1115
1116         -- Remember to delete all these files
1117         addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s"
1118                                 | n <- [1..n_files]]
1119
1120         return (SplitAs, dflags', maybe_loc, "**splitmangle**")
1121           -- we don't use the filename
1122
1123 -----------------------------------------------------------------------------
1124 -- As phase
1125
1126 runPhase As _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
1127   = liftIO $
1128     do  let dflags = hsc_dflags hsc_env
1129         let as_opts =  getOpts dflags opt_a
1130         let cmdline_include_paths = includePaths dflags
1131
1132         output_fn <- get_output_fn dflags StopLn maybe_loc
1133
1134         -- we create directories for the object file, because it
1135         -- might be a hierarchical module.
1136         createDirectoryHierarchy (takeDirectory output_fn)
1137
1138         let (md_c_flags, _) = machdepCCOpts dflags
1139         SysTools.runAs dflags   
1140                        (map SysTools.Option as_opts
1141                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1142 #ifdef sparc_TARGET_ARCH
1143         -- We only support SparcV9 and better because V8 lacks an atomic CAS
1144         -- instruction so we have to make sure that the assembler accepts the
1145         -- instruction set. Note that the user can still override this
1146         -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1147         -- regardless of the ordering.
1148         --
1149         -- This is a temporary hack.
1150                        ++ [ SysTools.Option "-mcpu=v9" ]
1151 #endif
1152                        ++ [ SysTools.Option "-c"
1153                           , SysTools.FileOption "" input_fn
1154                           , SysTools.Option "-o"
1155                           , SysTools.FileOption "" output_fn
1156                           ]
1157                        ++ map SysTools.Option md_c_flags)
1158
1159         return (StopLn, dflags, maybe_loc, output_fn)
1160
1161
1162 runPhase SplitAs _stop hsc_env _basename _suff _input_fn get_output_fn maybe_loc
1163   = liftIO $ do
1164         let dflags = hsc_dflags hsc_env
1165         output_fn <- get_output_fn dflags StopLn maybe_loc
1166
1167         let base_o = dropExtension output_fn
1168             osuf = objectSuf dflags
1169             split_odir  = base_o ++ "_" ++ osuf ++ "_split"
1170
1171         createDirectoryHierarchy split_odir
1172
1173         -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1174         -- later and we don't want to pick up any old objects.
1175         fs <- getDirectoryContents split_odir
1176         mapM_ removeFile $ map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1177
1178         let as_opts = getOpts dflags opt_a
1179
1180         let (split_s_prefix, n) = case splitInfo dflags of
1181                                   Nothing -> panic "No split info"
1182                                   Just x -> x
1183
1184         let split_s   n = split_s_prefix ++ "__" ++ show n <.> "s"
1185             split_obj n = split_odir </>
1186                           takeFileName base_o ++ "__" ++ show n <.> osuf
1187
1188         let (md_c_flags, _) = machdepCCOpts dflags
1189         let assemble_file n
1190               = SysTools.runAs dflags
1191                          (map SysTools.Option as_opts ++
1192 #ifdef sparc_TARGET_ARCH
1193         -- We only support SparcV9 and better because V8 lacks an atomic CAS
1194         -- instruction so we have to make sure that the assembler accepts the
1195         -- instruction set. Note that the user can still override this
1196         -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1197         -- regardless of the ordering.
1198         --
1199         -- This is a temporary hack.
1200                           [ SysTools.Option "-mcpu=v9" ] ++
1201 #endif
1202                           [ SysTools.Option "-c"
1203                           , SysTools.Option "-o"
1204                           , SysTools.FileOption "" (split_obj n)
1205                           , SysTools.FileOption "" (split_s n)
1206                           ]
1207                        ++ map SysTools.Option md_c_flags)
1208
1209         mapM_ assemble_file [1..n]
1210
1211         -- and join the split objects into a single object file:
1212         let ld_r args = SysTools.runLink dflags ([
1213                             SysTools.Option "-nostdlib",
1214                             SysTools.Option "-nodefaultlibs",
1215                             SysTools.Option "-Wl,-r",
1216                             SysTools.Option ld_x_flag,
1217                             SysTools.Option "-o",
1218                             SysTools.FileOption "" output_fn ]
1219                          ++ map SysTools.Option md_c_flags
1220                          ++ args)
1221             ld_x_flag | null cLD_X = ""
1222                       | otherwise  = "-Wl,-x"
1223
1224         if cLdIsGNULd == "YES"
1225             then do
1226                   let script = split_odir </> "ld.script"
1227                   writeFile script $
1228                       "INPUT(" ++ unwords (map split_obj [1..n]) ++ ")"
1229                   ld_r [SysTools.FileOption "" script]
1230             else do
1231                   ld_r (map (SysTools.FileOption "" . split_obj) [1..n])
1232
1233         return (StopLn, dflags, maybe_loc, output_fn)
1234
1235 -- warning suppression
1236 runPhase other _stop _dflags _basename _suff _input_fn _get_output_fn _maybe_loc =
1237    panic ("runPhase: don't know how to run phase " ++ show other)
1238 -----------------------------------------------------------------------------
1239 -- MoveBinary sort-of-phase
1240 -- After having produced a binary, move it somewhere else and generate a
1241 -- wrapper script calling the binary. Currently, we need this only in 
1242 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1243 -- central directory.
1244 -- This is called from linkBinary below, after linking. I haven't made it
1245 -- a separate phase to minimise interfering with other modules, and
1246 -- we don't need the generality of a phase (MoveBinary is always
1247 -- done after linking and makes only sense in a parallel setup)   -- HWL
1248
1249 runPhase_MoveBinary :: DynFlags -> FilePath -> [PackageId] -> IO Bool
1250 runPhase_MoveBinary dflags input_fn dep_packages
1251     | WayPar `elem` (wayNames dflags) && not opt_Static =
1252         panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1253     | WayPar `elem` (wayNames dflags) = do
1254         let sysMan = pgm_sysman dflags
1255         pvm_root <- getEnv "PVM_ROOT"
1256         pvm_arch <- getEnv "PVM_ARCH"
1257         let
1258            pvm_executable_base = "=" ++ input_fn
1259            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1260         -- nuke old binary; maybe use configur'ed names for cp and rm?
1261         _ <- tryIO (removeFile pvm_executable)
1262         -- move the newly created binary into PVM land
1263         copy dflags "copying PVM executable" input_fn pvm_executable
1264         -- generate a wrapper script for running a parallel prg under PVM
1265         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1266         return True
1267     | not opt_Static =
1268         case (dynLibLoader dflags) of
1269           Wrapped wrapmode ->
1270               do
1271                 let (o_base, o_ext) = splitExtension input_fn
1272                 let wrapped_executable | o_ext == "exe" = (o_base ++ ".dyn") <.> o_ext
1273                                        | otherwise = input_fn ++ ".dyn"
1274                 behaviour <- wrapper_behaviour dflags wrapmode dep_packages
1275
1276                 -- THINKME isn't this possible to do a bit nicer?
1277                 let behaviour' = concatMap (\x -> if x=='\\' then "\\\\" else [x]) behaviour
1278                 renameFile input_fn wrapped_executable
1279                 let rtsDetails = (getPackageDetails (pkgState dflags) rtsPackageId);
1280                 SysTools.runCc dflags
1281                   ([ SysTools.FileOption "" ((head (libraryDirs rtsDetails)) ++ "/dyn-wrapper.c")
1282                    , SysTools.Option ("-DBEHAVIOUR=\"" ++ behaviour' ++ "\"")
1283                    , SysTools.Option "-o"
1284                    , SysTools.FileOption "" input_fn
1285                    ] ++ map (SysTools.FileOption "-I") (includeDirs rtsDetails))
1286                 return True
1287           _ -> return True
1288     | otherwise = return True
1289
1290 wrapper_behaviour :: DynFlags -> Maybe [Char] -> [PackageId] -> IO [Char]
1291 wrapper_behaviour dflags mode dep_packages =
1292     let seperateBySemiColon strs = tail $ concatMap (';':) strs
1293     in case mode of
1294       Nothing -> do
1295                 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1296                 return ('H' : (seperateBySemiColon pkg_lib_paths))
1297       Just s -> do
1298         allpkg <- getPreloadPackagesAnd dflags dep_packages
1299         putStrLn (unwords (map (packageIdString . packageConfigId) allpkg))
1300         return $ 'F':s ++ ';':(seperateBySemiColon (map (packageIdString . packageConfigId) allpkg))
1301
1302 mkExtraCObj :: DynFlags -> [String] -> IO FilePath
1303 mkExtraCObj dflags xs
1304  = do cFile <- newTempName dflags "c"
1305       oFile <- newTempName dflags "o"
1306       writeFile cFile $ unlines xs
1307       let rtsDetails = getPackageDetails (pkgState dflags) rtsPackageId
1308       SysTools.runCc dflags
1309                      ([Option        "-c",
1310                        FileOption "" cFile,
1311                        Option        "-o",
1312                        FileOption "" oFile] ++
1313                       map (FileOption "-I") (includeDirs rtsDetails))
1314       return oFile
1315
1316 -- generates a Perl skript starting a parallel prg under PVM
1317 mk_pvm_wrapper_script :: String -> String -> String -> String
1318 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1319  [
1320   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
1321   "  if $running_under_some_shell;",
1322   "# =!=!=!=!=!=!=!=!=!=!=!",
1323   "# This script is automatically generated: DO NOT EDIT!!!",
1324   "# Generated by Glasgow Haskell Compiler",
1325   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1326   "#",
1327   "$pvm_executable      = '" ++ pvm_executable ++ "';",
1328   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1329   "$SysMan = '" ++ sysMan ++ "';",
1330   "",
1331   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1332   "# first, some magical shortcuts to run "commands" on the binary",
1333   "# (which is hidden)",
1334   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1335   "    local($cmd) = $1;",
1336   "    system("$cmd $pvm_executable");",
1337   "    exit(0); # all done",
1338   "}", -}
1339   "",
1340   "# Now, run the real binary; process the args first",
1341   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
1342   "$debug = '';",
1343   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1344   "@nonPVM_args = ();",
1345   "$in_RTS_args = 0;",
1346   "",
1347   "args: while ($a = shift(@ARGV)) {",
1348   "    if ( $a eq '+RTS' ) {",
1349   "        $in_RTS_args = 1;",
1350   "    } elsif ( $a eq '-RTS' ) {",
1351   "        $in_RTS_args = 0;",
1352   "    }",
1353   "    if ( $a eq '-d' && $in_RTS_args ) {",
1354   "        $debug = '-';",
1355   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1356   "        $nprocessors = $1;",
1357   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1358   "        $nprocessors = $1;",
1359   "    } else {",
1360   "        push(@nonPVM_args, $a);",
1361   "    }",
1362   "}",
1363   "",
1364   "local($return_val) = 0;",
1365   "# Start the parallel execution by calling SysMan",
1366   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1367   "$return_val = $?;",
1368   "# ToDo: fix race condition moving files and flushing them!!",
1369   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1370   "exit($return_val);"
1371  ]
1372
1373 -----------------------------------------------------------------------------
1374 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1375
1376 getHCFilePackages :: FilePath -> IO [PackageId]
1377 getHCFilePackages filename =
1378   Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1379     l <- hGetLine h
1380     case l of
1381       '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1382           return (map stringToPackageId (words rest))
1383       _other ->
1384           return []
1385
1386 -----------------------------------------------------------------------------
1387 -- Static linking, of .o files
1388
1389 -- The list of packages passed to link is the list of packages on
1390 -- which this program depends, as discovered by the compilation
1391 -- manager.  It is combined with the list of packages that the user
1392 -- specifies on the command line with -package flags.  
1393 --
1394 -- In one-shot linking mode, we can't discover the package
1395 -- dependencies (because we haven't actually done any compilation or
1396 -- read any interface files), so the user must explicitly specify all
1397 -- the packages.
1398
1399 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1400 linkBinary dflags o_files dep_packages = do
1401     let verb = getVerbFlag dflags
1402         output_fn = exeFileName dflags
1403
1404     -- get the full list of packages to link with, by combining the
1405     -- explicit packages with the auto packages and all of their
1406     -- dependencies, and eliminating duplicates.
1407
1408     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1409     let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1410 #ifdef elf_OBJ_FORMAT
1411         get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1412                                 | otherwise = ["-L" ++ l]
1413 #else
1414         get_pkg_lib_path_opts l = ["-L" ++ l]
1415 #endif
1416
1417     let lib_paths = libraryPaths dflags
1418     let lib_path_opts = map ("-L"++) lib_paths
1419
1420     -- The C "main" function is not in the rts but in a separate static
1421     -- library libHSrtsmain.a that sits next to the rts lib files. Assuming
1422     -- we're using a Haskell main function then we need to link it in.
1423     let no_hs_main = dopt Opt_NoHsMain dflags
1424     let main_lib | no_hs_main = []
1425                  | otherwise  = [ "-lHSrtsmain" ]
1426     rtsEnabledObj <- if dopt Opt_RtsOptsEnabled dflags
1427                      then do fn <- mkExtraCObj dflags
1428                                     ["#include \"Rts.h\"",
1429                                      "const rtsBool rtsOptsEnabled = rtsTrue;"]
1430                              return [fn]
1431                      else return []
1432     rtsOptsObj <- case rtsOpts dflags of
1433                   Just opts ->
1434                       do fn <- mkExtraCObj dflags
1435                                  -- We assume that the Haskell "show" does
1436                                  -- the right thing here
1437                                  ["char *ghc_rts_opts = " ++ show opts ++ ";"]
1438                          return [fn]
1439                   Nothing -> return []
1440
1441     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1442
1443 #ifdef darwin_TARGET_OS
1444     pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1445     let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1446
1447     let framework_paths = frameworkPaths dflags
1448         framework_path_opts = map ("-F"++) framework_paths
1449
1450     pkg_frameworks <- getPackageFrameworks dflags dep_packages
1451     let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1452     
1453     let frameworks = cmdlineFrameworks dflags
1454         framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1455          -- reverse because they're added in reverse order from the cmd line
1456 #endif
1457         -- probably _stub.o files
1458     extra_ld_inputs <- readIORef v_Ld_inputs
1459
1460         -- opts from -optl-<blah> (including -l<blah> options)
1461     let extra_ld_opts = getOpts dflags opt_l
1462
1463     let ways = wayNames dflags
1464
1465     -- Here are some libs that need to be linked at the *end* of
1466     -- the command line, because they contain symbols that are referred to
1467     -- by the RTS.  We can't therefore use the ordinary way opts for these.
1468     let
1469         debug_opts | WayDebug `elem` ways = [ 
1470 #if defined(HAVE_LIBBFD)
1471                         "-lbfd", "-liberty"
1472 #endif
1473                          ]
1474                    | otherwise            = []
1475
1476     let
1477         thread_opts | WayThreaded `elem` ways = [ 
1478 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS) && !defined(haiku_TARGET_OS)
1479                         "-lpthread"
1480 #endif
1481 #if defined(osf3_TARGET_OS)
1482                         , "-lexc"
1483 #endif
1484                         ]
1485                     | otherwise               = []
1486
1487     rc_objs <- maybeCreateManifest dflags output_fn
1488
1489     let (md_c_flags, _) = machdepCCOpts dflags
1490     SysTools.runLink dflags ( 
1491                        [ SysTools.Option verb
1492                        , SysTools.Option "-o"
1493                        , SysTools.FileOption "" output_fn
1494                        ]
1495                       ++ map SysTools.Option (
1496                          md_c_flags
1497
1498 #ifdef mingw32_TARGET_OS
1499                       -- Permit the linker to auto link _symbol to _imp_symbol.
1500                       -- This lets us link against DLLs without needing an "import library".
1501                       ++ ["-Wl,--enable-auto-import"]
1502 #endif
1503                       ++ o_files
1504                       ++ extra_ld_inputs
1505                       ++ lib_path_opts
1506                       ++ extra_ld_opts
1507                       ++ rc_objs
1508 #ifdef darwin_TARGET_OS
1509                       ++ framework_path_opts
1510                       ++ framework_opts
1511 #endif
1512                       ++ pkg_lib_path_opts
1513                       ++ main_lib
1514                       ++ rtsEnabledObj
1515                       ++ rtsOptsObj
1516                       ++ pkg_link_opts
1517 #ifdef darwin_TARGET_OS
1518                       ++ pkg_framework_path_opts
1519                       ++ pkg_framework_opts
1520 #endif
1521                       ++ debug_opts
1522                       ++ thread_opts
1523                     ))
1524
1525     -- parallel only: move binary to another dir -- HWL
1526     success <- runPhase_MoveBinary dflags output_fn dep_packages
1527     if success then return ()
1528                else ghcError (InstallationError ("cannot move binary"))
1529
1530
1531 exeFileName :: DynFlags -> FilePath
1532 exeFileName dflags
1533   | Just s <- outputFile dflags =
1534 #if defined(mingw32_HOST_OS)
1535       if null (takeExtension s)
1536         then s <.> "exe"
1537         else s
1538 #else
1539       s
1540 #endif
1541   | otherwise = 
1542 #if defined(mingw32_HOST_OS)
1543         "main.exe"
1544 #else
1545         "a.out"
1546 #endif
1547
1548 maybeCreateManifest
1549    :: DynFlags
1550    -> FilePath                          -- filename of executable
1551    -> IO [FilePath]                     -- extra objects to embed, maybe
1552 #ifndef mingw32_TARGET_OS
1553 maybeCreateManifest _ _ = do
1554   return []
1555 #else
1556 maybeCreateManifest dflags exe_filename = do
1557   if not (dopt Opt_GenManifest dflags) then return [] else do
1558
1559   let manifest_filename = exe_filename <.> "manifest"
1560
1561   writeFile manifest_filename $ 
1562       "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1563       "  <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1564       "  <assemblyIdentity version=\"1.0.0.0\"\n"++
1565       "     processorArchitecture=\"X86\"\n"++
1566       "     name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1567       "     type=\"win32\"/>\n\n"++
1568       "  <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1569       "    <security>\n"++
1570       "      <requestedPrivileges>\n"++
1571       "        <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1572       "        </requestedPrivileges>\n"++
1573       "       </security>\n"++
1574       "  </trustInfo>\n"++
1575       "</assembly>\n"
1576
1577   -- Windows will find the manifest file if it is named foo.exe.manifest.
1578   -- However, for extra robustness, and so that we can move the binary around,
1579   -- we can embed the manifest in the binary itself using windres:
1580   if not (dopt Opt_EmbedManifest dflags) then return [] else do
1581
1582   rc_filename <- newTempName dflags "rc"
1583   rc_obj_filename <- newTempName dflags (objectSuf dflags)
1584
1585   writeFile rc_filename $
1586       "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1587         -- magic numbers :-)
1588         -- show is a bit hackish above, but we need to escape the
1589         -- backslashes in the path.
1590
1591   let wr_opts = getOpts dflags opt_windres
1592   runWindres dflags $ map SysTools.Option $
1593         ["--input="++rc_filename, 
1594          "--output="++rc_obj_filename,
1595          "--output-format=coff"] 
1596         ++ wr_opts
1597         -- no FileOptions here: windres doesn't like seeing
1598         -- backslashes, apparently
1599
1600   removeFile manifest_filename
1601
1602   return [rc_obj_filename]
1603 #endif
1604
1605
1606 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1607 linkDynLib dflags o_files dep_packages = do
1608     let verb = getVerbFlag dflags
1609     let o_file = outputFile dflags
1610
1611     -- We don't want to link our dynamic libs against the RTS package,
1612     -- because the RTS lib comes in several flavours and we want to be
1613     -- able to pick the flavour when a binary is linked.
1614     pkgs <- getPreloadPackagesAnd dflags dep_packages
1615
1616     -- On Windows we need to link the RTS import lib as Windows does
1617     -- not allow undefined symbols.
1618 #if !defined(mingw32_HOST_OS)
1619     let pkgs_no_rts = filter ((/= rtsPackageId) . packageConfigId) pkgs
1620 #else
1621     let pkgs_no_rts = pkgs
1622 #endif
1623     let pkg_lib_paths = collectLibraryPaths pkgs_no_rts
1624     let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1625 #ifdef elf_OBJ_FORMAT
1626         get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1627                                 | otherwise = ["-L" ++ l]
1628 #else
1629         get_pkg_lib_path_opts l = ["-L" ++ l]
1630 #endif
1631
1632     let lib_paths = libraryPaths dflags
1633     let lib_path_opts = map ("-L"++) lib_paths
1634
1635     let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1636
1637         -- probably _stub.o files
1638     extra_ld_inputs <- readIORef v_Ld_inputs
1639
1640     let (md_c_flags, _) = machdepCCOpts dflags
1641     let extra_ld_opts = getOpts dflags opt_l
1642 #if defined(mingw32_HOST_OS)
1643     -----------------------------------------------------------------------------
1644     -- Making a DLL
1645     -----------------------------------------------------------------------------
1646     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1647
1648     SysTools.runLink dflags
1649          ([ SysTools.Option verb
1650           , SysTools.Option "-o"
1651           , SysTools.FileOption "" output_fn
1652           , SysTools.Option "-shared"
1653           ] ++
1654           [ SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1655           | dopt Opt_SharedImplib dflags
1656           ]
1657          ++ map (SysTools.FileOption "") o_files
1658          ++ map SysTools.Option (
1659             md_c_flags
1660             
1661          -- Permit the linker to auto link _symbol to _imp_symbol
1662          -- This lets us link against DLLs without needing an "import library"
1663          ++ ["-Wl,--enable-auto-import"]
1664
1665          ++ extra_ld_inputs
1666          ++ lib_path_opts
1667          ++ extra_ld_opts
1668          ++ pkg_lib_path_opts
1669          ++ pkg_link_opts
1670         ))
1671 #elif defined(darwin_TARGET_OS)
1672     -----------------------------------------------------------------------------
1673     -- Making a darwin dylib
1674     -----------------------------------------------------------------------------
1675     -- About the options used for Darwin:
1676     -- -dynamiclib
1677     --   Apple's way of saying -shared
1678     -- -undefined dynamic_lookup:
1679     --   Without these options, we'd have to specify the correct dependencies
1680     --   for each of the dylibs. Note that we could (and should) do without this
1681     --   for all libraries except the RTS; all we need to do is to pass the
1682     --   correct HSfoo_dyn.dylib files to the link command.
1683     --   This feature requires Mac OS X 10.3 or later; there is a similar feature,
1684     --   -flat_namespace -undefined suppress, which works on earlier versions,
1685     --   but it has other disadvantages.
1686     -- -single_module
1687     --   Build the dynamic library as a single "module", i.e. no dynamic binding
1688     --   nonsense when referring to symbols from within the library. The NCG
1689     --   assumes that this option is specified (on i386, at least).
1690     -- -Wl,-macosx_version_min -Wl,10.3
1691     --   Tell the linker its safe to assume that the library will run on 10.3 or
1692     --   later, so that it will not complain about the use of the option
1693     --   -undefined dynamic_lookup above.
1694     -- -install_name
1695     --   Mac OS/X stores the path where a dynamic library is (to be) installed
1696     --   in the library itself.  It's called the "install name" of the library.
1697     --   Then any library or executable that links against it before it's
1698     --   installed will search for it in its ultimate install location.  By
1699     --   default we set the install name to the absolute path at build time, but
1700     --   it can be overridden by the -dylib-install-name option passed to ghc.
1701     --   Cabal does this.
1702     -----------------------------------------------------------------------------
1703
1704     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1705
1706     instName <- case dylibInstallName dflags of
1707         Just n -> return n
1708         Nothing -> do
1709             pwd <- getCurrentDirectory
1710             return $ pwd `combine` output_fn
1711     SysTools.runLink dflags
1712          ([ SysTools.Option verb
1713           , SysTools.Option "-dynamiclib"
1714           , SysTools.Option "-o"
1715           , SysTools.FileOption "" output_fn
1716           ]
1717          ++ map SysTools.Option (
1718             md_c_flags
1719          ++ o_files
1720          ++ [ "-undefined", "dynamic_lookup", "-single_module", "-Wl,-macosx_version_min","-Wl,10.5",
1721               "-Wl,-read_only_relocs,suppress", "-install_name", instName ]
1722          ++ extra_ld_inputs
1723          ++ lib_path_opts
1724          ++ extra_ld_opts
1725          ++ pkg_lib_path_opts
1726          ++ pkg_link_opts
1727         ))
1728 #else
1729     -----------------------------------------------------------------------------
1730     -- Making a DSO
1731     -----------------------------------------------------------------------------
1732
1733     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1734     let buildingRts = thisPackage dflags == rtsPackageId
1735     let bsymbolicFlag = if buildingRts
1736                         then -- -Bsymbolic breaks the way we implement
1737                              -- hooks in the RTS
1738                              []
1739                         else -- we need symbolic linking to resolve
1740                              -- non-PIC intra-package-relocations
1741                              ["-Wl,-Bsymbolic"]
1742
1743     SysTools.runLink dflags
1744          ([ SysTools.Option verb
1745           , SysTools.Option "-o"
1746           , SysTools.FileOption "" output_fn
1747           ]
1748          ++ map SysTools.Option (
1749             md_c_flags
1750          ++ o_files
1751          ++ [ "-shared" ]
1752          ++ bsymbolicFlag
1753          ++ [ "-Wl,-soname," ++ takeFileName output_fn ] -- set the library soname
1754          ++ extra_ld_inputs
1755          ++ lib_path_opts
1756          ++ extra_ld_opts
1757          ++ pkg_lib_path_opts
1758          ++ pkg_link_opts
1759         ))
1760 #endif
1761 -- -----------------------------------------------------------------------------
1762 -- Running CPP
1763
1764 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1765 doCpp dflags raw include_cc_opts input_fn output_fn = do
1766     let hscpp_opts = getOpts dflags opt_P
1767     let cmdline_include_paths = includePaths dflags
1768
1769     pkg_include_dirs <- getPackageIncludePath dflags []
1770     let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1771                           (cmdline_include_paths ++ pkg_include_dirs)
1772
1773     let verb = getVerbFlag dflags
1774
1775     let cc_opts
1776           | not include_cc_opts = []
1777           | otherwise           = (optc ++ md_c_flags)
1778                 where 
1779                       optc = getOpts dflags opt_c
1780                       (md_c_flags, _) = machdepCCOpts dflags
1781
1782     let cpp_prog args | raw       = SysTools.runCpp dflags args
1783                       | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1784
1785     let target_defs = 
1786           [ "-D" ++ HOST_OS     ++ "_BUILD_OS=1",
1787             "-D" ++ HOST_ARCH   ++ "_BUILD_ARCH=1",
1788             "-D" ++ TARGET_OS   ++ "_HOST_OS=1",
1789             "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1790         -- remember, in code we *compile*, the HOST is the same our TARGET,
1791         -- and BUILD is the same as our HOST.
1792
1793     cpp_prog       ([SysTools.Option verb]
1794                     ++ map SysTools.Option include_paths
1795                     ++ map SysTools.Option hsSourceCppOpts
1796                     ++ map SysTools.Option hscpp_opts
1797                     ++ map SysTools.Option cc_opts
1798                     ++ map SysTools.Option target_defs
1799                     ++ [ SysTools.Option     "-x"
1800                        , SysTools.Option     "c"
1801                        , SysTools.Option     input_fn
1802         -- We hackily use Option instead of FileOption here, so that the file
1803         -- name is not back-slashed on Windows.  cpp is capable of
1804         -- dealing with / in filenames, so it works fine.  Furthermore
1805         -- if we put in backslashes, cpp outputs #line directives
1806         -- with *double* backslashes.   And that in turn means that
1807         -- our error messages get double backslashes in them.
1808         -- In due course we should arrange that the lexer deals
1809         -- with these \\ escapes properly.
1810                        , SysTools.Option     "-o"
1811                        , SysTools.FileOption "" output_fn
1812                        ])
1813
1814 cHaskell1Version :: String
1815 cHaskell1Version = "5" -- i.e., Haskell 98
1816
1817 hsSourceCppOpts :: [String]
1818 -- Default CPP defines in Haskell source
1819 hsSourceCppOpts =
1820         [ "-D__HASKELL1__="++cHaskell1Version
1821         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
1822         , "-D__HASKELL98__"
1823         , "-D__CONCURRENT_HASKELL__"
1824         ]
1825
1826
1827 -- -----------------------------------------------------------------------------
1828 -- Misc.
1829
1830 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1831 hscNextPhase _ HsBootFile _        =  StopLn
1832 hscNextPhase dflags _ hsc_lang = 
1833   case hsc_lang of
1834         HscC -> HCc
1835         HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1836                | otherwise -> As
1837         HscNothing     -> StopLn
1838         HscInterpreted -> StopLn
1839         _other         -> StopLn
1840
1841
1842 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1843 hscMaybeAdjustTarget dflags stop _ current_hsc_lang 
1844   = hsc_lang 
1845   where
1846         keep_hc = dopt Opt_KeepHcFiles dflags
1847         hsc_lang
1848                 -- don't change the lang if we're interpreting
1849                  | current_hsc_lang == HscInterpreted = current_hsc_lang
1850
1851                 -- force -fvia-C if we are being asked for a .hc file
1852                  | HCc <- stop = HscC
1853                  | keep_hc     = HscC
1854                 -- otherwise, stick to the plan
1855                  | otherwise = current_hsc_lang
1856