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