iOS: generate archive files when compiling.
[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 | otherwise = "-O"
1121
1122 -- Decide next phase
1123 let next_phase = As
1124 output_fn <- phaseOutputFilename next_phase
1125
1126 let
1127 more_hcc_opts =
1128 -- on x86 the floating point regs have greater precision
1129 -- than a double, which leads to unpredictable results.
1130 -- By default, we turn this off with -ffloat-store unless
1131 -- the user specified -fexcess-precision.
1132 (if platformArch platform == ArchX86 &&
1133 not (gopt Opt_ExcessPrecision dflags)
1134 then [ "-ffloat-store" ]
1135 else []) ++
1136
1137 -- gcc's -fstrict-aliasing allows two accesses to memory
1138 -- to be considered non-aliasing if they have different types.
1139 -- This interacts badly with the C code we generate, which is
1140 -- very weakly typed, being derived from C--.
1141 ["-fno-strict-aliasing"]
1142
1143 let gcc_lang_opt | cc_phase `eqPhase` Ccpp = "c++"
1144 | cc_phase `eqPhase` Cobjc = "objective-c"
1145 | cc_phase `eqPhase` Cobjcpp = "objective-c++"
1146 | otherwise = "c"
1147 liftIO $ SysTools.runCc dflags (
1148 -- force the C compiler to interpret this file as C when
1149 -- compiling .hc files, by adding the -x c option.
1150 -- Also useful for plain .c files, just in case GHC saw a
1151 -- -x c option.
1152 [ SysTools.Option "-x", SysTools.Option gcc_lang_opt
1153 , SysTools.FileOption "" input_fn
1154 , SysTools.Option "-o"
1155 , SysTools.FileOption "" output_fn
1156 ]
1157 ++ map SysTools.Option (
1158 pic_c_flags
1159
1160 -- Stub files generated for foreign exports references the runIO_closure
1161 -- and runNonIO_closure symbols, which are defined in the base package.
1162 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1163 -- way we do the import depends on whether we're currently compiling
1164 -- the base package or not.
1165 ++ (if platformOS platform == OSMinGW32 &&
1166 thisPackage dflags == basePackageId
1167 then [ "-DCOMPILING_BASE_PACKAGE" ]
1168 else [])
1169
1170 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1171 -- instruction. Note that the user can still override this
1172 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1173 -- regardless of the ordering.
1174 --
1175 -- This is a temporary hack. See #2872, commit
1176 -- 5bd3072ac30216a505151601884ac88bf404c9f2
1177 ++ (if platformArch platform == ArchSPARC
1178 then ["-mcpu=v9"]
1179 else [])
1180
1181 -- GCC 4.6+ doesn't like -Wimplicit when compiling C++.
1182 ++ (if (cc_phase /= Ccpp && cc_phase /= Cobjcpp)
1183 then ["-Wimplicit"]
1184 else [])
1185
1186 ++ (if hcc
1187 then gcc_extra_viac_flags ++ more_hcc_opts
1188 else [])
1189 ++ verbFlags
1190 ++ [ "-S", cc_opt ]
1191 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1192 ++ framework_paths
1193 ++ split_opt
1194 ++ include_paths
1195 ++ pkg_extra_cc_opts
1196 ))
1197
1198 return (RealPhase next_phase, output_fn)
1199
1200 -----------------------------------------------------------------------------
1201 -- Splitting phase
1202
1203 runPhase (RealPhase Splitter) input_fn dflags
1204 = do -- tmp_pfx is the prefix used for the split .s files
1205
1206 split_s_prefix <- liftIO $ SysTools.newTempName dflags "split"
1207 let n_files_fn = split_s_prefix
1208
1209 liftIO $ SysTools.runSplit dflags
1210 [ SysTools.FileOption "" input_fn
1211 , SysTools.FileOption "" split_s_prefix
1212 , SysTools.FileOption "" n_files_fn
1213 ]
1214
1215 -- Save the number of split files for future references
1216 s <- liftIO $ readFile n_files_fn
1217 let n_files = read s :: Int
1218 dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1219
1220 setDynFlags dflags'
1221
1222 -- Remember to delete all these files
1223 liftIO $ addFilesToClean dflags'
1224 [ split_s_prefix ++ "__" ++ show n ++ ".s"
1225 | n <- [1..n_files]]
1226
1227 return (RealPhase SplitAs,
1228 "**splitter**") -- we don't use the filename in SplitAs
1229
1230 -----------------------------------------------------------------------------
1231 -- As, SpitAs phase : Assembler
1232
1233 -- This is for calling the assembler on a regular assembly file (not split).
1234 runPhase (RealPhase As) input_fn dflags
1235 = do
1236 -- LLVM from version 3.0 onwards doesn't support the OS X system
1237 -- assembler, so we use clang as the assembler instead. (#5636)
1238 let whichAsProg | hscTarget dflags == HscLlvm &&
1239 platformOS (targetPlatform dflags) == OSDarwin
1240 = do
1241 -- be careful what options we call clang with
1242 -- see #5903 and #7617 for bugs caused by this.
1243 llvmVer <- liftIO $ figureLlvmVersion dflags
1244 return $ case llvmVer of
1245 Just n | n >= 30 -> SysTools.runClang
1246 _ -> SysTools.runAs
1247
1248 | otherwise = return SysTools.runAs
1249
1250 as_prog <- whichAsProg
1251 let cmdline_include_paths = includePaths dflags
1252
1253 next_phase <- maybeMergeStub
1254 output_fn <- phaseOutputFilename next_phase
1255
1256 -- we create directories for the object file, because it
1257 -- might be a hierarchical module.
1258 liftIO $ createDirectoryIfMissing True (takeDirectory output_fn)
1259
1260 let runAssembler inputFilename outputFilename
1261 = liftIO $ as_prog dflags
1262 ([ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1263
1264 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1265 -- instruction so we have to make sure that the assembler accepts the
1266 -- instruction set. Note that the user can still override this
1267 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1268 -- regardless of the ordering.
1269 --
1270 -- This is a temporary hack.
1271 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
1272 then [SysTools.Option "-mcpu=v9"]
1273 else [])
1274
1275 ++ [ SysTools.Option "-x", SysTools.Option "assembler-with-cpp"
1276 , SysTools.Option "-c"
1277 , SysTools.FileOption "" inputFilename
1278 , SysTools.Option "-o"
1279 , SysTools.FileOption "" outputFilename
1280 ])
1281
1282 liftIO $ debugTraceMsg dflags 4 (text "Running the assembler")
1283 runAssembler input_fn output_fn
1284 return (RealPhase next_phase, output_fn)
1285
1286
1287 -- This is for calling the assembler on a split assembly file (so a collection
1288 -- of assembly files)
1289 runPhase (RealPhase SplitAs) _input_fn dflags
1290 = do
1291 -- we'll handle the stub_o file in this phase, so don't MergeStub,
1292 -- just jump straight to StopLn afterwards.
1293 let next_phase = StopLn
1294 output_fn <- phaseOutputFilename next_phase
1295
1296 let base_o = dropExtension output_fn
1297 osuf = objectSuf dflags
1298 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1299
1300 liftIO $ createDirectoryIfMissing True split_odir
1301
1302 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1303 -- later and we don't want to pick up any old objects.
1304 fs <- liftIO $ getDirectoryContents split_odir
1305 liftIO $ mapM_ removeFile $
1306 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1307
1308 let (split_s_prefix, n) = case splitInfo dflags of
1309 Nothing -> panic "No split info"
1310 Just x -> x
1311
1312 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1313
1314 split_obj :: Int -> FilePath
1315 split_obj n = split_odir </>
1316 takeFileName base_o ++ "__" ++ show n <.> osuf
1317
1318 let assemble_file n
1319 = SysTools.runAs dflags (
1320
1321 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1322 -- instruction so we have to make sure that the assembler accepts the
1323 -- instruction set. Note that the user can still override this
1324 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1325 -- regardless of the ordering.
1326 --
1327 -- This is a temporary hack.
1328 (if platformArch (targetPlatform dflags) == ArchSPARC
1329 then [SysTools.Option "-mcpu=v9"]
1330 else []) ++
1331
1332 [ SysTools.Option "-c"
1333 , SysTools.Option "-o"
1334 , SysTools.FileOption "" (split_obj n)
1335 , SysTools.FileOption "" (split_s n)
1336 ])
1337
1338 liftIO $ mapM_ assemble_file [1..n]
1339
1340 -- Note [pipeline-split-init]
1341 -- If we have a stub file, it may contain constructor
1342 -- functions for initialisation of this module. We can't
1343 -- simply leave the stub as a separate object file, because it
1344 -- will never be linked in: nothing refers to it. We need to
1345 -- ensure that if we ever refer to the data in this module
1346 -- that needs initialisation, then we also pull in the
1347 -- initialisation routine.
1348 --
1349 -- To that end, we make a DANGEROUS ASSUMPTION here: the data
1350 -- that needs to be initialised is all in the FIRST split
1351 -- object. See Note [codegen-split-init].
1352
1353 PipeState{maybe_stub_o} <- getPipeState
1354 case maybe_stub_o of
1355 Nothing -> return ()
1356 Just stub_o -> liftIO $ do
1357 tmp_split_1 <- newTempName dflags osuf
1358 let split_1 = split_obj 1
1359 copyFile split_1 tmp_split_1
1360 removeFile split_1
1361 joinObjectFiles dflags [tmp_split_1, stub_o] split_1
1362
1363 -- join them into a single .o file
1364 liftIO $ joinObjectFiles dflags (map split_obj [1..n]) output_fn
1365
1366 return (RealPhase next_phase, output_fn)
1367
1368 -----------------------------------------------------------------------------
1369 -- LlvmOpt phase
1370
1371 runPhase (RealPhase LlvmOpt) input_fn dflags
1372 = do
1373 ver <- liftIO $ readIORef (llvmVersion dflags)
1374
1375 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1376 -- don't specify anything if user has specified commands. We do this
1377 -- for opt but not llc since opt is very specifically for optimisation
1378 -- passes only, so if the user is passing us extra options we assume
1379 -- they know what they are doing and don't get in the way.
1380 optFlag = if null (getOpts dflags opt_lo)
1381 then map SysTools.Option $ words (llvmOpts !! opt_lvl)
1382 else []
1383 tbaa | ver < 29 = "" -- no tbaa in 2.8 and earlier
1384 | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true"
1385 | otherwise = "--enable-tbaa=false"
1386
1387
1388 output_fn <- phaseOutputFilename LlvmLlc
1389
1390 liftIO $ SysTools.runLlvmOpt dflags
1391 ([ SysTools.FileOption "" input_fn,
1392 SysTools.Option "-o",
1393 SysTools.FileOption "" output_fn]
1394 ++ optFlag
1395 ++ [SysTools.Option tbaa])
1396
1397 return (RealPhase LlvmLlc, output_fn)
1398 where
1399 -- we always (unless -optlo specified) run Opt since we rely on it to
1400 -- fix up some pretty big deficiencies in the code we generate
1401 llvmOpts = ["-mem2reg -globalopt", "-O1", "-O2"]
1402
1403 -----------------------------------------------------------------------------
1404 -- LlvmLlc phase
1405
1406 runPhase (RealPhase LlvmLlc) input_fn dflags
1407 = do
1408 ver <- liftIO $ readIORef (llvmVersion dflags)
1409
1410 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1411 -- iOS requires external references to be loaded indirectly from the
1412 -- DATA segment or dyld traps at runtime writing into TEXT: see #7722
1413 rmodel | platformOS (targetPlatform dflags) == OSiOS = "dynamic-no-pic"
1414 | gopt Opt_PIC dflags = "pic"
1415 | not (gopt Opt_Static dflags) = "dynamic-no-pic"
1416 | otherwise = "static"
1417 tbaa | ver < 29 = "" -- no tbaa in 2.8 and earlier
1418 | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true"
1419 | otherwise = "--enable-tbaa=false"
1420
1421 -- hidden debugging flag '-dno-llvm-mangler' to skip mangling
1422 let next_phase = case gopt Opt_NoLlvmMangler dflags of
1423 False -> LlvmMangle
1424 True | gopt Opt_SplitObjs dflags -> Splitter
1425 True -> As
1426
1427 output_fn <- phaseOutputFilename next_phase
1428
1429 liftIO $ SysTools.runLlvmLlc dflags
1430 ([ SysTools.Option (llvmOpts !! opt_lvl),
1431 SysTools.Option $ "-relocation-model=" ++ rmodel,
1432 SysTools.FileOption "" input_fn,
1433 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1434 ++ [SysTools.Option tbaa]
1435 ++ map SysTools.Option fpOpts
1436 ++ map SysTools.Option abiOpts
1437 ++ map SysTools.Option sseOpts)
1438
1439 return (RealPhase next_phase, output_fn)
1440 where
1441 -- Bug in LLVM at O3 on OSX.
1442 llvmOpts = if platformOS (targetPlatform dflags) == OSDarwin
1443 then ["-O1", "-O2", "-O2"]
1444 else ["-O1", "-O2", "-O3"]
1445 -- On ARMv7 using LLVM, LLVM fails to allocate floating point registers
1446 -- while compiling GHC source code. It's probably due to fact that it
1447 -- does not enable VFP by default. Let's do this manually here
1448 fpOpts = case platformArch (targetPlatform dflags) of
1449 ArchARM ARMv7 ext _ -> if (elem VFPv3 ext)
1450 then ["-mattr=+v7,+vfp3"]
1451 else if (elem VFPv3D16 ext)
1452 then ["-mattr=+v7,+vfp3,+d16"]
1453 else []
1454 ArchARM ARMv6 ext _ -> if (elem VFPv2 ext)
1455 then ["-mattr=+v6,+vfp2"]
1456 else ["-mattr=+v6"]
1457 _ -> []
1458 -- On Ubuntu/Debian with ARM hard float ABI, LLVM's llc still
1459 -- compiles into soft-float ABI. We need to explicitly set abi
1460 -- to hard
1461 abiOpts = case platformArch (targetPlatform dflags) of
1462 ArchARM _ _ HARD -> ["-float-abi=hard"]
1463 ArchARM _ _ _ -> []
1464 _ -> []
1465
1466 sseOpts | isSse4_2Enabled dflags = ["-mattr=+sse42"]
1467 | isSse2Enabled dflags = ["-mattr=+sse2"]
1468 | otherwise = []
1469
1470 -----------------------------------------------------------------------------
1471 -- LlvmMangle phase
1472
1473 runPhase (RealPhase LlvmMangle) input_fn dflags
1474 = do
1475 let next_phase = if gopt Opt_SplitObjs dflags then Splitter else As
1476 output_fn <- phaseOutputFilename next_phase
1477 liftIO $ llvmFixupAsm dflags input_fn output_fn
1478 return (RealPhase next_phase, output_fn)
1479
1480 -----------------------------------------------------------------------------
1481 -- merge in stub objects
1482
1483 runPhase (RealPhase MergeStub) input_fn dflags
1484 = do
1485 PipeState{maybe_stub_o} <- getPipeState
1486 output_fn <- phaseOutputFilename StopLn
1487 case maybe_stub_o of
1488 Nothing ->
1489 panic "runPhase(MergeStub): no stub"
1490 Just stub_o -> do
1491 liftIO $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1492 return (RealPhase StopLn, output_fn)
1493
1494 -- warning suppression
1495 runPhase (RealPhase other) _input_fn _dflags =
1496 panic ("runPhase: don't know how to run phase " ++ show other)
1497
1498 maybeMergeStub :: CompPipeline Phase
1499 maybeMergeStub
1500 = do
1501 PipeState{maybe_stub_o} <- getPipeState
1502 if isJust maybe_stub_o then return MergeStub else return StopLn
1503
1504 getLocation :: HscSource -> ModuleName -> CompPipeline ModLocation
1505 getLocation src_flavour mod_name = do
1506 dflags <- getDynFlags
1507
1508 PipeEnv{ src_basename=basename,
1509 src_suffix=suff } <- getPipeEnv
1510
1511 -- Build a ModLocation to pass to hscMain.
1512 -- The source filename is rather irrelevant by now, but it's used
1513 -- by hscMain for messages. hscMain also needs
1514 -- the .hi and .o filenames, and this is as good a way
1515 -- as any to generate them, and better than most. (e.g. takes
1516 -- into account the -osuf flags)
1517 location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff
1518
1519 -- Boot-ify it if necessary
1520 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
1521 | otherwise = location1
1522
1523
1524 -- Take -ohi into account if present
1525 -- This can't be done in mkHomeModuleLocation because
1526 -- it only applies to the module being compiles
1527 let ohi = outputHi dflags
1528 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
1529 | otherwise = location2
1530
1531 -- Take -o into account if present
1532 -- Very like -ohi, but we must *only* do this if we aren't linking
1533 -- (If we're linking then the -o applies to the linked thing, not to
1534 -- the object file for one module.)
1535 -- Note the nasty duplication with the same computation in compileFile above
1536 let expl_o_file = outputFile dflags
1537 location4 | Just ofile <- expl_o_file
1538 , isNoLink (ghcLink dflags)
1539 = location3 { ml_obj_file = ofile }
1540 | otherwise = location3
1541
1542 return location4
1543
1544 -----------------------------------------------------------------------------
1545 -- MoveBinary sort-of-phase
1546 -- After having produced a binary, move it somewhere else and generate a
1547 -- wrapper script calling the binary. Currently, we need this only in
1548 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1549 -- central directory.
1550 -- This is called from linkBinary below, after linking. I haven't made it
1551 -- a separate phase to minimise interfering with other modules, and
1552 -- we don't need the generality of a phase (MoveBinary is always
1553 -- done after linking and makes only sense in a parallel setup) -- HWL
1554
1555 runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool
1556 runPhase_MoveBinary dflags input_fn
1557 | WayPar `elem` ways dflags && not (gopt Opt_Static dflags) =
1558 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1559 | WayPar `elem` ways dflags = do
1560 let sysMan = pgm_sysman dflags
1561 pvm_root <- getEnv "PVM_ROOT"
1562 pvm_arch <- getEnv "PVM_ARCH"
1563 let
1564 pvm_executable_base = "=" ++ input_fn
1565 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1566 -- nuke old binary; maybe use configur'ed names for cp and rm?
1567 _ <- tryIO (removeFile pvm_executable)
1568 -- move the newly created binary into PVM land
1569 copy dflags "copying PVM executable" input_fn pvm_executable
1570 -- generate a wrapper script for running a parallel prg under PVM
1571 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1572 return True
1573 | otherwise = return True
1574
1575 mkExtraObj :: DynFlags -> Suffix -> String -> IO FilePath
1576 mkExtraObj dflags extn xs
1577 = do cFile <- newTempName dflags extn
1578 oFile <- newTempName dflags "o"
1579 writeFile cFile xs
1580 let rtsDetails = getPackageDetails (pkgState dflags) rtsPackageId
1581 SysTools.runCc dflags
1582 ([Option "-c",
1583 FileOption "" cFile,
1584 Option "-o",
1585 FileOption "" oFile]
1586 ++ map (FileOption "-I") (includeDirs rtsDetails))
1587 return oFile
1588
1589 -- When linking a binary, we need to create a C main() function that
1590 -- starts everything off. This used to be compiled statically as part
1591 -- of the RTS, but that made it hard to change the -rtsopts setting,
1592 -- so now we generate and compile a main() stub as part of every
1593 -- binary and pass the -rtsopts setting directly to the RTS (#5373)
1594 --
1595 mkExtraObjToLinkIntoBinary :: DynFlags -> IO FilePath
1596 mkExtraObjToLinkIntoBinary dflags = do
1597 when (gopt Opt_NoHsMain dflags && haveRtsOptsFlags dflags) $ do
1598 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
1599 (text "Warning: -rtsopts and -with-rtsopts have no effect with -no-hs-main." $$
1600 text " Call hs_init_ghc() from your main() function to set these options.")
1601
1602 mkExtraObj dflags "c" (showSDoc dflags main)
1603
1604 where
1605 main
1606 | gopt Opt_NoHsMain dflags = empty
1607 | otherwise = vcat [
1608 ptext (sLit "#include \"Rts.h\""),
1609 ptext (sLit "extern StgClosure ZCMain_main_closure;"),
1610 ptext (sLit "int main(int argc, char *argv[])"),
1611 char '{',
1612 ptext (sLit " RtsConfig __conf = defaultRtsConfig;"),
1613 ptext (sLit " __conf.rts_opts_enabled = ")
1614 <> text (show (rtsOptsEnabled dflags)) <> semi,
1615 case rtsOpts dflags of
1616 Nothing -> empty
1617 Just opts -> ptext (sLit " __conf.rts_opts= ") <>
1618 text (show opts) <> semi,
1619 ptext (sLit " return hs_main(argc, argv, &ZCMain_main_closure,__conf);"),
1620 char '}',
1621 char '\n' -- final newline, to keep gcc happy
1622 ]
1623
1624 -- Write out the link info section into a new assembly file. Previously
1625 -- this was included as inline assembly in the main.c file but this
1626 -- is pretty fragile. gas gets upset trying to calculate relative offsets
1627 -- that span the .note section (notably .text) when debug info is present
1628 mkNoteObjsToLinkIntoBinary :: DynFlags -> [PackageId] -> IO [FilePath]
1629 mkNoteObjsToLinkIntoBinary dflags dep_packages = do
1630 link_info <- getLinkInfo dflags dep_packages
1631
1632 if (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
1633 then fmap (:[]) $ mkExtraObj dflags "s" (showSDoc dflags (link_opts link_info))
1634 else return []
1635
1636 where
1637 link_opts info = hcat [
1638 text "\t.section ", text ghcLinkInfoSectionName,
1639 text ",\"\",",
1640 text elfSectionNote,
1641 text "\n",
1642
1643 text "\t.ascii \"", info', text "\"\n",
1644
1645 -- ALL generated assembly must have this section to disable
1646 -- executable stacks. See also
1647 -- compiler/nativeGen/AsmCodeGen.lhs for another instance
1648 -- where we need to do this.
1649 (if platformHasGnuNonexecStack (targetPlatform dflags)
1650 then text ".section .note.GNU-stack,\"\",@progbits\n"
1651 else empty)
1652
1653 ]
1654 where
1655 info' = text $ escape info
1656
1657 escape :: String -> String
1658 escape = concatMap (charToC.fromIntegral.ord)
1659
1660 elfSectionNote :: String
1661 elfSectionNote = case platformArch (targetPlatform dflags) of
1662 ArchARM _ _ _ -> "%note"
1663 _ -> "@note"
1664
1665 -- The "link info" is a string representing the parameters of the
1666 -- link. We save this information in the binary, and the next time we
1667 -- link, if nothing else has changed, we use the link info stored in
1668 -- the existing binary to decide whether to re-link or not.
1669 getLinkInfo :: DynFlags -> [PackageId] -> IO String
1670 getLinkInfo dflags dep_packages = do
1671 package_link_opts <- getPackageLinkOpts dflags dep_packages
1672 pkg_frameworks <- if platformUsesFrameworks (targetPlatform dflags)
1673 then getPackageFrameworks dflags dep_packages
1674 else return []
1675 let extra_ld_inputs = ldInputs dflags
1676 let
1677 link_info = (package_link_opts,
1678 pkg_frameworks,
1679 rtsOpts dflags,
1680 rtsOptsEnabled dflags,
1681 gopt Opt_NoHsMain dflags,
1682 map showOpt extra_ld_inputs,
1683 getOpts dflags opt_l)
1684 --
1685 return (show link_info)
1686
1687 -- generates a Perl skript starting a parallel prg under PVM
1688 mk_pvm_wrapper_script :: String -> String -> String -> String
1689 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1690 [
1691 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1692 " if $running_under_some_shell;",
1693 "# =!=!=!=!=!=!=!=!=!=!=!",
1694 "# This script is automatically generated: DO NOT EDIT!!!",
1695 "# Generated by Glasgow Haskell Compiler",
1696 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1697 "#",
1698 "$pvm_executable = '" ++ pvm_executable ++ "';",
1699 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1700 "$SysMan = '" ++ sysMan ++ "';",
1701 "",
1702 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1703 "# first, some magical shortcuts to run "commands" on the binary",
1704 "# (which is hidden)",
1705 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1706 " local($cmd) = $1;",
1707 " system("$cmd $pvm_executable");",
1708 " exit(0); # all done",
1709 "}", -}
1710 "",
1711 "# Now, run the real binary; process the args first",
1712 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1713 "$debug = '';",
1714 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1715 "@nonPVM_args = ();",
1716 "$in_RTS_args = 0;",
1717 "",
1718 "args: while ($a = shift(@ARGV)) {",
1719 " if ( $a eq '+RTS' ) {",
1720 " $in_RTS_args = 1;",
1721 " } elsif ( $a eq '-RTS' ) {",
1722 " $in_RTS_args = 0;",
1723 " }",
1724 " if ( $a eq '-d' && $in_RTS_args ) {",
1725 " $debug = '-';",
1726 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1727 " $nprocessors = $1;",
1728 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1729 " $nprocessors = $1;",
1730 " } else {",
1731 " push(@nonPVM_args, $a);",
1732 " }",
1733 "}",
1734 "",
1735 "local($return_val) = 0;",
1736 "# Start the parallel execution by calling SysMan",
1737 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1738 "$return_val = $?;",
1739 "# ToDo: fix race condition moving files and flushing them!!",
1740 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1741 "exit($return_val);"
1742 ]
1743
1744 -----------------------------------------------------------------------------
1745 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1746
1747 getHCFilePackages :: FilePath -> IO [PackageId]
1748 getHCFilePackages filename =
1749 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1750 l <- hGetLine h
1751 case l of
1752 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1753 return (map stringToPackageId (words rest))
1754 _other ->
1755 return []
1756
1757 -----------------------------------------------------------------------------
1758 -- Static linking, of .o files
1759
1760 -- The list of packages passed to link is the list of packages on
1761 -- which this program depends, as discovered by the compilation
1762 -- manager. It is combined with the list of packages that the user
1763 -- specifies on the command line with -package flags.
1764 --
1765 -- In one-shot linking mode, we can't discover the package
1766 -- dependencies (because we haven't actually done any compilation or
1767 -- read any interface files), so the user must explicitly specify all
1768 -- the packages.
1769
1770 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1771 linkBinary dflags o_files dep_packages = do
1772 let platform = targetPlatform dflags
1773 mySettings = settings dflags
1774 verbFlags = getVerbFlags dflags
1775 output_fn = exeFileName dflags
1776
1777 -- get the full list of packages to link with, by combining the
1778 -- explicit packages with the auto packages and all of their
1779 -- dependencies, and eliminating duplicates.
1780
1781 full_output_fn <- if isAbsolute output_fn
1782 then return output_fn
1783 else do d <- getCurrentDirectory
1784 return $ normalise (d </> output_fn)
1785 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1786 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1787 get_pkg_lib_path_opts l
1788 | osElfTarget (platformOS platform) &&
1789 dynLibLoader dflags == SystemDependent &&
1790 not (gopt Opt_Static dflags)
1791 = let libpath = if gopt Opt_RelativeDynlibPaths dflags
1792 then "$ORIGIN" </>
1793 (l `makeRelativeTo` full_output_fn)
1794 else l
1795 rpath = if gopt Opt_RPath dflags
1796 then ["-Wl,-rpath", "-Wl," ++ libpath]
1797 else []
1798 -- Solaris 11's linker does not support -rpath-link option. It silently
1799 -- ignores it and then complains about next option which is -l<some
1800 -- dir> as being a directory and not expected object file, E.g
1801 -- ld: elf error: file
1802 -- /tmp/ghc-src/libraries/base/dist-install/build:
1803 -- elf_begin: I/O error: region read: Is a directory
1804 rpathlink = if (platformOS platform) == OSSolaris2
1805 then []
1806 else ["-Wl,-rpath-link", "-Wl," ++ l]
1807 in ["-L" ++ l] ++ rpathlink ++ rpath
1808 | otherwise = ["-L" ++ l]
1809
1810 let lib_paths = libraryPaths dflags
1811 let lib_path_opts = map ("-L"++) lib_paths
1812
1813 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags
1814 noteLinkObjs <- mkNoteObjsToLinkIntoBinary dflags dep_packages
1815
1816 pkg_link_opts <- if platformBinariesAreStaticLibs platform
1817 then -- If building an executable really means
1818 -- making a static library (e.g. iOS), then
1819 -- we don't want the options (like -lm)
1820 -- that getPackageLinkOpts gives us. #7720
1821 return []
1822 else getPackageLinkOpts dflags dep_packages
1823
1824 pkg_framework_path_opts <-
1825 if platformUsesFrameworks platform
1826 then do pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1827 return $ map ("-F" ++) pkg_framework_paths
1828 else return []
1829
1830 framework_path_opts <-
1831 if platformUsesFrameworks platform
1832 then do let framework_paths = frameworkPaths dflags
1833 return $ map ("-F" ++) framework_paths
1834 else return []
1835
1836 pkg_framework_opts <-
1837 if platformUsesFrameworks platform
1838 then do pkg_frameworks <- getPackageFrameworks dflags dep_packages
1839 return $ concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1840 else return []
1841
1842 framework_opts <-
1843 if platformUsesFrameworks platform
1844 then do let frameworks = cmdlineFrameworks dflags
1845 -- reverse because they're added in reverse order from
1846 -- the cmd line:
1847 return $ concat [ ["-framework", fw]
1848 | fw <- reverse frameworks ]
1849 else return []
1850
1851 -- probably _stub.o files
1852 let extra_ld_inputs = ldInputs dflags
1853
1854 -- Here are some libs that need to be linked at the *end* of
1855 -- the command line, because they contain symbols that are referred to
1856 -- by the RTS. We can't therefore use the ordinary way opts for these.
1857 let
1858 debug_opts | WayDebug `elem` ways dflags = [
1859 #if defined(HAVE_LIBBFD)
1860 "-lbfd", "-liberty"
1861 #endif
1862 ]
1863 | otherwise = []
1864
1865 let thread_opts
1866 | WayThreaded `elem` ways dflags =
1867 let os = platformOS (targetPlatform dflags)
1868 in if os == OSOsf3 then ["-lpthread", "-lexc"]
1869 else if os `elem` [OSMinGW32, OSFreeBSD, OSOpenBSD,
1870 OSNetBSD, OSHaiku, OSQNXNTO]
1871 then []
1872 else ["-lpthread"]
1873 | otherwise = []
1874
1875 rc_objs <- maybeCreateManifest dflags output_fn
1876
1877 SysTools.runLink dflags (
1878 map SysTools.Option verbFlags
1879 ++ [ SysTools.Option "-o"
1880 , SysTools.FileOption "" output_fn
1881 ]
1882 ++ map SysTools.Option (
1883 []
1884
1885 -- Permit the linker to auto link _symbol to _imp_symbol.
1886 -- This lets us link against DLLs without needing an "import library".
1887 ++ (if platformOS platform == OSMinGW32
1888 then ["-Wl,--enable-auto-import"]
1889 else [])
1890
1891 -- '-no_compact_unwind'
1892 -- C++/Objective-C exceptions cannot use optimised
1893 -- stack unwinding code. The optimised form is the
1894 -- default in Xcode 4 on at least x86_64, and
1895 -- without this flag we're also seeing warnings
1896 -- like
1897 -- ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog
1898 -- on x86.
1899 ++ (if sLdSupportsCompactUnwind mySettings &&
1900 platformOS platform == OSDarwin &&
1901 platformArch platform `elem` [ArchX86, ArchX86_64]
1902 then ["-Wl,-no_compact_unwind"]
1903 else [])
1904
1905 -- '-Wl,-read_only_relocs,suppress'
1906 -- ld gives loads of warnings like:
1907 -- ld: warning: text reloc in _base_GHCziArr_unsafeArray_info to _base_GHCziArr_unsafeArray_closure
1908 -- when linking any program. We're not sure
1909 -- whether this is something we ought to fix, but
1910 -- for now this flags silences them.
1911 ++ (if platformOS platform == OSDarwin &&
1912 platformArch platform == ArchX86
1913 then ["-Wl,-read_only_relocs,suppress"]
1914 else [])
1915
1916 ++ o_files
1917 ++ lib_path_opts)
1918 ++ extra_ld_inputs
1919 ++ map SysTools.Option (
1920 rc_objs
1921 ++ framework_path_opts
1922 ++ framework_opts
1923 ++ pkg_lib_path_opts
1924 ++ extraLinkObj:noteLinkObjs
1925 ++ pkg_link_opts
1926 ++ pkg_framework_path_opts
1927 ++ pkg_framework_opts
1928 ++ debug_opts
1929 ++ thread_opts
1930 ))
1931
1932 -- parallel only: move binary to another dir -- HWL
1933 success <- runPhase_MoveBinary dflags output_fn
1934 unless success $
1935 throwGhcExceptionIO (InstallationError ("cannot move binary"))
1936
1937
1938 exeFileName :: DynFlags -> FilePath
1939 exeFileName dflags
1940 | Just s <- outputFile dflags =
1941 case platformOS (targetPlatform dflags) of
1942 OSMinGW32 -> s <?.> "exe"
1943 OSiOS -> s <?.> "a"
1944 _ -> s
1945 | otherwise =
1946 if platformOS (targetPlatform dflags) == OSMinGW32
1947 then "main.exe"
1948 else "a.out"
1949 where s <?.> ext | null (takeExtension s) = s <.> ext
1950 | otherwise = s
1951
1952 maybeCreateManifest
1953 :: DynFlags
1954 -> FilePath -- filename of executable
1955 -> IO [FilePath] -- extra objects to embed, maybe
1956 maybeCreateManifest dflags exe_filename
1957 | platformOS (targetPlatform dflags) == OSMinGW32 &&
1958 gopt Opt_GenManifest dflags
1959 = do let manifest_filename = exe_filename <.> "manifest"
1960
1961 writeFile manifest_filename $
1962 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1963 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1964 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1965 " processorArchitecture=\"X86\"\n"++
1966 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1967 " type=\"win32\"/>\n\n"++
1968 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1969 " <security>\n"++
1970 " <requestedPrivileges>\n"++
1971 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1972 " </requestedPrivileges>\n"++
1973 " </security>\n"++
1974 " </trustInfo>\n"++
1975 "</assembly>\n"
1976
1977 -- Windows will find the manifest file if it is named
1978 -- foo.exe.manifest. However, for extra robustness, and so that
1979 -- we can move the binary around, we can embed the manifest in
1980 -- the binary itself using windres:
1981 if not (gopt Opt_EmbedManifest dflags) then return [] else do
1982
1983 rc_filename <- newTempName dflags "rc"
1984 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1985
1986 writeFile rc_filename $
1987 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1988 -- magic numbers :-)
1989 -- show is a bit hackish above, but we need to escape the
1990 -- backslashes in the path.
1991
1992 runWindres dflags $ map SysTools.Option $
1993 ["--input="++rc_filename,
1994 "--output="++rc_obj_filename,
1995 "--output-format=coff"]
1996 -- no FileOptions here: windres doesn't like seeing
1997 -- backslashes, apparently
1998
1999 removeFile manifest_filename
2000
2001 return [rc_obj_filename]
2002 | otherwise = return []
2003
2004
2005 linkDynLibCheck :: DynFlags -> [String] -> [PackageId] -> IO ()
2006 linkDynLibCheck dflags o_files dep_packages
2007 = do
2008 when (haveRtsOptsFlags dflags) $ do
2009 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
2010 (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$
2011 text " Call hs_init_ghc() from your main() function to set these options.")
2012
2013 linkDynLib dflags o_files dep_packages
2014
2015 -- -----------------------------------------------------------------------------
2016 -- Running CPP
2017
2018 doCpp :: DynFlags -> Bool -> FilePath -> FilePath -> IO ()
2019 doCpp dflags raw input_fn output_fn = do
2020 let hscpp_opts = picPOpts dflags
2021 let cmdline_include_paths = includePaths dflags
2022
2023 pkg_include_dirs <- getPackageIncludePath dflags []
2024 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
2025 (cmdline_include_paths ++ pkg_include_dirs)
2026
2027 let verbFlags = getVerbFlags dflags
2028
2029 let cpp_prog args | raw = SysTools.runCpp dflags args
2030 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
2031
2032 let target_defs =
2033 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
2034 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
2035 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
2036 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
2037 -- remember, in code we *compile*, the HOST is the same our TARGET,
2038 -- and BUILD is the same as our HOST.
2039
2040 let sse2 = isSse2Enabled dflags
2041 sse4_2 = isSse4_2Enabled dflags
2042 sse_defs =
2043 [ "-D__SSE__=1" | sse2 || sse4_2 ] ++
2044 [ "-D__SSE2__=1" | sse2 || sse4_2 ] ++
2045 [ "-D__SSE4_2__=1" | sse4_2 ]
2046
2047 backend_defs <- getBackendDefs dflags
2048
2049 cpp_prog ( map SysTools.Option verbFlags
2050 ++ map SysTools.Option include_paths
2051 ++ map SysTools.Option hsSourceCppOpts
2052 ++ map SysTools.Option target_defs
2053 ++ map SysTools.Option backend_defs
2054 ++ map SysTools.Option hscpp_opts
2055 ++ map SysTools.Option sse_defs
2056 -- Set the language mode to assembler-with-cpp when preprocessing. This
2057 -- alleviates some of the C99 macro rules relating to whitespace and the hash
2058 -- operator, which we tend to abuse. Clang in particular is not very happy
2059 -- about this.
2060 ++ [ SysTools.Option "-x"
2061 , SysTools.Option "assembler-with-cpp"
2062 , SysTools.Option input_fn
2063 -- We hackily use Option instead of FileOption here, so that the file
2064 -- name is not back-slashed on Windows. cpp is capable of
2065 -- dealing with / in filenames, so it works fine. Furthermore
2066 -- if we put in backslashes, cpp outputs #line directives
2067 -- with *double* backslashes. And that in turn means that
2068 -- our error messages get double backslashes in them.
2069 -- In due course we should arrange that the lexer deals
2070 -- with these \\ escapes properly.
2071 , SysTools.Option "-o"
2072 , SysTools.FileOption "" output_fn
2073 ])
2074
2075 getBackendDefs :: DynFlags -> IO [String]
2076 getBackendDefs dflags | hscTarget dflags == HscLlvm = do
2077 llvmVer <- figureLlvmVersion dflags
2078 return [ "-D__GLASGOW_HASKELL_LLVM__="++show llvmVer ]
2079
2080 getBackendDefs _ =
2081 return []
2082
2083 hsSourceCppOpts :: [String]
2084 -- Default CPP defines in Haskell source
2085 hsSourceCppOpts =
2086 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
2087
2088 -- ---------------------------------------------------------------------------
2089 -- join object files into a single relocatable object file, using ld -r
2090
2091 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
2092 joinObjectFiles dflags o_files output_fn = do
2093 let mySettings = settings dflags
2094 ldIsGnuLd = sLdIsGnuLd mySettings
2095 ld_r args = SysTools.runLink dflags ([
2096 SysTools.Option "-nostdlib",
2097 SysTools.Option "-nodefaultlibs",
2098 SysTools.Option "-Wl,-r"
2099 ]
2100 -- gcc on sparc sets -Wl,--relax implicitly, but
2101 -- -r and --relax are incompatible for ld, so
2102 -- disable --relax explicitly.
2103 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
2104 && ldIsGnuLd
2105 then [SysTools.Option "-Wl,-no-relax"]
2106 else [])
2107 ++ map SysTools.Option ld_build_id
2108 ++ [ SysTools.Option "-o",
2109 SysTools.FileOption "" output_fn ]
2110 ++ args)
2111
2112 -- suppress the generation of the .note.gnu.build-id section,
2113 -- which we don't need and sometimes causes ld to emit a
2114 -- warning:
2115 ld_build_id | sLdSupportsBuildId mySettings = ["-Wl,--build-id=none"]
2116 | otherwise = []
2117
2118 if ldIsGnuLd
2119 then do
2120 script <- newTempName dflags "ldscript"
2121 writeFile script $ "INPUT(" ++ unwords o_files ++ ")"
2122 ld_r [SysTools.FileOption "" script]
2123 else if sLdSupportsFilelist mySettings
2124 then do
2125 filelist <- newTempName dflags "filelist"
2126 writeFile filelist $ unlines o_files
2127 ld_r [SysTools.Option "-Wl,-filelist",
2128 SysTools.FileOption "-Wl," filelist]
2129 else do
2130 ld_r (map (SysTools.FileOption "") o_files)
2131
2132 -- -----------------------------------------------------------------------------
2133 -- Misc.
2134
2135 -- | What phase to run after one of the backend code generators has run
2136 hscPostBackendPhase :: DynFlags -> HscSource -> HscTarget -> Phase
2137 hscPostBackendPhase _ HsBootFile _ = StopLn
2138 hscPostBackendPhase dflags _ hsc_lang =
2139 case hsc_lang of
2140 HscC -> HCc
2141 HscAsm | gopt Opt_SplitObjs dflags -> Splitter
2142 | otherwise -> As
2143 HscLlvm -> LlvmOpt
2144 HscNothing -> StopLn
2145 HscInterpreted -> StopLn
2146
2147 touchObjectFile :: DynFlags -> FilePath -> IO ()
2148 touchObjectFile dflags path = do
2149 createDirectoryIfMissing True $ takeDirectory path
2150 SysTools.touch dflags "Touching object file" path
2151
2152 haveRtsOptsFlags :: DynFlags -> Bool
2153 haveRtsOptsFlags dflags =
2154 isJust (rtsOpts dflags) || case rtsOptsEnabled dflags of
2155 RtsOptsSafeOnly -> False
2156 _ -> True