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