1 {-# OPTIONS -fno-cse #-}
2 {-# LANGUAGE NamedFieldPuns #-}
3 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
5 -----------------------------------------------------------------------------
9 -- (c) The University of Glasgow 2005
11 -----------------------------------------------------------------------------
13 module DriverPipeline (
14 -- Run a series of compilation steps in a pipeline, for a
15 -- collection of source files.
18 -- Interfaces for the batch-mode driver
21 -- Interfaces for the compilation manager (interpreted/batch-mode)
28 #include "HsVersions.h"
39 import UniqFM ( eltsUFM )
42 import StaticFlags ( v_Ld_inputs, opt_PIC, opt_Static, WayName(..) )
46 import StringBuffer ( hGetStringBuffer )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
49 import ParserCoreUtils ( getCoreModuleName )
52 import LlvmCodeGen ( llvmFixupAsm )
57 import Data.IORef ( readIORef )
58 import Distribution.System
59 -- import GHC.Exts ( Int(..) )
60 import System.Directory
61 import System.FilePath
64 import Data.List ( isSuffixOf )
66 import System.Environment
69 -- ---------------------------------------------------------------------------
72 -- | Just preprocess a file, put the result in a temp. file (used by the
73 -- compilation manager during the summary phase).
75 -- We return the augmented DynFlags, because they contain the result
76 -- of slurping in the OPTIONS pragmas
79 -> (FilePath, Maybe Phase) -- ^ filename and starting phase
80 -> IO (DynFlags, FilePath)
81 preprocess hsc_env (filename, mb_phase) =
82 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
83 runPipeline anyHsc hsc_env (filename, mb_phase)
84 Nothing Temporary Nothing{-no ModLocation-} Nothing{-no stub-}
86 -- ---------------------------------------------------------------------------
90 -- Compile a single module, under the control of the compilation manager.
92 -- This is the interface between the compilation manager and the
93 -- compiler proper (hsc), where we deal with tedious details like
94 -- reading the OPTIONS pragma from the source file, converting the
95 -- C or assembly that GHC produces into an object file, and compiling
98 -- NB. No old interface can also mean that the source has changed.
101 -> ModSummary -- ^ summary for module being compiled
102 -> Int -- ^ module N ...
104 -> Maybe ModIface -- ^ old interface, if we have one
105 -> Maybe Linkable -- ^ old linkable, if we have one
106 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
108 compile = compile' (hscCompileNothing, hscCompileInteractive, hscCompileBatch)
111 (Compiler (HscStatus, ModIface, ModDetails),
112 Compiler (InteractiveStatus, ModIface, ModDetails),
113 Compiler (HscStatus, ModIface, ModDetails))
115 -> ModSummary -- ^ summary for module being compiled
116 -> Int -- ^ module N ...
118 -> Maybe ModIface -- ^ old interface, if we have one
119 -> Maybe Linkable -- ^ old linkable, if we have one
120 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
122 compile' (nothingCompiler, interactiveCompiler, batchCompiler)
123 hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
125 let dflags0 = ms_hspp_opts summary
126 this_mod = ms_mod summary
127 src_flavour = ms_hsc_src summary
128 location = ms_location summary
129 input_fn = expectJust "compile:hs" (ml_hs_file location)
130 input_fnpp = ms_hspp_file summary
132 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
134 let basename = dropExtension input_fn
136 -- We add the directory in which the .hs files resides) to the import path.
137 -- This is needed when we try to compile the .hc file later, if it
138 -- imports a _stub.h file that we created here.
139 let current_dir = case takeDirectory basename of
140 "" -> "." -- XXX Hack
142 old_paths = includePaths dflags0
143 dflags = dflags0 { includePaths = current_dir : old_paths }
144 hsc_env = hsc_env0 {hsc_dflags = dflags}
146 -- Figure out what lang we're generating
147 let hsc_lang = hscTarget dflags
148 -- ... and what the next phase should be
149 let next_phase = hscNextPhase dflags src_flavour hsc_lang
150 -- ... and what file to generate the output into
151 output_fn <- getOutputFilename next_phase
152 Temporary basename dflags next_phase (Just location)
154 let dflags' = dflags { hscTarget = hsc_lang,
155 hscOutName = output_fn,
156 extCoreName = basename ++ ".hcr" }
157 let hsc_env' = hsc_env { hsc_dflags = dflags' }
159 -- -fforce-recomp should also work with --make
160 let force_recomp = dopt Opt_ForceRecomp dflags
161 source_unchanged = isJust maybe_old_linkable && not force_recomp
162 object_filename = ml_obj_file location
164 let handleBatch HscNoRecomp
165 = ASSERT (isJust maybe_old_linkable)
166 return maybe_old_linkable
168 handleBatch (HscRecomp hasStub _)
169 | isHsBoot src_flavour
170 = do when (isObjectTarget hsc_lang) $ -- interpreted reaches here too
171 liftIO $ SysTools.touch dflags' "Touching object file"
173 return maybe_old_linkable
176 = do (hs_unlinked, unlinked_time) <-
179 return ([], ms_hs_date summary)
180 -- We're in --make mode: finish the compilation pipeline.
182 maybe_stub_o <- case hasStub of
183 Nothing -> return Nothing
185 stub_o <- compileStub hsc_env' stub_c
187 _ <- runPipeline StopLn hsc_env' (output_fn,Nothing)
192 -- The object filename comes from the ModLocation
193 o_time <- getModificationTime object_filename
194 return ([DotO object_filename], o_time)
196 let linkable = LM unlinked_time this_mod hs_unlinked
197 return (Just linkable)
199 handleInterpreted HscNoRecomp
200 = ASSERT (isJust maybe_old_linkable)
201 return maybe_old_linkable
202 handleInterpreted (HscRecomp _hasStub Nothing)
203 = ASSERT (isHsBoot src_flavour)
204 return maybe_old_linkable
205 handleInterpreted (HscRecomp hasStub (Just (comp_bc, modBreaks)))
206 = do stub_o <- case hasStub of
209 stub_o <- compileStub hsc_env' stub_c
212 let hs_unlinked = [BCOs comp_bc modBreaks]
213 unlinked_time = ms_hs_date summary
214 -- Why do we use the timestamp of the source file here,
215 -- rather than the current time? This works better in
216 -- the case where the local clock is out of sync
217 -- with the filesystem's clock. It's just as accurate:
218 -- if the source is modified, then the linkable will
220 let linkable = LM unlinked_time this_mod
221 (hs_unlinked ++ stub_o)
222 return (Just linkable)
224 let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
226 runCompiler compiler handle
227 = do (result, iface, details)
228 <- compiler hsc_env' summary source_unchanged mb_old_iface
229 (Just (mod_index, nmods))
230 linkable <- handle result
231 return (HomeModInfo{ hm_details = details,
233 hm_linkable = linkable })
236 HscInterpreted -> runCompiler interactiveCompiler handleInterpreted
237 HscNothing -> runCompiler nothingCompiler handleBatch
238 _other -> runCompiler batchCompiler handleBatch
240 -----------------------------------------------------------------------------
241 -- stub .h and .c files (for foreign export support)
243 -- The _stub.c file is derived from the haskell source file, possibly taking
244 -- into account the -stubdir option.
246 -- The object file created by compiling the _stub.c file is put into a
247 -- temporary file, which will be later combined with the main .o file
248 -- (see the MergeStubs phase).
250 compileStub :: HscEnv -> FilePath -> IO FilePath
251 compileStub hsc_env stub_c = do
252 (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing
253 Temporary Nothing{-no ModLocation-} Nothing
257 -- ---------------------------------------------------------------------------
260 link :: GhcLink -- interactive or batch
261 -> DynFlags -- dynamic flags
262 -> Bool -- attempt linking in batch mode?
263 -> HomePackageTable -- what to link
266 -- For the moment, in the batch linker, we don't bother to tell doLink
267 -- which packages to link -- it just tries all that are available.
268 -- batch_attempt_linking should only be *looked at* in batch mode. It
269 -- should only be True if the upsweep was successful and someone
270 -- exports main, i.e., we have good reason to believe that linking
273 link LinkInMemory _ _ _
274 = if cGhcWithInterpreter == "YES"
275 then -- Not Linking...(demand linker will do the job)
277 else panicBadLink LinkInMemory
282 link LinkBinary dflags batch_attempt_linking hpt
283 = link' dflags batch_attempt_linking hpt
285 link LinkDynLib dflags batch_attempt_linking hpt
286 = link' dflags batch_attempt_linking hpt
288 panicBadLink :: GhcLink -> a
289 panicBadLink other = panic ("link: GHC not built to link this way: " ++
292 link' :: DynFlags -- dynamic flags
293 -> Bool -- attempt linking in batch mode?
294 -> HomePackageTable -- what to link
297 link' dflags batch_attempt_linking hpt
298 | batch_attempt_linking
301 home_mod_infos = eltsUFM hpt
303 -- the packages we depend on
304 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
306 -- the linkables to link
307 linkables = map (expectJust "link".hm_linkable) home_mod_infos
309 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
311 -- check for the -no-link flag
312 if isNoLink (ghcLink dflags)
313 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
317 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
318 obj_files = concatMap getOfiles linkables
320 exe_file = exeFileName dflags
322 linking_needed <- linkingNeeded dflags linkables pkg_deps
324 if not (dopt Opt_ForceRecomp dflags) && not linking_needed
325 then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required."))
329 debugTraceMsg dflags 1 (ptext (sLit "Linking") <+> text exe_file
332 -- Don't showPass in Batch mode; doLink will do that for us.
333 let link = case ghcLink dflags of
334 LinkBinary -> linkBinary
335 LinkDynLib -> linkDynLib
336 other -> panicBadLink other
337 link dflags obj_files pkg_deps
339 debugTraceMsg dflags 3 (text "link: done")
341 -- linkBinary only returns if it succeeds
345 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
346 text " Main.main not exported; not linking.")
350 linkingNeeded :: DynFlags -> [Linkable] -> [PackageId] -> IO Bool
351 linkingNeeded dflags linkables pkg_deps = do
352 -- if the modification time on the executable is later than the
353 -- modification times on all of the objects and libraries, then omit
354 -- linking (unless the -fforce-recomp flag was given).
355 let exe_file = exeFileName dflags
356 e_exe_time <- tryIO $ getModificationTime exe_file
358 Left _ -> return True
360 -- first check object files and extra_ld_inputs
361 extra_ld_inputs <- readIORef v_Ld_inputs
362 e_extra_times <- mapM (tryIO . getModificationTime) extra_ld_inputs
363 let (errs,extra_times) = splitEithers e_extra_times
364 let obj_times = map linkableTime linkables ++ extra_times
365 if not (null errs) || any (t <) obj_times
369 -- next, check libraries. XXX this only checks Haskell libraries,
370 -- not extra_libraries or -l things from the command line.
371 let pkg_map = pkgIdMap (pkgState dflags)
372 pkg_hslibs = [ (libraryDirs c, lib)
373 | Just c <- map (lookupPackage pkg_map) pkg_deps,
374 lib <- packageHsLibs dflags c ]
376 pkg_libfiles <- mapM (uncurry findHSLib) pkg_hslibs
377 if any isNothing pkg_libfiles then return True else do
378 e_lib_times <- mapM (tryIO . getModificationTime)
379 (catMaybes pkg_libfiles)
380 let (lib_errs,lib_times) = splitEithers e_lib_times
381 if not (null lib_errs) || any (t <) lib_times
383 else checkLinkInfo dflags pkg_deps exe_file
385 -- Returns 'False' if it was, and we can avoid linking, because the
386 -- previous binary was linked with "the same options".
387 checkLinkInfo :: DynFlags -> [PackageId] -> FilePath -> IO Bool
388 checkLinkInfo dflags pkg_deps exe_file
389 | isWindowsTarget || isDarwinTarget
390 -- ToDo: Windows and OS X do not use the ELF binary format, so
391 -- readelf does not work there. We need to find another way to do
393 = return False -- conservatively we should return True, but not
394 -- linking in this case was the behaviour for a long
395 -- time so we leave it as-is.
398 link_info <- getLinkInfo dflags pkg_deps
399 debugTraceMsg dflags 3 $ text ("Link info: " ++ link_info)
400 m_exe_link_info <- readElfSection dflags ghcLinkInfoSectionName exe_file
401 debugTraceMsg dflags 3 $ text ("Exe link info: " ++ show m_exe_link_info)
402 return (Just link_info /= m_exe_link_info)
404 ghcLinkInfoSectionName :: String
405 ghcLinkInfoSectionName = ".debug-ghc-link-info"
406 -- if we use the ".debug" prefix, then strip will strip it by default
408 findHSLib :: [String] -> String -> IO (Maybe FilePath)
409 findHSLib dirs lib = do
410 let batch_lib_file = "lib" ++ lib <.> "a"
411 found <- filterM doesFileExist (map (</> batch_lib_file) dirs)
414 (x:_) -> return (Just x)
416 -- -----------------------------------------------------------------------------
417 -- Compile files in one-shot mode.
419 oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO ()
420 oneShot hsc_env stop_phase srcs = do
421 o_files <- mapM (compileFile hsc_env stop_phase) srcs
422 doLink (hsc_dflags hsc_env) stop_phase o_files
424 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
425 compileFile hsc_env stop_phase (src, mb_phase) = do
426 exists <- doesFileExist src
428 ghcError (CmdLineError ("does not exist: " ++ src))
431 dflags = hsc_dflags hsc_env
432 split = dopt Opt_SplitObjs dflags
433 mb_o_file = outputFile dflags
434 ghc_link = ghcLink dflags -- Set by -c or -no-link
436 -- When linking, the -o argument refers to the linker's output.
437 -- otherwise, we use it as the name for the pipeline's output.
439 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
440 -- -o foo applies to linker
441 | Just o_file <- mb_o_file = SpecificFile o_file
442 -- -o foo applies to the file we are compiling now
443 | otherwise = Persistent
445 stop_phase' = case stop_phase of
446 As | split -> SplitAs
449 ( _, out_file) <- runPipeline stop_phase' hsc_env
450 (src, mb_phase) Nothing output
451 Nothing{-no ModLocation-} Nothing
455 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
456 doLink dflags stop_phase o_files
457 | not (isStopLn stop_phase)
458 = return () -- We stopped before the linking phase
461 = case ghcLink dflags of
463 LinkBinary -> linkBinary dflags o_files []
464 LinkDynLib -> linkDynLib dflags o_files []
465 other -> panicBadLink other
468 -- ---------------------------------------------------------------------------
472 -- ^ Output should be to a temporary file: we're going to
473 -- run more compilation steps on this output later.
475 -- ^ We want a persistent file, i.e. a file in the current directory
476 -- derived from the input filename, but with the appropriate extension.
477 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
478 | SpecificFile FilePath
479 -- ^ The output must go into the specified file.
481 -- | Run a compilation pipeline, consisting of multiple phases.
483 -- This is the interface to the compilation pipeline, which runs
484 -- a series of compilation steps on a single source file, specifying
485 -- at which stage to stop.
487 -- The DynFlags can be modified by phases in the pipeline (eg. by
488 -- OPTIONS_GHC pragmas), and the changes affect later phases in the
491 :: Phase -- ^ When to stop
492 -> HscEnv -- ^ Compilation environment
493 -> (FilePath,Maybe Phase) -- ^ Input filename (and maybe -x suffix)
494 -> Maybe FilePath -- ^ original basename (if different from ^^^)
495 -> PipelineOutput -- ^ Output filename
496 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
497 -> Maybe FilePath -- ^ stub object, if we have one
498 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
500 runPipeline stop_phase hsc_env0 (input_fn, mb_phase)
501 mb_basename output maybe_loc maybe_stub_o
503 let dflags0 = hsc_dflags hsc_env0
504 (input_basename, suffix) = splitExtension input_fn
505 suffix' = drop 1 suffix -- strip off the .
506 basename | Just b <- mb_basename = b
507 | otherwise = input_basename
509 -- Decide where dump files should go based on the pipeline output
510 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
511 hsc_env = hsc_env0 {hsc_dflags = dflags}
513 -- If we were given a -x flag, then use that phase to start from
514 start_phase = fromMaybe (startPhase suffix') mb_phase
516 -- We want to catch cases of "you can't get there from here" before
517 -- we start the pipeline, because otherwise it will just run off the
520 -- There is a partial ordering on phases, where A < B iff A occurs
521 -- before B in a normal compilation pipeline.
523 when (not (start_phase `happensBefore` stop_phase)) $
525 ("cannot compile this file to desired target: "
528 -- this is a function which will be used to calculate output file names
529 -- as we go along (we partially apply it to some of its inputs here)
530 let get_output_fn = getOutputFilename stop_phase output basename
532 -- Execute the pipeline...
533 let env = PipeEnv{ stop_phase,
534 src_basename = basename,
535 src_suffix = suffix',
536 output_spec = output }
538 state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o }
540 (state', output_fn) <- unP (pipeLoop start_phase input_fn) env state
542 let PipeState{ hsc_env=hsc_env', maybe_loc } = state'
543 dflags' = hsc_dflags hsc_env'
545 -- Sometimes, a compilation phase doesn't actually generate any output
546 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
547 -- stage, but we wanted to keep the output, then we have to explicitly
548 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
549 -- further compilation stages can tell what the original filename was.
552 return (dflags', output_fn)
554 do final_fn <- get_output_fn dflags' stop_phase maybe_loc
555 when (final_fn /= output_fn) $ do
556 let msg = ("Copying `" ++ output_fn ++"' to `" ++ final_fn ++ "'")
557 line_prag = Just ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}\n")
558 copyWithHeader dflags msg line_prag output_fn final_fn
559 return (dflags', final_fn)
561 -- -----------------------------------------------------------------------------
562 -- The pipeline uses a monad to carry around various bits of information
564 -- PipeEnv: invariant information passed down
565 data PipeEnv = PipeEnv {
566 stop_phase :: Phase, -- ^ Stop just before this phase
567 src_basename :: String, -- ^ basename of original input source
568 src_suffix :: String, -- ^ its extension
569 output_spec :: PipelineOutput -- ^ says where to put the pipeline output
572 -- PipeState: information that might change during a pipeline run
573 data PipeState = PipeState {
575 -- ^ only the DynFlags change in the HscEnv. The DynFlags change
576 -- at various points, for example when we read the OPTIONS_GHC
577 -- pragmas in the Cpp phase.
578 maybe_loc :: Maybe ModLocation,
579 -- ^ the ModLocation. This is discovered during compilation,
580 -- in the Hsc phase where we read the module header.
581 maybe_stub_o :: Maybe FilePath
582 -- ^ the stub object. This is set by the Hsc phase if a stub
583 -- object was created. The stub object will be joined with
584 -- the main compilation object using "ld -r" at the end.
587 getPipeEnv :: CompPipeline PipeEnv
588 getPipeEnv = P $ \env state -> return (state, env)
590 getPipeState :: CompPipeline PipeState
591 getPipeState = P $ \_env state -> return (state, state)
593 getDynFlags :: CompPipeline DynFlags
594 getDynFlags = P $ \_env state -> return (state, hsc_dflags (hsc_env state))
596 setDynFlags :: DynFlags -> CompPipeline ()
597 setDynFlags dflags = P $ \_env state ->
598 return (state{hsc_env= (hsc_env state){ hsc_dflags = dflags }}, ())
600 setModLocation :: ModLocation -> CompPipeline ()
601 setModLocation loc = P $ \_env state ->
602 return (state{ maybe_loc = Just loc }, ())
604 setStubO :: FilePath -> CompPipeline ()
605 setStubO stub_o = P $ \_env state ->
606 return (state{ maybe_stub_o = Just stub_o }, ())
608 newtype CompPipeline a = P { unP :: PipeEnv -> PipeState -> IO (PipeState, a) }
610 instance Monad CompPipeline where
611 return a = P $ \_env state -> return (state, a)
612 P m >>= k = P $ \env state -> do (state',a) <- m env state
615 io :: IO a -> CompPipeline a
616 io m = P $ \_env state -> do a <- m; return (state, a)
618 phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath
619 phaseOutputFilename next_phase = do
620 PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv
621 PipeState{maybe_loc, hsc_env} <- getPipeState
622 let dflags = hsc_dflags hsc_env
623 io $ getOutputFilename stop_phase output_spec
624 src_basename dflags next_phase maybe_loc
626 -- ---------------------------------------------------------------------------
627 -- outer pipeline loop
629 -- | pipeLoop runs phases until we reach the stop phase
630 pipeLoop :: Phase -> FilePath -> CompPipeline FilePath
631 pipeLoop phase input_fn = do
632 PipeEnv{stop_phase} <- getPipeEnv
633 PipeState{hsc_env} <- getPipeState
635 _ | phase `eqPhase` stop_phase -- All done
638 | not (phase `happensBefore` stop_phase)
639 -- Something has gone wrong. We'll try to cover all the cases when
640 -- this could happen, so if we reach here it is a panic.
641 -- eg. it might happen if the -C flag is used on a source file that
642 -- has {-# OPTIONS -fasm #-}.
643 -> panic ("pipeLoop: at phase " ++ show phase ++
644 " but I wanted to stop at phase " ++ show stop_phase)
647 -> do io $ debugTraceMsg (hsc_dflags hsc_env) 4
648 (ptext (sLit "Running phase") <+> ppr phase)
649 dflags <- getDynFlags
650 (next_phase, output_fn) <- runPhase phase input_fn dflags
651 pipeLoop next_phase output_fn
653 -- -----------------------------------------------------------------------------
654 -- In each phase, we need to know into what filename to generate the
655 -- output. All the logic about which filenames we generate output
656 -- into is embodied in the following function.
659 :: Phase -> PipelineOutput -> String
660 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
661 getOutputFilename stop_phase output basename
664 func dflags next_phase maybe_location
665 | is_last_phase, Persistent <- output = persistent_fn
666 | is_last_phase, SpecificFile f <- output = return f
667 | keep_this_output = persistent_fn
668 | otherwise = newTempName dflags suffix
671 odir = objectDir dflags
672 osuf = objectSuf dflags
673 keep_hc = dopt Opt_KeepHcFiles dflags
674 keep_s = dopt Opt_KeepSFiles dflags
675 keep_bc = dopt Opt_KeepLlvmFiles dflags
677 myPhaseInputExt HCc = hcsuf
678 myPhaseInputExt MergeStub = osuf
679 myPhaseInputExt StopLn = osuf
680 myPhaseInputExt other = phaseInputExt other
682 is_last_phase = next_phase `eqPhase` stop_phase
684 -- sometimes, we keep output from intermediate stages
688 LlvmOpt | keep_bc -> True
689 HCc | keep_hc -> True
692 suffix = myPhaseInputExt next_phase
694 -- persistent object files get put in odir
696 | StopLn <- next_phase = return odir_persistent
697 | otherwise = return persistent
699 persistent = basename <.> suffix
702 | Just loc <- maybe_location = ml_obj_file loc
703 | Just d <- odir = d </> persistent
704 | otherwise = persistent
707 -- -----------------------------------------------------------------------------
708 -- | Each phase in the pipeline returns the next phase to execute, and the
709 -- name of the file in which the output was placed.
711 -- We must do things dynamically this way, because we often don't know
712 -- what the rest of the phases will be until part-way through the
713 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
714 -- of a source file can change the latter stages of the pipeline from
715 -- taking the via-C route to using the native code generator.
717 runPhase :: Phase -- ^ Run this phase
718 -> FilePath -- ^ name of the input file
719 -> DynFlags -- ^ for convenience, we pass the current dflags in
720 -> CompPipeline (Phase, -- next phase to run
721 FilePath) -- output filename
723 -- Invariant: the output filename always contains the output
724 -- Interesting case: Hsc when there is no recompilation to do
725 -- Then the output filename is still a .o file
728 -------------------------------------------------------------------------------
731 runPhase (Unlit sf) input_fn dflags
733 output_fn <- phaseOutputFilename (Cpp sf)
735 let unlit_flags = getOpts dflags opt_L
736 flags = map SysTools.Option unlit_flags ++
737 [ -- The -h option passes the file name for unlit to
738 -- put in a #line directive
740 -- cpp interprets \b etc as escape sequences,
741 -- so we use / for filenames in pragmas
742 , SysTools.Option $ reslash Forwards $ normalise input_fn
743 , SysTools.FileOption "" input_fn
744 , SysTools.FileOption "" output_fn
747 io $ SysTools.runUnlit dflags flags
749 return (Cpp sf, output_fn)
751 -------------------------------------------------------------------------------
752 -- Cpp phase : (a) gets OPTIONS out of file
753 -- (b) runs cpp if necessary
755 runPhase (Cpp sf) input_fn dflags0
757 src_opts <- io $ getOptionsFromFile dflags0 input_fn
758 (dflags1, unhandled_flags, warns)
759 <- io $ parseDynamicNoPackageFlags dflags0 src_opts
761 io $ checkProcessArgsResult unhandled_flags
763 if not (xopt Opt_Cpp dflags1) then do
764 -- we have to be careful to emit warnings only once.
765 unless (dopt Opt_Pp dflags1) $ io $ handleFlagWarnings dflags1 warns
767 -- no need to preprocess CPP, just pass input file along
768 -- to the next phase of the pipeline.
769 return (HsPp sf, input_fn)
771 output_fn <- phaseOutputFilename (HsPp sf)
772 io $ doCpp dflags1 True{-raw-} False{-no CC opts-} input_fn output_fn
773 -- re-read the pragmas now that we've preprocessed the file
775 src_opts <- io $ getOptionsFromFile dflags0 output_fn
776 (dflags2, unhandled_flags, warns)
777 <- io $ parseDynamicNoPackageFlags dflags0 src_opts
778 io $ checkProcessArgsResult unhandled_flags
779 unless (dopt Opt_Pp dflags2) $ io $ handleFlagWarnings dflags2 warns
780 -- the HsPp pass below will emit warnings
784 return (HsPp sf, output_fn)
786 -------------------------------------------------------------------------------
789 runPhase (HsPp sf) input_fn dflags
791 if not (dopt Opt_Pp dflags) then
792 -- no need to preprocess, just pass input file along
793 -- to the next phase of the pipeline.
794 return (Hsc sf, input_fn)
796 let hspp_opts = getOpts dflags opt_F
797 PipeEnv{src_basename, src_suffix} <- getPipeEnv
798 let orig_fn = src_basename <.> src_suffix
799 output_fn <- phaseOutputFilename (Hsc sf)
800 io $ SysTools.runPp dflags
801 ( [ SysTools.Option orig_fn
802 , SysTools.Option input_fn
803 , SysTools.FileOption "" output_fn
805 map SysTools.Option hspp_opts
808 -- re-read pragmas now that we've parsed the file (see #3674)
809 src_opts <- io $ getOptionsFromFile dflags output_fn
810 (dflags1, unhandled_flags, warns)
811 <- io $ parseDynamicNoPackageFlags dflags src_opts
813 io $ checkProcessArgsResult unhandled_flags
814 io $ handleFlagWarnings dflags1 warns
816 return (Hsc sf, output_fn)
818 -----------------------------------------------------------------------------
821 -- Compilation of a single module, in "legacy" mode (_not_ under
822 -- the direction of the compilation manager).
823 runPhase (Hsc src_flavour) input_fn dflags0
824 = do -- normal Hsc mode, not mkdependHS
826 PipeEnv{ stop_phase=stop,
827 src_basename=basename,
828 src_suffix=suff } <- getPipeEnv
830 -- we add the current directory (i.e. the directory in which
831 -- the .hs files resides) to the include path, since this is
832 -- what gcc does, and it's probably what you want.
833 let current_dir = case takeDirectory basename of
834 "" -> "." -- XXX Hack
837 paths = includePaths dflags0
838 dflags = dflags0 { includePaths = current_dir : paths }
842 -- gather the imports and module name
843 (hspp_buf,mod_name,imps,src_imps) <- io $
845 ExtCoreFile -> do -- no explicit imports in ExtCore input.
846 m <- getCoreModuleName input_fn
847 return (Nothing, mkModuleName m, [], [])
850 buf <- hGetStringBuffer input_fn
851 (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
852 return (Just buf, mod_name, imps, src_imps)
854 -- Build a ModLocation to pass to hscMain.
855 -- The source filename is rather irrelevant by now, but it's used
856 -- by hscMain for messages. hscMain also needs
857 -- the .hi and .o filenames, and this is as good a way
858 -- as any to generate them, and better than most. (e.g. takes
859 -- into accout the -osuf flags)
860 location1 <- io $ mkHomeModLocation2 dflags mod_name basename suff
862 -- Boot-ify it if necessary
863 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
864 | otherwise = location1
867 -- Take -ohi into account if present
868 -- This can't be done in mkHomeModuleLocation because
869 -- it only applies to the module being compiles
870 let ohi = outputHi dflags
871 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
872 | otherwise = location2
874 -- Take -o into account if present
875 -- Very like -ohi, but we must *only* do this if we aren't linking
876 -- (If we're linking then the -o applies to the linked thing, not to
877 -- the object file for one module.)
878 -- Note the nasty duplication with the same computation in compileFile above
879 let expl_o_file = outputFile dflags
880 location4 | Just ofile <- expl_o_file
881 , isNoLink (ghcLink dflags)
882 = location3 { ml_obj_file = ofile }
883 | otherwise = location3
885 o_file = ml_obj_file location4 -- The real object file
887 setModLocation location4
889 -- Figure out if the source has changed, for recompilation avoidance.
891 -- Setting source_unchanged to True means that M.o seems
892 -- to be up to date wrt M.hs; so no need to recompile unless imports have
893 -- changed (which the compiler itself figures out).
894 -- Setting source_unchanged to False tells the compiler that M.o is out of
895 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
896 src_timestamp <- io $ getModificationTime (basename <.> suff)
898 let force_recomp = dopt Opt_ForceRecomp dflags
899 hsc_lang = hscTarget dflags
900 source_unchanged <- io $
901 if force_recomp || not (isStopLn stop)
902 -- Set source_unchanged to False unconditionally if
903 -- (a) recompilation checker is off, or
904 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
906 -- Otherwise look at file modification dates
907 else do o_file_exists <- doesFileExist o_file
909 then return False -- Need to recompile
910 else do t2 <- getModificationTime o_file
911 if t2 > src_timestamp
916 let next_phase = hscNextPhase dflags src_flavour hsc_lang
917 output_fn <- phaseOutputFilename next_phase
919 let dflags' = dflags { hscTarget = hsc_lang,
920 hscOutName = output_fn,
921 extCoreName = basename ++ ".hcr" }
924 PipeState{hsc_env=hsc_env'} <- getPipeState
926 -- Tell the finder cache about this module
927 mod <- io $ addHomeModuleToFinder hsc_env' mod_name location4
929 -- Make the ModSummary to hand to hscMain
931 mod_summary = ModSummary { ms_mod = mod,
932 ms_hsc_src = src_flavour,
933 ms_hspp_file = input_fn,
934 ms_hspp_opts = dflags,
935 ms_hspp_buf = hspp_buf,
936 ms_location = location4,
937 ms_hs_date = src_timestamp,
938 ms_obj_date = Nothing,
940 ms_srcimps = src_imps }
943 result <- io $ hscCompileOneShot hsc_env'
944 mod_summary source_unchanged
946 Nothing -- No "module i of n" progress info
950 -> do io $ SysTools.touch dflags' "Touching object file" o_file
951 -- The .o file must have a later modification date
952 -- than the source file (else we wouldn't be in HscNoRecomp)
953 -- but we touch it anyway, to keep 'make' happy (we think).
954 return (StopLn, o_file)
955 (HscRecomp hasStub _)
956 -> do case hasStub of
959 do stub_o <- io $ compileStub hsc_env' stub_c
961 -- In the case of hs-boot files, generate a dummy .o-boot
962 -- stamp file for the benefit of Make
963 when (isHsBoot src_flavour) $
964 io $ SysTools.touch dflags' "Touching object file" o_file
965 return (next_phase, output_fn)
967 -----------------------------------------------------------------------------
970 runPhase CmmCpp input_fn dflags
972 output_fn <- phaseOutputFilename Cmm
973 io $ doCpp dflags False{-not raw-} True{-include CC opts-}
975 return (Cmm, output_fn)
977 runPhase Cmm input_fn dflags
979 PipeEnv{src_basename} <- getPipeEnv
980 let hsc_lang = hscTarget dflags
982 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
984 output_fn <- phaseOutputFilename next_phase
986 let dflags' = dflags { hscTarget = hsc_lang,
987 hscOutName = output_fn,
988 extCoreName = src_basename ++ ".hcr" }
991 PipeState{hsc_env} <- getPipeState
993 io $ hscCompileCmmFile hsc_env input_fn
995 -- XXX: catch errors above and convert them into ghcError? Original
998 --when (not ok) $ ghcError (PhaseFailed "cmm" (ExitFailure 1))
1000 return (next_phase, output_fn)
1002 -----------------------------------------------------------------------------
1005 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
1006 -- way too many hacks, and I can't say I've ever used it anyway.
1008 runPhase cc_phase input_fn dflags
1009 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` Ccpp || cc_phase `eqPhase` HCc || cc_phase `eqPhase` Cobjc
1011 let cc_opts = getOpts dflags opt_c
1012 hcc = cc_phase `eqPhase` HCc
1014 let cmdline_include_paths = includePaths dflags
1016 -- HC files have the dependent packages stamped into them
1017 pkgs <- if hcc then io $ getHCFilePackages input_fn else return []
1019 -- add package include paths even if we're just compiling .c
1020 -- files; this is the Value Add(TM) that using ghc instead of
1022 pkg_include_dirs <- io $ getPackageIncludePath dflags pkgs
1023 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1024 (cmdline_include_paths ++ pkg_include_dirs)
1026 let gcc_extra_viac_flags = extraGccViaCFlags dflags
1027 let pic_c_flags = picCCOpts dflags
1029 let verbFlags = getVerbFlags dflags
1031 -- cc-options are not passed when compiling .hc files. Our
1032 -- hc code doesn't not #include any header files anyway, so these
1033 -- options aren't necessary.
1034 pkg_extra_cc_opts <- io $
1035 if cc_phase `eqPhase` HCc
1037 else getPackageExtraCcOpts dflags pkgs
1039 #ifdef darwin_TARGET_OS
1040 pkg_framework_paths <- io $ getPackageFrameworkPath dflags pkgs
1041 let cmdline_framework_paths = frameworkPaths dflags
1042 let framework_paths = map ("-F"++)
1043 (cmdline_framework_paths ++ pkg_framework_paths)
1046 let split_objs = dopt Opt_SplitObjs dflags
1047 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
1050 let cc_opt | optLevel dflags >= 2 = "-O2"
1053 -- Decide next phase
1056 output_fn <- phaseOutputFilename next_phase
1060 -- on x86 the floating point regs have greater precision
1061 -- than a double, which leads to unpredictable results.
1062 -- By default, we turn this off with -ffloat-store unless
1063 -- the user specified -fexcess-precision.
1064 (if cTargetArch == I386 &&
1065 not (dopt Opt_ExcessPrecision dflags)
1066 then [ "-ffloat-store" ]
1069 -- gcc's -fstrict-aliasing allows two accesses to memory
1070 -- to be considered non-aliasing if they have different types.
1071 -- This interacts badly with the C code we generate, which is
1072 -- very weakly typed, being derived from C--.
1073 ["-fno-strict-aliasing"]
1075 let gcc_lang_opt | cc_phase `eqPhase` Ccpp = "c++"
1076 | cc_phase `eqPhase` Cobjc = "objective-c"
1078 io $ SysTools.runCc dflags (
1079 -- force the C compiler to interpret this file as C when
1080 -- compiling .hc files, by adding the -x c option.
1081 -- Also useful for plain .c files, just in case GHC saw a
1083 [ SysTools.Option "-x", SysTools.Option gcc_lang_opt
1084 , SysTools.FileOption "" input_fn
1085 , SysTools.Option "-o"
1086 , SysTools.FileOption "" output_fn
1088 ++ map SysTools.Option (
1091 -- Stub files generated for foreign exports references the runIO_closure
1092 -- and runNonIO_closure symbols, which are defined in the base package.
1093 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1094 -- way we do the import depends on whether we're currently compiling
1095 -- the base package or not.
1096 ++ (if cTargetOS == Windows &&
1097 thisPackage dflags == basePackageId
1098 then [ "-DCOMPILING_BASE_PACKAGE" ]
1101 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1102 -- instruction. Note that the user can still override this
1103 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1104 -- regardless of the ordering.
1106 -- This is a temporary hack.
1107 ++ (if cTargetArch == Sparc
1112 then gcc_extra_viac_flags ++ more_hcc_opts
1115 ++ [ "-S", "-Wimplicit", cc_opt ]
1116 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1117 #ifdef darwin_TARGET_OS
1123 ++ pkg_extra_cc_opts
1126 return (next_phase, output_fn)
1128 -- ToDo: postprocess the output from gcc
1130 -----------------------------------------------------------------------------
1133 runPhase SplitMangle input_fn dflags
1134 = do -- tmp_pfx is the prefix used for the split .s files
1136 split_s_prefix <- io $ SysTools.newTempName dflags "split"
1137 let n_files_fn = split_s_prefix
1139 io $ SysTools.runSplit dflags
1140 [ SysTools.FileOption "" input_fn
1141 , SysTools.FileOption "" split_s_prefix
1142 , SysTools.FileOption "" n_files_fn
1145 -- Save the number of split files for future references
1146 s <- io $ readFile n_files_fn
1147 let n_files = read s :: Int
1148 dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1152 -- Remember to delete all these files
1153 io $ addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s"
1154 | n <- [1..n_files]]
1156 return (SplitAs, "**splitmangle**")
1157 -- we don't use the filename
1159 -----------------------------------------------------------------------------
1162 runPhase As input_fn dflags
1164 let as_opts = getOpts dflags opt_a
1165 let cmdline_include_paths = includePaths dflags
1167 next_phase <- maybeMergeStub
1168 output_fn <- phaseOutputFilename next_phase
1170 -- we create directories for the object file, because it
1171 -- might be a hierarchical module.
1172 io $ createDirectoryHierarchy (takeDirectory output_fn)
1174 io $ SysTools.runAs dflags
1175 (map SysTools.Option as_opts
1176 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1178 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1179 -- instruction so we have to make sure that the assembler accepts the
1180 -- instruction set. Note that the user can still override this
1181 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1182 -- regardless of the ordering.
1184 -- This is a temporary hack.
1185 ++ (if cTargetArch == Sparc
1186 then [SysTools.Option "-mcpu=v9"]
1189 ++ [ SysTools.Option "-c"
1190 , SysTools.FileOption "" input_fn
1191 , SysTools.Option "-o"
1192 , SysTools.FileOption "" output_fn
1195 return (next_phase, output_fn)
1198 runPhase SplitAs _input_fn dflags
1200 -- we'll handle the stub_o file in this phase, so don't MergeStub,
1201 -- just jump straight to StopLn afterwards.
1202 let next_phase = StopLn
1203 output_fn <- phaseOutputFilename next_phase
1205 let base_o = dropExtension output_fn
1206 osuf = objectSuf dflags
1207 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1209 io $ createDirectoryHierarchy split_odir
1211 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1212 -- later and we don't want to pick up any old objects.
1213 fs <- io $ getDirectoryContents split_odir
1214 io $ mapM_ removeFile $
1215 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1217 let as_opts = getOpts dflags opt_a
1219 let (split_s_prefix, n) = case splitInfo dflags of
1220 Nothing -> panic "No split info"
1223 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1225 split_obj :: Int -> FilePath
1226 split_obj n = split_odir </>
1227 takeFileName base_o ++ "__" ++ show n <.> osuf
1230 = SysTools.runAs dflags
1231 (map SysTools.Option as_opts ++
1233 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1234 -- instruction so we have to make sure that the assembler accepts the
1235 -- instruction set. Note that the user can still override this
1236 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1237 -- regardless of the ordering.
1239 -- This is a temporary hack.
1240 (if cTargetArch == Sparc
1241 then [SysTools.Option "-mcpu=v9"]
1244 [ SysTools.Option "-c"
1245 , SysTools.Option "-o"
1246 , SysTools.FileOption "" (split_obj n)
1247 , SysTools.FileOption "" (split_s n)
1250 io $ mapM_ assemble_file [1..n]
1252 -- Note [pipeline-split-init]
1253 -- If we have a stub file, it may contain constructor
1254 -- functions for initialisation of this module. We can't
1255 -- simply leave the stub as a separate object file, because it
1256 -- will never be linked in: nothing refers to it. We need to
1257 -- ensure that if we ever refer to the data in this module
1258 -- that needs initialisation, then we also pull in the
1259 -- initialisation routine.
1261 -- To that end, we make a DANGEROUS ASSUMPTION here: the data
1262 -- that needs to be initialised is all in the FIRST split
1263 -- object. See Note [codegen-split-init].
1265 PipeState{maybe_stub_o} <- getPipeState
1266 case maybe_stub_o of
1267 Nothing -> return ()
1268 Just stub_o -> io $ do
1269 tmp_split_1 <- newTempName dflags osuf
1270 let split_1 = split_obj 1
1271 copyFile split_1 tmp_split_1
1273 joinObjectFiles dflags [tmp_split_1, stub_o] split_1
1275 -- join them into a single .o file
1276 io $ joinObjectFiles dflags (map split_obj [1..n]) output_fn
1278 return (next_phase, output_fn)
1280 -----------------------------------------------------------------------------
1283 runPhase LlvmOpt input_fn dflags
1285 let lo_opts = getOpts dflags opt_lo
1286 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1287 -- don't specify anything if user has specified commands. We do this for
1288 -- opt but not llc since opt is very specifically for optimisation passes
1289 -- only, so if the user is passing us extra options we assume they know
1290 -- what they are doing and don't get in the way.
1291 let optFlag = if null lo_opts
1292 then [SysTools.Option (llvmOpts !! opt_lvl)]
1295 output_fn <- phaseOutputFilename LlvmLlc
1297 io $ SysTools.runLlvmOpt dflags
1298 ([ SysTools.FileOption "" input_fn,
1299 SysTools.Option "-o",
1300 SysTools.FileOption "" output_fn]
1302 ++ map SysTools.Option lo_opts)
1304 return (LlvmLlc, output_fn)
1306 -- we always (unless -optlo specified) run Opt since we rely on it to
1307 -- fix up some pretty big deficiencies in the code we generate
1308 llvmOpts = ["-mem2reg", "-O1", "-O2"]
1311 -----------------------------------------------------------------------------
1314 runPhase LlvmLlc input_fn dflags
1316 let lc_opts = getOpts dflags opt_lc
1317 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1318 let nphase = if cTargetOS == OSX
1321 let rmodel | opt_PIC = "pic"
1322 | not opt_Static = "dynamic-no-pic"
1323 | otherwise = "static"
1325 output_fn <- phaseOutputFilename nphase
1327 io $ SysTools.runLlvmLlc dflags
1328 ([ SysTools.Option (llvmOpts !! opt_lvl),
1329 SysTools.Option $ "-relocation-model=" ++ rmodel,
1330 SysTools.FileOption "" input_fn,
1331 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1332 ++ map SysTools.Option lc_opts)
1334 return (nphase, output_fn)
1336 llvmOpts = if cTargetOS == OSX
1337 then ["-O1", "-O2", "-O2"]
1338 else ["-O1", "-O2", "-O3"]
1341 -----------------------------------------------------------------------------
1344 runPhase LlvmMangle input_fn _dflags
1346 output_fn <- phaseOutputFilename As
1347 io $ llvmFixupAsm input_fn output_fn
1348 return (As, output_fn)
1350 -----------------------------------------------------------------------------
1351 -- merge in stub objects
1353 runPhase MergeStub input_fn dflags
1355 PipeState{maybe_stub_o} <- getPipeState
1356 output_fn <- phaseOutputFilename StopLn
1357 case maybe_stub_o of
1359 panic "runPhase(MergeStub): no stub"
1361 io $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1362 return (StopLn, output_fn)
1364 -- warning suppression
1365 runPhase other _input_fn _dflags =
1366 panic ("runPhase: don't know how to run phase " ++ show other)
1368 maybeMergeStub :: CompPipeline Phase
1371 PipeState{maybe_stub_o} <- getPipeState
1372 if isJust maybe_stub_o then return MergeStub else return StopLn
1374 -----------------------------------------------------------------------------
1375 -- MoveBinary sort-of-phase
1376 -- After having produced a binary, move it somewhere else and generate a
1377 -- wrapper script calling the binary. Currently, we need this only in
1378 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1379 -- central directory.
1380 -- This is called from linkBinary below, after linking. I haven't made it
1381 -- a separate phase to minimise interfering with other modules, and
1382 -- we don't need the generality of a phase (MoveBinary is always
1383 -- done after linking and makes only sense in a parallel setup) -- HWL
1385 runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool
1386 runPhase_MoveBinary dflags input_fn
1387 | WayPar `elem` (wayNames dflags) && not opt_Static =
1388 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1389 | WayPar `elem` (wayNames dflags) = do
1390 let sysMan = pgm_sysman dflags
1391 pvm_root <- getEnv "PVM_ROOT"
1392 pvm_arch <- getEnv "PVM_ARCH"
1394 pvm_executable_base = "=" ++ input_fn
1395 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1396 -- nuke old binary; maybe use configur'ed names for cp and rm?
1397 _ <- tryIO (removeFile pvm_executable)
1398 -- move the newly created binary into PVM land
1399 copy dflags "copying PVM executable" input_fn pvm_executable
1400 -- generate a wrapper script for running a parallel prg under PVM
1401 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1403 | otherwise = return True
1405 mkExtraCObj :: DynFlags -> String -> IO FilePath
1406 mkExtraCObj dflags xs
1407 = do cFile <- newTempName dflags "c"
1408 oFile <- newTempName dflags "o"
1410 let rtsDetails = getPackageDetails (pkgState dflags) rtsPackageId
1411 SysTools.runCc dflags
1413 FileOption "" cFile,
1415 FileOption "" oFile] ++
1416 map (FileOption "-I") (includeDirs rtsDetails))
1419 mkExtraObjToLinkIntoBinary :: DynFlags -> [PackageId] -> IO FilePath
1420 mkExtraObjToLinkIntoBinary dflags dep_packages = do
1421 link_info <- getLinkInfo dflags dep_packages
1422 mkExtraCObj dflags (showSDoc (vcat [rts_opts_enabled,
1424 link_opts link_info]
1425 <> char '\n')) -- final newline, to
1429 mk_rts_opts_enabled val
1430 = vcat [text "#include \"Rts.h\"",
1431 text "#include \"RtsOpts.h\"",
1432 text "const RtsOptsEnabledEnum rtsOptsEnabled = " <>
1435 rts_opts_enabled = case rtsOptsEnabled dflags of
1436 RtsOptsNone -> mk_rts_opts_enabled "RtsOptsNone"
1437 RtsOptsSafeOnly -> empty -- The default
1438 RtsOptsAll -> mk_rts_opts_enabled "RtsOptsAll"
1440 extra_rts_opts = case rtsOpts dflags of
1442 Just opts -> text "char *ghc_rts_opts = " <> text (show opts) <> semi
1445 | isDarwinTarget = empty
1446 | isWindowsTarget = empty
1447 | otherwise = hcat [
1448 text "__asm__(\"\\t.section ", text ghcLinkInfoSectionName,
1449 text ",\\\"\\\",@note\\n",
1450 text "\\t.ascii \\\"", info', text "\\\"\\n\");" ]
1452 -- we need to escape twice: once because we're inside a C string,
1453 -- and again because we're inside an asm string.
1454 info' = text $ (escape.escape) info
1456 escape :: String -> String
1457 escape = concatMap (charToC.fromIntegral.ord)
1459 -- The "link info" is a string representing the parameters of the
1460 -- link. We save this information in the binary, and the next time we
1461 -- link, if nothing else has changed, we use the link info stored in
1462 -- the existing binary to decide whether to re-link or not.
1463 getLinkInfo :: DynFlags -> [PackageId] -> IO String
1464 getLinkInfo dflags dep_packages = do
1465 package_link_opts <- getPackageLinkOpts dflags dep_packages
1466 #ifdef darwin_TARGET_OS
1467 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1469 extra_ld_inputs <- readIORef v_Ld_inputs
1471 link_info = (package_link_opts,
1472 #ifdef darwin_TARGET_OS
1476 rtsOptsEnabled dflags,
1477 dopt Opt_NoHsMain dflags,
1479 getOpts dflags opt_l)
1481 return (show link_info)
1483 -- generates a Perl skript starting a parallel prg under PVM
1484 mk_pvm_wrapper_script :: String -> String -> String -> String
1485 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1487 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1488 " if $running_under_some_shell;",
1489 "# =!=!=!=!=!=!=!=!=!=!=!",
1490 "# This script is automatically generated: DO NOT EDIT!!!",
1491 "# Generated by Glasgow Haskell Compiler",
1492 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1494 "$pvm_executable = '" ++ pvm_executable ++ "';",
1495 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1496 "$SysMan = '" ++ sysMan ++ "';",
1498 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1499 "# first, some magical shortcuts to run "commands" on the binary",
1500 "# (which is hidden)",
1501 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1502 " local($cmd) = $1;",
1503 " system("$cmd $pvm_executable");",
1504 " exit(0); # all done",
1507 "# Now, run the real binary; process the args first",
1508 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1510 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1511 "@nonPVM_args = ();",
1512 "$in_RTS_args = 0;",
1514 "args: while ($a = shift(@ARGV)) {",
1515 " if ( $a eq '+RTS' ) {",
1516 " $in_RTS_args = 1;",
1517 " } elsif ( $a eq '-RTS' ) {",
1518 " $in_RTS_args = 0;",
1520 " if ( $a eq '-d' && $in_RTS_args ) {",
1522 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1523 " $nprocessors = $1;",
1524 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1525 " $nprocessors = $1;",
1527 " push(@nonPVM_args, $a);",
1531 "local($return_val) = 0;",
1532 "# Start the parallel execution by calling SysMan",
1533 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1534 "$return_val = $?;",
1535 "# ToDo: fix race condition moving files and flushing them!!",
1536 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1537 "exit($return_val);"
1540 -----------------------------------------------------------------------------
1541 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1543 getHCFilePackages :: FilePath -> IO [PackageId]
1544 getHCFilePackages filename =
1545 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1548 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1549 return (map stringToPackageId (words rest))
1553 -----------------------------------------------------------------------------
1554 -- Static linking, of .o files
1556 -- The list of packages passed to link is the list of packages on
1557 -- which this program depends, as discovered by the compilation
1558 -- manager. It is combined with the list of packages that the user
1559 -- specifies on the command line with -package flags.
1561 -- In one-shot linking mode, we can't discover the package
1562 -- dependencies (because we haven't actually done any compilation or
1563 -- read any interface files), so the user must explicitly specify all
1566 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1567 linkBinary dflags o_files dep_packages = do
1568 let verbFlags = getVerbFlags dflags
1569 output_fn = exeFileName dflags
1571 -- get the full list of packages to link with, by combining the
1572 -- explicit packages with the auto packages and all of their
1573 -- dependencies, and eliminating duplicates.
1575 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1576 let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1577 #ifdef elf_OBJ_FORMAT
1578 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1579 | otherwise = ["-L" ++ l]
1581 get_pkg_lib_path_opts l = ["-L" ++ l]
1584 let lib_paths = libraryPaths dflags
1585 let lib_path_opts = map ("-L"++) lib_paths
1587 -- The C "main" function is not in the rts but in a separate static
1588 -- library libHSrtsmain.a that sits next to the rts lib files. Assuming
1589 -- we're using a Haskell main function then we need to link it in.
1590 let no_hs_main = dopt Opt_NoHsMain dflags
1591 let main_lib | no_hs_main = []
1592 | otherwise = [ "-lHSrtsmain" ]
1594 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags dep_packages
1596 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1598 #ifdef darwin_TARGET_OS
1599 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1600 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1602 let framework_paths = frameworkPaths dflags
1603 framework_path_opts = map ("-F"++) framework_paths
1605 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1606 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1608 let frameworks = cmdlineFrameworks dflags
1609 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1610 -- reverse because they're added in reverse order from the cmd line
1612 -- probably _stub.o files
1613 extra_ld_inputs <- readIORef v_Ld_inputs
1615 -- opts from -optl-<blah> (including -l<blah> options)
1616 let extra_ld_opts = getOpts dflags opt_l
1618 let ways = wayNames dflags
1620 -- Here are some libs that need to be linked at the *end* of
1621 -- the command line, because they contain symbols that are referred to
1622 -- by the RTS. We can't therefore use the ordinary way opts for these.
1624 debug_opts | WayDebug `elem` ways = [
1625 #if defined(HAVE_LIBBFD)
1632 thread_opts | WayThreaded `elem` ways = [
1633 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS) && !defined(openbsd_TARGET_OS) && !defined(haiku_TARGET_OS)
1636 #if defined(osf3_TARGET_OS)
1642 rc_objs <- maybeCreateManifest dflags output_fn
1644 SysTools.runLink dflags (
1645 map SysTools.Option verbFlags
1646 ++ [ SysTools.Option "-o"
1647 , SysTools.FileOption "" output_fn
1649 ++ map SysTools.Option (
1652 -- Permit the linker to auto link _symbol to _imp_symbol.
1653 -- This lets us link against DLLs without needing an "import library".
1654 ++ (if cTargetOS == Windows
1655 then ["-Wl,--enable-auto-import"]
1663 #ifdef darwin_TARGET_OS
1664 ++ framework_path_opts
1667 ++ pkg_lib_path_opts
1671 #ifdef darwin_TARGET_OS
1672 ++ pkg_framework_path_opts
1673 ++ pkg_framework_opts
1679 -- parallel only: move binary to another dir -- HWL
1680 success <- runPhase_MoveBinary dflags output_fn
1681 if success then return ()
1682 else ghcError (InstallationError ("cannot move binary"))
1685 exeFileName :: DynFlags -> FilePath
1687 | Just s <- outputFile dflags =
1688 if cTargetOS == Windows
1689 then if null (takeExtension s)
1694 if cTargetOS == Windows
1700 -> FilePath -- filename of executable
1701 -> IO [FilePath] -- extra objects to embed, maybe
1702 #ifndef mingw32_TARGET_OS
1703 maybeCreateManifest _ _ = do
1706 maybeCreateManifest dflags exe_filename = do
1707 if not (dopt Opt_GenManifest dflags) then return [] else do
1709 let manifest_filename = exe_filename <.> "manifest"
1711 writeFile manifest_filename $
1712 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1713 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1714 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1715 " processorArchitecture=\"X86\"\n"++
1716 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1717 " type=\"win32\"/>\n\n"++
1718 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1720 " <requestedPrivileges>\n"++
1721 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1722 " </requestedPrivileges>\n"++
1727 -- Windows will find the manifest file if it is named foo.exe.manifest.
1728 -- However, for extra robustness, and so that we can move the binary around,
1729 -- we can embed the manifest in the binary itself using windres:
1730 if not (dopt Opt_EmbedManifest dflags) then return [] else do
1732 rc_filename <- newTempName dflags "rc"
1733 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1735 writeFile rc_filename $
1736 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1737 -- magic numbers :-)
1738 -- show is a bit hackish above, but we need to escape the
1739 -- backslashes in the path.
1741 let wr_opts = getOpts dflags opt_windres
1742 runWindres dflags $ map SysTools.Option $
1743 ["--input="++rc_filename,
1744 "--output="++rc_obj_filename,
1745 "--output-format=coff"]
1747 -- no FileOptions here: windres doesn't like seeing
1748 -- backslashes, apparently
1750 removeFile manifest_filename
1752 return [rc_obj_filename]
1756 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1757 linkDynLib dflags o_files dep_packages = do
1758 let verbFlags = getVerbFlags dflags
1759 let o_file = outputFile dflags
1761 pkgs <- getPreloadPackagesAnd dflags dep_packages
1763 let pkg_lib_paths = collectLibraryPaths pkgs
1764 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1765 #ifdef elf_OBJ_FORMAT
1766 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1767 | otherwise = ["-L" ++ l]
1769 get_pkg_lib_path_opts l = ["-L" ++ l]
1772 let lib_paths = libraryPaths dflags
1773 let lib_path_opts = map ("-L"++) lib_paths
1775 -- We don't want to link our dynamic libs against the RTS package,
1776 -- because the RTS lib comes in several flavours and we want to be
1777 -- able to pick the flavour when a binary is linked.
1778 -- On Windows we need to link the RTS import lib as Windows does
1779 -- not allow undefined symbols.
1780 -- The RTS library path is still added to the library search path
1781 -- above in case the RTS is being explicitly linked in (see #3807).
1782 #if !defined(mingw32_HOST_OS)
1783 let pkgs_no_rts = filter ((/= rtsPackageId) . packageConfigId) pkgs
1785 let pkgs_no_rts = pkgs
1787 let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1789 -- probably _stub.o files
1790 extra_ld_inputs <- readIORef v_Ld_inputs
1792 let extra_ld_opts = getOpts dflags opt_l
1794 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags dep_packages
1796 #if defined(mingw32_HOST_OS)
1797 -----------------------------------------------------------------------------
1799 -----------------------------------------------------------------------------
1800 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1802 SysTools.runLink dflags (
1803 map SysTools.Option verbFlags
1804 ++ [ SysTools.Option "-o"
1805 , SysTools.FileOption "" output_fn
1806 , SysTools.Option "-shared"
1808 [ SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1809 | dopt Opt_SharedImplib dflags
1811 ++ map (SysTools.FileOption "") o_files
1812 ++ map SysTools.Option (
1814 -- Permit the linker to auto link _symbol to _imp_symbol
1815 -- This lets us link against DLLs without needing an "import library"
1816 ["-Wl,--enable-auto-import"]
1821 ++ pkg_lib_path_opts
1825 #elif defined(darwin_TARGET_OS)
1826 -----------------------------------------------------------------------------
1827 -- Making a darwin dylib
1828 -----------------------------------------------------------------------------
1829 -- About the options used for Darwin:
1831 -- Apple's way of saying -shared
1832 -- -undefined dynamic_lookup:
1833 -- Without these options, we'd have to specify the correct dependencies
1834 -- for each of the dylibs. Note that we could (and should) do without this
1835 -- for all libraries except the RTS; all we need to do is to pass the
1836 -- correct HSfoo_dyn.dylib files to the link command.
1837 -- This feature requires Mac OS X 10.3 or later; there is a similar feature,
1838 -- -flat_namespace -undefined suppress, which works on earlier versions,
1839 -- but it has other disadvantages.
1841 -- Build the dynamic library as a single "module", i.e. no dynamic binding
1842 -- nonsense when referring to symbols from within the library. The NCG
1843 -- assumes that this option is specified (on i386, at least).
1845 -- Mac OS/X stores the path where a dynamic library is (to be) installed
1846 -- in the library itself. It's called the "install name" of the library.
1847 -- Then any library or executable that links against it before it's
1848 -- installed will search for it in its ultimate install location. By
1849 -- default we set the install name to the absolute path at build time, but
1850 -- it can be overridden by the -dylib-install-name option passed to ghc.
1852 -----------------------------------------------------------------------------
1854 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1856 instName <- case dylibInstallName dflags of
1859 pwd <- getCurrentDirectory
1860 return $ pwd `combine` output_fn
1861 SysTools.runLink dflags (
1862 map SysTools.Option verbFlags
1863 ++ [ SysTools.Option "-dynamiclib"
1864 , SysTools.Option "-o"
1865 , SysTools.FileOption "" output_fn
1867 ++ map SysTools.Option (
1869 ++ [ "-undefined", "dynamic_lookup", "-single_module",
1870 #if !defined(x86_64_TARGET_ARCH)
1871 "-Wl,-read_only_relocs,suppress",
1873 "-install_name", instName ]
1877 ++ pkg_lib_path_opts
1882 -----------------------------------------------------------------------------
1884 -----------------------------------------------------------------------------
1886 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1887 let buildingRts = thisPackage dflags == rtsPackageId
1888 let bsymbolicFlag = if buildingRts
1889 then -- -Bsymbolic breaks the way we implement
1892 else -- we need symbolic linking to resolve
1893 -- non-PIC intra-package-relocations
1896 SysTools.runLink dflags (
1897 map SysTools.Option verbFlags
1898 ++ [ SysTools.Option "-o"
1899 , SysTools.FileOption "" output_fn
1901 ++ map SysTools.Option (
1905 -- Set the library soname. We use -h rather than -soname as
1906 -- Solaris 10 doesn't support the latter:
1907 ++ [ "-Wl,-h," ++ takeFileName output_fn ]
1911 ++ pkg_lib_path_opts
1916 -- -----------------------------------------------------------------------------
1919 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1920 doCpp dflags raw include_cc_opts input_fn output_fn = do
1921 let hscpp_opts = getOpts dflags opt_P
1922 let cmdline_include_paths = includePaths dflags
1924 pkg_include_dirs <- getPackageIncludePath dflags []
1925 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1926 (cmdline_include_paths ++ pkg_include_dirs)
1928 let verbFlags = getVerbFlags dflags
1931 | include_cc_opts = getOpts dflags opt_c
1934 let cpp_prog args | raw = SysTools.runCpp dflags args
1935 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1938 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1939 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1940 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1941 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1942 -- remember, in code we *compile*, the HOST is the same our TARGET,
1943 -- and BUILD is the same as our HOST.
1945 cpp_prog ( map SysTools.Option verbFlags
1946 ++ map SysTools.Option include_paths
1947 ++ map SysTools.Option hsSourceCppOpts
1948 ++ map SysTools.Option target_defs
1949 ++ map SysTools.Option hscpp_opts
1950 ++ map SysTools.Option cc_opts
1951 ++ [ SysTools.Option "-x"
1952 , SysTools.Option "c"
1953 , SysTools.Option input_fn
1954 -- We hackily use Option instead of FileOption here, so that the file
1955 -- name is not back-slashed on Windows. cpp is capable of
1956 -- dealing with / in filenames, so it works fine. Furthermore
1957 -- if we put in backslashes, cpp outputs #line directives
1958 -- with *double* backslashes. And that in turn means that
1959 -- our error messages get double backslashes in them.
1960 -- In due course we should arrange that the lexer deals
1961 -- with these \\ escapes properly.
1962 , SysTools.Option "-o"
1963 , SysTools.FileOption "" output_fn
1966 hsSourceCppOpts :: [String]
1967 -- Default CPP defines in Haskell source
1969 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1971 -- ---------------------------------------------------------------------------
1972 -- join object files into a single relocatable object file, using ld -r
1974 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
1975 joinObjectFiles dflags o_files output_fn = do
1976 let ld_r args = SysTools.runLink dflags ([
1977 SysTools.Option "-nostdlib",
1978 SysTools.Option "-nodefaultlibs",
1979 SysTools.Option "-Wl,-r",
1980 SysTools.Option ld_build_id,
1981 SysTools.Option ld_x_flag,
1982 SysTools.Option "-o",
1983 SysTools.FileOption "" output_fn ]
1986 ld_x_flag | null cLD_X = ""
1987 | otherwise = "-Wl,-x"
1989 -- suppress the generation of the .note.gnu.build-id section,
1990 -- which we don't need and sometimes causes ld to emit a
1992 ld_build_id | cLdHasBuildId == "YES" = "-Wl,--build-id=none"
1995 if cLdIsGNULd == "YES"
1997 script <- newTempName dflags "ldscript"
1998 writeFile script $ "INPUT(" ++ unwords o_files ++ ")"
1999 ld_r [SysTools.FileOption "" script]
2001 ld_r (map (SysTools.FileOption "") o_files)
2003 -- -----------------------------------------------------------------------------
2006 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
2007 hscNextPhase _ HsBootFile _ = StopLn
2008 hscNextPhase dflags _ hsc_lang =
2011 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
2014 HscNothing -> StopLn
2015 HscInterpreted -> StopLn