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