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