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