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