2 {-# OPTIONS -fno-warn-missing-fields #-}
3 -----------------------------------------------------------------------------
7 -- Most flags are dynamic flags, which means they can change from
8 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
9 -- multi-session GHC each session can be using different dynamic
10 -- flags. Dynamic flags can also be set at the prompt in GHCi.
12 -- (c) The University of Glasgow 2005
14 -----------------------------------------------------------------------------
20 HscTarget(..), isObjectTarget, defaultObjectTarget,
21 GhcMode(..), isOneShot,
22 GhcLink(..), isNoLink,
26 -- Configuration of the core-to-core and stg-to-stg phases
30 SimplifierMode(..), FloatOutSwitches(..),
31 getCoreToDo, getStgToDo,
33 -- Manipulating DynFlags
34 defaultDynFlags, -- DynFlags
35 initDynFlags, -- DynFlags -> IO DynFlags
37 dopt, -- DynFlag -> DynFlags -> Bool
38 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
39 getOpts, -- (DynFlags -> [a]) -> IO [a]
50 machdepCCOpts, picCCOpts
53 #include "HsVersions.h"
55 import Module ( Module, mkModuleName, mkModule )
57 import PrelNames ( mAIN )
58 #ifdef i386_TARGET_ARCH
59 import StaticFlags ( opt_Static )
61 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
63 import {-# SOURCE #-} Packages (PackageState)
64 import DriverPhases ( Phase(..), phaseInputExt )
67 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
68 import Panic ( panic, GhcException(..) )
69 import UniqFM ( UniqFM )
70 import Util ( notNull, splitLongestPrefix, normalisePath )
71 import Maybes ( orElse, fromJust )
72 import SrcLoc ( SrcSpan )
74 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
76 import Data.IORef ( readIORef )
77 import Control.Exception ( throwDyn )
78 import Control.Monad ( when )
79 #ifdef mingw32_TARGET_OS
80 import Data.List ( isPrefixOf )
85 import Data.Char ( isUpper, toLower )
86 import System.IO ( hPutStrLn, stderr )
88 -- -----------------------------------------------------------------------------
102 | Opt_D_dump_inlinings
103 | Opt_D_dump_rule_firings
104 | Opt_D_dump_occur_anal
108 | Opt_D_dump_simpl_iterations
117 | Opt_D_dump_worker_wrapper
118 | Opt_D_dump_rn_trace
119 | Opt_D_dump_rn_stats
121 | Opt_D_dump_simpl_stats
122 | Opt_D_dump_tc_trace
123 | Opt_D_dump_if_trace
129 | Opt_D_verbose_core2core
130 | Opt_D_verbose_stg2stg
132 | Opt_D_dump_hi_diffs
133 | Opt_D_dump_minimal_imports
134 | Opt_D_dump_mod_cycles
135 | Opt_D_faststring_stats
140 | Opt_WarnIsError -- -Werror; makes warnings fatal
141 | Opt_WarnDuplicateExports
143 | Opt_WarnImplicitPrelude
144 | Opt_WarnIncompletePatterns
145 | Opt_WarnIncompletePatternsRecUpd
146 | Opt_WarnMissingFields
147 | Opt_WarnMissingMethods
148 | Opt_WarnMissingSigs
149 | Opt_WarnNameShadowing
150 | Opt_WarnOverlappingPatterns
151 | Opt_WarnSimplePatterns
152 | Opt_WarnTypeDefaults
153 | Opt_WarnMonomorphism
154 | Opt_WarnUnusedBinds
155 | Opt_WarnUnusedImports
156 | Opt_WarnUnusedMatches
157 | Opt_WarnDeprecations
158 | Opt_WarnDodgyImports
163 | Opt_AllowOverlappingInstances
164 | Opt_AllowUndecidableInstances
165 | Opt_AllowIncoherentInstances
166 | Opt_MonomorphismRestriction
168 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
171 | Opt_PArr -- Syntactic support for parallel arrays
172 | Opt_Arrows -- Arrow-notation syntax
176 | Opt_ImplicitPrelude
177 | Opt_ScopedTypeVariables
179 | Opt_ExpressionSignaturesUnboxedTuples
180 | Opt_TypeSynonymUnboxedTuples
183 | Opt_OverloadedStrings
184 | Opt_DisambiguateRecordFields
185 | Opt_RecordWildCards
188 | Opt_RelaxedPolyRec -- -X=RelaxedPolyRec
189 | Opt_TypeSynonymInstances
190 | Opt_FlexibleContexts
191 | Opt_FlexibleInstances
192 | Opt_MultiParamTypeClasses
193 | Opt_FunctionalDependencies
195 | Opt_PolymorphicComponents
196 | Opt_ExistentialQuantification
200 | Opt_PatternSignatures
201 | Opt_ParallelListComp
202 | Opt_GeneralizedNewtypeDeriving
205 | Opt_PartiallyAppliedClosedTypeSynonyms
210 | Opt_PrintExplicitForalls
218 | Opt_IgnoreInterfacePragmas
219 | Opt_OmitInterfacePragmas
220 | Opt_DoLambdaEtaExpansion
222 | Opt_IgnoreBreakpoints
225 | Opt_UnboxStrictFields
236 | Opt_ExcessPrecision
237 | Opt_ReadUserPackageConf
241 | Opt_HideAllPackages
242 | Opt_PrintBindResult
245 | Opt_BreakOnException
256 data DynFlags = DynFlags {
259 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
260 stgToDo :: Maybe [StgToDo], -- similarly
261 hscTarget :: HscTarget,
262 hscOutName :: String, -- name of the output file
263 extCoreName :: String, -- name of the .core output file
264 verbosity :: Int, -- verbosity level
265 optLevel :: Int, -- optimisation level
266 maxSimplIterations :: Int, -- max simplifier iterations
267 ruleCheck :: Maybe String,
269 specThreshold :: Int, -- Threshold for function specialisation
271 stolen_x86_regs :: Int,
272 cmdlineHcIncludes :: [String], -- -#includes
273 importPaths :: [FilePath],
275 mainFunIs :: Maybe String,
276 ctxtStkDepth :: Int, -- Typechecker context stack depth
278 thisPackage :: PackageId,
281 wayNames :: [WayName], -- way flags from the cmd line
282 buildTag :: String, -- the global "way" (eg. "p" for prof)
283 rtsBuildTag :: String, -- the RTS "way"
286 objectDir :: Maybe String,
287 hiDir :: Maybe String,
288 stubDir :: Maybe String,
294 outputFile :: Maybe String,
295 outputHi :: Maybe String,
297 includePaths :: [String],
298 libraryPaths :: [String],
299 frameworkPaths :: [String], -- used on darwin only
300 cmdlineFrameworks :: [String], -- ditto
301 tmpDir :: String, -- no trailing '/'
303 ghcUsagePath :: FilePath, -- Filled in by SysTools
304 ghciUsagePath :: FilePath, -- ditto
306 hpcDir :: String, -- ^ path to store the .mix files
308 -- options for particular phases
319 -- commands for particular phases
321 pgm_P :: (String,[Option]),
323 pgm_c :: (String,[Option]),
324 pgm_m :: (String,[Option]),
325 pgm_s :: (String,[Option]),
326 pgm_a :: (String,[Option]),
327 pgm_l :: (String,[Option]),
328 pgm_dll :: (String,[Option]),
330 pgm_sysman :: String,
333 extraPkgConfs :: [FilePath],
334 topDir :: FilePath, -- filled in by SysTools
335 systemPackageConfig :: FilePath, -- ditto
336 -- The -package-conf flags given on the command line, in the order
339 packageFlags :: [PackageFlag],
340 -- The -package and -hide-package flags from the command-line
343 -- NB. do not modify this field, it is calculated by
344 -- Packages.initPackages and Packages.updatePackages.
345 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
346 pkgState :: PackageState,
352 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
363 -- | will this target result in an object file on the disk?
364 isObjectTarget :: HscTarget -> Bool
365 isObjectTarget HscC = True
366 isObjectTarget HscAsm = True
367 isObjectTarget _ = False
369 -- | The 'GhcMode' tells us whether we're doing multi-module
370 -- compilation (controlled via the "GHC" API) or one-shot
371 -- (single-module) compilation. This makes a difference primarily to
372 -- the "Finder": in one-shot mode we look for interface files for
373 -- imported modules, but in multi-module mode we look for source files
374 -- in order to check whether they need to be recompiled.
376 = CompManager -- ^ --make, GHCi, etc.
377 | OneShot -- ^ ghc -c Foo.hs
378 | MkDepend -- ^ ghc -M, see Finder for why we need this
381 isOneShot :: GhcMode -> Bool
382 isOneShot OneShot = True
383 isOneShot _other = False
385 -- | What kind of linking to do.
386 data GhcLink -- What to do in the link step, if there is one
387 = NoLink -- Don't link at all
388 | LinkBinary -- Link object code into a binary
389 | LinkInMemory -- Use the in-memory dynamic linker
390 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
393 isNoLink :: GhcLink -> Bool
394 isNoLink NoLink = True
395 isNoLink other = False
398 = ExposePackage String
400 | IgnorePackage String
403 defaultHscTarget = defaultObjectTarget
405 -- | the 'HscTarget' value corresponding to the default way to create
406 -- object files on the current platform.
408 | cGhcWithNativeCodeGen == "YES" = HscAsm
411 initDynFlags dflags = do
412 -- someday these will be dynamic flags
413 ways <- readIORef v_Ways
414 build_tag <- readIORef v_Build_tag
415 rts_build_tag <- readIORef v_RTS_Build_tag
418 buildTag = build_tag,
419 rtsBuildTag = rts_build_tag
424 ghcMode = CompManager,
425 ghcLink = LinkBinary,
428 hscTarget = defaultHscTarget,
433 maxSimplIterations = 4,
437 cmdlineHcIncludes = [],
441 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
443 thisPackage = mainPackageId,
449 objectSuf = phaseInputExt StopLn,
450 hcSuf = phaseInputExt HCc,
453 outputFile = Nothing,
458 cmdlineFrameworks = [],
459 tmpDir = cDEFAULT_TMPDIR,
475 pkgDatabase = Nothing,
476 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
478 Opt_ReadUserPackageConf,
480 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
481 -- behaviour the default, to see if anyone notices
485 Opt_MonomorphismRestriction,
490 Opt_PrintBindResult ]
491 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
492 -- The default -O0 options
495 log_action = \severity srcSpan style msg ->
497 SevInfo -> hPutStrLn stderr (show (msg style))
498 SevFatal -> hPutStrLn stderr (show (msg style))
499 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
505 0 | print errors & warnings only
506 1 | minimal verbosity: print "compiling M ... done." for each module.
507 2 | equivalent to -dshow-passes
508 3 | equivalent to existing "ghc -v"
509 4 | "ghc -v -ddump-most"
510 5 | "ghc -v -ddump-all"
513 dopt :: DynFlag -> DynFlags -> Bool
514 dopt f dflags = f `elem` (flags dflags)
516 dopt_set :: DynFlags -> DynFlag -> DynFlags
517 dopt_set dfs f = dfs{ flags = f : flags dfs }
519 dopt_unset :: DynFlags -> DynFlag -> DynFlags
520 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
522 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
523 getOpts dflags opts = reverse (opts dflags)
524 -- We add to the options from the front, so we need to reverse the list
526 getVerbFlag :: DynFlags -> String
528 | verbosity dflags >= 3 = "-v"
531 setObjectDir f d = d{ objectDir = f}
532 setHiDir f d = d{ hiDir = f}
533 setStubDir f d = d{ stubDir = f}
535 setObjectSuf f d = d{ objectSuf = f}
536 setHiSuf f d = d{ hiSuf = f}
537 setHcSuf f d = d{ hcSuf = f}
539 setOutputFile f d = d{ outputFile = f}
540 setOutputHi f d = d{ outputHi = f}
542 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
543 -- Config.hs should really use Option.
544 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
546 setPgmL f d = d{ pgm_L = f}
547 setPgmF f d = d{ pgm_F = f}
548 setPgmc f d = d{ pgm_c = (f,[])}
549 setPgmm f d = d{ pgm_m = (f,[])}
550 setPgms f d = d{ pgm_s = (f,[])}
551 setPgma f d = d{ pgm_a = (f,[])}
552 setPgml f d = d{ pgm_l = (f,[])}
553 setPgmdll f d = d{ pgm_dll = (f,[])}
555 addOptL f d = d{ opt_L = f : opt_L d}
556 addOptP f d = d{ opt_P = f : opt_P d}
557 addOptF f d = d{ opt_F = f : opt_F d}
558 addOptc f d = d{ opt_c = f : opt_c d}
559 addOptm f d = d{ opt_m = f : opt_m d}
560 addOpta f d = d{ opt_a = f : opt_a d}
561 addOptl f d = d{ opt_l = f : opt_l d}
562 addOptdll f d = d{ opt_dll = f : opt_dll d}
563 addOptdep f d = d{ opt_dep = f : opt_dep d}
565 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
567 -- -----------------------------------------------------------------------------
568 -- Command-line options
570 -- When invoking external tools as part of the compilation pipeline, we
571 -- pass these a sequence of options on the command-line. Rather than
572 -- just using a list of Strings, we use a type that allows us to distinguish
573 -- between filepaths and 'other stuff'. [The reason being, of course, that
574 -- this type gives us a handle on transforming filenames, and filenames only,
575 -- to whatever format they're expected to be on a particular platform.]
578 = FileOption -- an entry that _contains_ filename(s) / filepaths.
579 String -- a non-filepath prefix that shouldn't be
580 -- transformed (e.g., "/out=")
581 String -- the filepath/filename portion
584 -----------------------------------------------------------------------------
585 -- Setting the optimisation level
587 updOptLevel :: Int -> DynFlags -> DynFlags
588 -- Set dynflags appropriate to the optimisation level
590 = dfs2{ optLevel = final_n }
592 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
593 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
594 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
596 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
597 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
599 optLevelFlags :: [([Int], DynFlag)]
601 = [ ([0], Opt_IgnoreInterfacePragmas)
602 , ([0], Opt_OmitInterfacePragmas)
604 , ([1,2], Opt_IgnoreAsserts)
605 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
607 , ([1,2], Opt_DoEtaReduction)
608 , ([1,2], Opt_CaseMerge)
609 , ([1,2], Opt_Strictness)
611 , ([1,2], Opt_FullLaziness)
613 , ([2], Opt_LiberateCase)
614 , ([2], Opt_SpecConstr)
616 , ([0,1,2], Opt_DoLambdaEtaExpansion)
617 -- This one is important for a tiresome reason:
618 -- we want to make sure that the bindings for data
619 -- constructors are eta-expanded. This is probably
620 -- a good thing anyway, but it seems fragile.
623 -- -----------------------------------------------------------------------------
624 -- Standard sets of warning options
627 = [ Opt_WarnDeprecations,
628 Opt_WarnOverlappingPatterns,
629 Opt_WarnMissingFields,
630 Opt_WarnMissingMethods,
631 Opt_WarnDuplicateExports
635 = standardWarnings ++
636 [ Opt_WarnUnusedBinds,
637 Opt_WarnUnusedMatches,
638 Opt_WarnUnusedImports,
639 Opt_WarnIncompletePatterns,
645 [ Opt_WarnTypeDefaults,
646 Opt_WarnNameShadowing,
652 -- -----------------------------------------------------------------------------
653 -- CoreToDo: abstraction of core-to-core passes to run.
655 data CoreToDo -- These are diff core-to-core passes,
656 -- which may be invoked in any order,
657 -- as many times as you like.
659 = CoreDoSimplify -- The core-to-core simplifier.
662 -- Each run of the simplifier can take a different
663 -- set of simplifier-specific flags.
665 | CoreDoFloatOutwards FloatOutSwitches
670 | CoreDoWorkerWrapper
673 | CoreDoOldStrictness
676 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
677 -- matching this string
678 | CoreDoNothing -- Useful when building up
679 | CoreDoPasses [CoreToDo] -- lists of these things
681 data SimplifierMode -- See comments in SimplMonad
685 data SimplifierSwitch
686 = MaxSimplifierIterations Int
689 data FloatOutSwitches
690 = FloatOutSw Bool -- True <=> float lambdas to top level
691 Bool -- True <=> float constants to top level,
692 -- even if they do not escape a lambda
695 -- The core-to-core pass ordering is derived from the DynFlags:
696 runWhen :: Bool -> CoreToDo -> CoreToDo
697 runWhen True do_this = do_this
698 runWhen False do_this = CoreDoNothing
700 getCoreToDo :: DynFlags -> [CoreToDo]
702 | Just todo <- coreToDo dflags = todo -- set explicitly by user
703 | otherwise = core_todo
705 opt_level = optLevel dflags
706 max_iter = maxSimplIterations dflags
707 strictness = dopt Opt_Strictness dflags
708 full_laziness = dopt Opt_FullLaziness dflags
709 cse = dopt Opt_CSE dflags
710 spec_constr = dopt Opt_SpecConstr dflags
711 liberate_case = dopt Opt_LiberateCase dflags
712 rule_check = ruleCheck dflags
715 if opt_level == 0 then
717 CoreDoSimplify (SimplPhase 0) [
718 MaxSimplifierIterations max_iter
721 else {- opt_level >= 1 -} [
723 -- initial simplify: mk specialiser happy: minimum effort please
724 CoreDoSimplify SimplGently [
726 -- Don't inline anything till full laziness has bitten
727 -- In particular, inlining wrappers inhibits floating
728 -- e.g. ...(case f x of ...)...
729 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
730 -- ==> ...(case x of I# x# -> case fw x# of ...)...
731 -- and now the redex (f x) isn't floatable any more
732 -- Similarly, don't apply any rules until after full
733 -- laziness. Notably, list fusion can prevent floating.
735 NoCaseOfCase, -- Don't do case-of-case transformations.
736 -- This makes full laziness work better
737 MaxSimplifierIterations max_iter
740 -- Specialisation is best done before full laziness
741 -- so that overloaded functions have all their dictionary lambdas manifest
744 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
748 CoreDoSimplify (SimplPhase 2) [
749 -- Want to run with inline phase 2 after the specialiser to give
750 -- maximum chance for fusion to work before we inline build/augment
751 -- in phase 1. This made a difference in 'ansi' where an
752 -- overloaded function wasn't inlined till too late.
753 MaxSimplifierIterations max_iter
755 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
757 CoreDoSimplify (SimplPhase 1) [
758 -- Need inline-phase2 here so that build/augment get
759 -- inlined. I found that spectral/hartel/genfft lost some useful
760 -- strictness in the function sumcode' if augment is not inlined
761 -- before strictness analysis runs
762 MaxSimplifierIterations max_iter
764 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
766 CoreDoSimplify (SimplPhase 0) [
767 -- Phase 0: allow all Ids to be inlined now
768 -- This gets foldr inlined before strictness analysis
770 MaxSimplifierIterations 3
771 -- At least 3 iterations because otherwise we land up with
772 -- huge dead expressions because of an infelicity in the
774 -- let k = BIG in foldr k z xs
775 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
776 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
780 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
782 #ifdef OLD_STRICTNESS
785 runWhen strictness (CoreDoPasses [
789 CoreDoSimplify (SimplPhase 0) [
790 MaxSimplifierIterations max_iter
793 runWhen full_laziness
794 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
795 True)), -- Float constants
796 -- nofib/spectral/hartel/wang doubles in speed if you
797 -- do full laziness late in the day. It only happens
798 -- after fusion and other stuff, so the early pass doesn't
799 -- catch it. For the record, the redex is
800 -- f_el22 (f_el21 r_midblock)
804 -- We want CSE to follow the final full-laziness pass, because it may
805 -- succeed in commoning up things floated out by full laziness.
806 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
810 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
812 -- Case-liberation for -O2. This should be after
813 -- strictness analysis and the simplification which follows it.
814 runWhen liberate_case (CoreDoPasses [
816 CoreDoSimplify (SimplPhase 0) [
817 MaxSimplifierIterations max_iter
818 ] ]), -- Run the simplifier after LiberateCase to vastly
819 -- reduce the possiblility of shadowing
820 -- Reason: see Note [Shadowing] in SpecConstr.lhs
822 runWhen spec_constr CoreDoSpecConstr,
824 -- Final clean-up simplification:
825 CoreDoSimplify (SimplPhase 0) [
826 MaxSimplifierIterations max_iter
830 -- -----------------------------------------------------------------------------
831 -- StgToDo: abstraction of stg-to-stg passes to run.
834 = StgDoMassageForProfiling -- should be (next to) last
835 -- There's also setStgVarInfo, but its absolute "lastness"
836 -- is so critical that it is hardwired in (no flag).
839 getStgToDo :: DynFlags -> [StgToDo]
841 | Just todo <- stgToDo dflags = todo -- set explicitly by user
844 stg_stats = dopt Opt_StgStats dflags
846 todo1 = if stg_stats then [D_stg_stats] else []
848 todo2 | WayProf `elem` wayNames dflags
849 = StgDoMassageForProfiling : todo1
853 -- -----------------------------------------------------------------------------
857 allFlags = map ('-':) $
858 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
859 map ("fno-"++) flags ++
861 where ok (PrefixPred _ _) = False
863 flags = map fst fFlags
865 dynamic_flags :: [(String, OptKind DynP)]
867 ( "n" , NoArg (setDynFlag Opt_DryRun) )
868 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
869 , ( "F" , NoArg (setDynFlag Opt_Pp))
870 , ( "#include" , HasArg (addCmdlineHCInclude) )
871 , ( "v" , OptIntSuffix setVerbosity )
873 ------- Specific phases --------------------------------------------
874 , ( "pgmL" , HasArg (upd . setPgmL) )
875 , ( "pgmP" , HasArg (upd . setPgmP) )
876 , ( "pgmF" , HasArg (upd . setPgmF) )
877 , ( "pgmc" , HasArg (upd . setPgmc) )
878 , ( "pgmm" , HasArg (upd . setPgmm) )
879 , ( "pgms" , HasArg (upd . setPgms) )
880 , ( "pgma" , HasArg (upd . setPgma) )
881 , ( "pgml" , HasArg (upd . setPgml) )
882 , ( "pgmdll" , HasArg (upd . setPgmdll) )
884 , ( "optL" , HasArg (upd . addOptL) )
885 , ( "optP" , HasArg (upd . addOptP) )
886 , ( "optF" , HasArg (upd . addOptF) )
887 , ( "optc" , HasArg (upd . addOptc) )
888 , ( "optm" , HasArg (upd . addOptm) )
889 , ( "opta" , HasArg (upd . addOpta) )
890 , ( "optl" , HasArg (upd . addOptl) )
891 , ( "optdll" , HasArg (upd . addOptdll) )
892 , ( "optdep" , HasArg (upd . addOptdep) )
894 , ( "split-objs" , NoArg (if can_split
895 then setDynFlag Opt_SplitObjs
898 -------- Linking ----------------------------------------------------
899 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
900 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
901 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
903 ------- Libraries ---------------------------------------------------
904 , ( "L" , Prefix addLibraryPath )
905 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
908 ------- Frameworks --------------------------------------------------
909 -- -framework-path should really be -F ...
910 , ( "framework-path" , HasArg addFrameworkPath )
911 , ( "framework" , HasArg (upd . addCmdlineFramework) )
913 ------- Output Redirection ------------------------------------------
914 , ( "odir" , HasArg (upd . setObjectDir . Just))
915 , ( "o" , SepArg (upd . setOutputFile . Just))
916 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
917 , ( "osuf" , HasArg (upd . setObjectSuf))
918 , ( "hcsuf" , HasArg (upd . setHcSuf))
919 , ( "hisuf" , HasArg (upd . setHiSuf))
920 , ( "hidir" , HasArg (upd . setHiDir . Just))
921 , ( "tmpdir" , HasArg (upd . setTmpDir))
922 , ( "stubdir" , HasArg (upd . setStubDir . Just))
924 ------- Keeping temporary files -------------------------------------
925 -- These can be singular (think ghc -c) or plural (think ghc --make)
926 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
927 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
928 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
929 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
930 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
931 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
932 -- This only makes sense as plural
933 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
935 ------- Miscellaneous ----------------------------------------------
936 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
937 , ( "main-is" , SepArg setMainIs )
938 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
939 , ( "hpcdir" , SepArg setOptHpcDir )
941 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
942 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
943 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
945 ------- Packages ----------------------------------------------------
946 , ( "package-conf" , HasArg extraPkgConf_ )
947 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
948 , ( "package-name" , HasArg (upd . setPackageName) )
949 , ( "package" , HasArg exposePackage )
950 , ( "hide-package" , HasArg hidePackage )
951 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
952 , ( "ignore-package" , HasArg ignorePackage )
953 , ( "syslib" , HasArg exposePackage ) -- for compatibility
955 ------ HsCpp opts ---------------------------------------------------
956 , ( "D", AnySuffix (upd . addOptP) )
957 , ( "U", AnySuffix (upd . addOptP) )
959 ------- Include/Import Paths ----------------------------------------
960 , ( "I" , Prefix addIncludePath)
961 , ( "i" , OptPrefix addImportPath )
963 ------ Debugging ----------------------------------------------------
964 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
966 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
967 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
968 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
969 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
970 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
971 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
972 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
973 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
974 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
975 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
976 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
977 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
978 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
979 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
980 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
981 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
982 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
983 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
984 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
985 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
986 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
987 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
988 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
989 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
990 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
991 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
992 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
993 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
994 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
995 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
996 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
997 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
998 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
999 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
1000 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
1001 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
1002 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
1003 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
1004 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
1005 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
1007 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
1008 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
1009 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
1010 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1011 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1012 setVerbosity (Just 2)) )
1013 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1015 ------ Machine dependant (-m<blah>) stuff ---------------------------
1017 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1018 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1019 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1021 ------ Warning opts -------------------------------------------------
1022 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1023 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1024 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1025 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1026 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
1028 ------ Optimisation flags ------------------------------------------
1029 , ( "O" , NoArg (upd (setOptLevel 1)))
1030 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1031 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1032 -- If the number is missing, use 1
1034 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1035 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1037 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1038 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1039 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1041 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1042 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1044 ------ Compiler flags -----------------------------------------------
1046 , ( "fasm", NoArg (setObjTarget HscAsm) )
1047 , ( "fvia-c", NoArg (setObjTarget HscC) )
1048 , ( "fvia-C", NoArg (setObjTarget HscC) )
1050 , ( "fno-code", NoArg (setTarget HscNothing))
1051 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1052 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1054 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1055 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1057 -- the rest of the -f* and -fno-* flags
1058 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1059 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1061 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1062 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1063 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1065 -- the rest of the -X* and -Xno-* flags
1066 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1067 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1070 -- these -f<blah> flags can all be reversed with -fno-<blah>
1073 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1074 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1075 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1076 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1077 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1078 ( "warn-missing-fields", Opt_WarnMissingFields ),
1079 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1080 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1081 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1082 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1083 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1084 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1085 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1086 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1087 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1088 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1089 ( "warn-deprecations", Opt_WarnDeprecations ),
1090 ( "warn-orphans", Opt_WarnOrphans ),
1091 ( "warn-tabs", Opt_WarnTabs ),
1092 ( "print-explicit-foralls", Opt_PrintExplicitForalls ),
1093 ( "strictness", Opt_Strictness ),
1094 ( "full-laziness", Opt_FullLaziness ),
1095 ( "liberate-case", Opt_LiberateCase ),
1096 ( "spec-constr", Opt_SpecConstr ),
1098 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1099 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1100 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1101 ( "ignore-asserts", Opt_IgnoreAsserts ),
1102 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1103 ( "do-eta-reduction", Opt_DoEtaReduction ),
1104 ( "case-merge", Opt_CaseMerge ),
1105 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1106 ( "dicts-cheap", Opt_DictsCheap ),
1107 ( "excess-precision", Opt_ExcessPrecision ),
1108 ( "asm-mangling", Opt_DoAsmMangling ),
1109 ( "print-bind-result", Opt_PrintBindResult ),
1110 ( "force-recomp", Opt_ForceRecomp ),
1111 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1112 ( "rewrite-rules", Opt_RewriteRules ),
1113 ( "break-on-exception", Opt_BreakOnException ),
1114 ( "vectorise", Opt_Vectorise )
1118 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1119 xFlags :: [(String, DynFlag)]
1122 ( "PatternGuards", Opt_PatternGuards ),
1123 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1124 ( "MagicHash", Opt_MagicHash ),
1125 ( "PolymorphicComponents", Opt_PolymorphicComponents ),
1126 ( "ExistentialQuantification", Opt_ExistentialQuantification ),
1127 ( "KindSignatures", Opt_KindSignatures ),
1128 ( "PatternSignatures", Opt_PatternSignatures ),
1129 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1130 ( "ParallelListComp", Opt_ParallelListComp ),
1131 ( "FI", Opt_FFI ), -- support `-ffi'...
1132 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1133 ( "ForeignFunctionInterface", Opt_FFI ),
1135 ( "PartiallyAppliedClosedTypeSynonyms", Opt_PartiallyAppliedClosedTypeSynonyms ),
1136 ( "Rank2Types", Opt_Rank2Types ),
1137 ( "RankNTypes", Opt_RankNTypes ),
1138 ( "TypeOperators", Opt_TypeOperators ),
1139 ( "RecursiveDo", Opt_RecursiveDo ),
1140 ( "Arrows", Opt_Arrows ), -- arrow syntax
1141 ( "Parr", Opt_PArr ),
1143 ( "TH", Opt_TH ), -- support -fth
1144 ( "TemplateHaskelll", Opt_TH ),
1146 ( "Generics", Opt_Generics ),
1148 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1150 ( "RecordWildCards", Opt_RecordWildCards ),
1151 ( "RecordPuns", Opt_RecordPuns ),
1152 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1154 ( "OverloadedStrings", Opt_OverloadedStrings ),
1155 ( "GADTs", Opt_GADTs ),
1156 ( "TypeFamilies", Opt_TypeFamilies ),
1157 ( "BangPatterns", Opt_BangPatterns ),
1158 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1159 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1160 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1161 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1162 ( "ImplicitParams", Opt_ImplicitParams ),
1163 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1164 ( "UnboxedTuples", Opt_UnboxedTuples ),
1165 ( "ExpressionSignaturesUnboxedTuples", Opt_ExpressionSignaturesUnboxedTuples ),
1166 ( "TypeSynonymUnboxedTuples", Opt_TypeSynonymUnboxedTuples ),
1167 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1168 ( "FlexibleContexts", Opt_FlexibleContexts ),
1169 ( "FlexibleInstances", Opt_FlexibleInstances ),
1170 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1171 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1172 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1173 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1174 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1175 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1178 impliedFlags :: [(DynFlag, [DynFlag])]
1180 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1183 glasgowExtsFlags = [ Opt_GlasgowExts
1184 , Opt_PrintExplicitForalls
1187 , Opt_ImplicitParams
1188 , Opt_ScopedTypeVariables
1190 , Opt_ExpressionSignaturesUnboxedTuples
1191 , Opt_TypeSynonymUnboxedTuples
1192 , Opt_TypeSynonymInstances
1193 , Opt_FlexibleContexts
1194 , Opt_FlexibleInstances
1195 , Opt_MultiParamTypeClasses
1196 , Opt_FunctionalDependencies
1198 , Opt_PolymorphicComponents
1199 , Opt_ExistentialQuantification
1202 , Opt_PartiallyAppliedClosedTypeSynonyms
1206 , Opt_ParallelListComp
1207 , Opt_EmptyDataDecls
1208 , Opt_KindSignatures
1209 , Opt_PatternSignatures
1210 , Opt_GeneralizedNewtypeDeriving
1211 , Opt_TypeFamilies ]
1214 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1216 isFlag flags f = is_flag flags (normaliseFlag f)
1219 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1222 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1223 -- nf is normalised alreadly
1226 getFlag, getNoFlag :: [(String,a)] -> String -> a
1228 getFlag flags f = get_flag flags (normaliseFlag f)
1230 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1231 -- The flag should be a no-flag already
1233 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1235 [] -> panic ("get_flag " ++ nf)
1238 noFlag_maybe :: String -> Maybe String
1239 -- The input is normalised already
1240 noFlag_maybe ('n' : 'o' : f) = Just f
1241 noFlag_maybe other = Nothing
1243 normaliseFlag :: String -> String
1244 -- Normalise a option flag by
1245 -- * map to lower case
1246 -- * removing hyphens
1247 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1248 normaliseFlag [] = []
1249 normaliseFlag ('-':s) = normaliseFlag s
1250 normaliseFlag (c:s) = toLower c : normaliseFlag s
1252 -- -----------------------------------------------------------------------------
1253 -- Parsing the dynamic flags.
1255 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1256 parseDynamicFlags dflags args = do
1257 let ((leftover,errs),dflags')
1258 = runCmdLine (processArgs dynamic_flags args) dflags
1259 when (not (null errs)) $ do
1260 throwDyn (UsageError (unlines errs))
1261 return (dflags', leftover)
1264 type DynP = CmdLineP DynFlags
1266 upd :: (DynFlags -> DynFlags) -> DynP ()
1268 dfs <- getCmdLineState
1269 putCmdLineState $! (f dfs)
1271 --------------------------
1272 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1273 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1275 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1276 -- When you set f, set the ones it implies
1277 -- When you un-set f, however, we don't un-set the things it implies
1278 -- (except for -fno-glasgow-exts, which is treated specially)
1280 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1282 --------------------------
1283 setDumpFlag :: DynFlag -> OptKind DynP
1284 setDumpFlag dump_flag
1285 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1286 -- Whenver we -ddump, switch off the recompilation checker,
1287 -- else you don't see the dump!
1289 setVerbosity :: Maybe Int -> DynP ()
1290 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1292 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1294 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1297 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1299 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1301 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1304 | Nothing <- unpackPackageId pid
1305 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1307 = \s -> s{ thisPackage = pid }
1309 pid = stringToPackageId p
1311 -- If we're linking a binary, then only targets that produce object
1312 -- code are allowed (requests for other target types are ignored).
1313 setTarget l = upd set
1316 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1319 -- Changes the target only if we're compiling object code. This is
1320 -- used by -fasm and -fvia-C, which switch from one to the other, but
1321 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1322 -- can be safely used in an OPTIONS_GHC pragma.
1323 setObjTarget l = upd set
1326 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1329 setOptLevel :: Int -> DynFlags -> DynFlags
1330 setOptLevel n dflags
1331 | hscTarget dflags == HscInterpreted && n > 0
1333 -- not in IO any more, oh well:
1334 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1336 = updOptLevel n dflags
1339 setMainIs :: String -> DynP ()
1341 | not (null main_fn) -- The arg looked like "Foo.baz"
1342 = upd $ \d -> d{ mainFunIs = Just main_fn,
1343 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1345 | isUpper (head main_mod) -- The arg looked like "Foo"
1346 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1348 | otherwise -- The arg looked like "baz"
1349 = upd $ \d -> d{ mainFunIs = Just main_mod }
1351 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1353 -----------------------------------------------------------------------------
1354 -- Paths & Libraries
1356 -- -i on its own deletes the import paths
1357 addImportPath "" = upd (\s -> s{importPaths = []})
1358 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1362 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1365 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1367 addFrameworkPath p =
1368 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1370 split_marker = ':' -- not configurable (ToDo)
1372 splitPathList :: String -> [String]
1373 splitPathList s = filter notNull (splitUp s)
1374 -- empty paths are ignored: there might be a trailing
1375 -- ':' in the initial list, for example. Empty paths can
1376 -- cause confusion when they are translated into -I options
1377 -- for passing to gcc.
1379 #ifndef mingw32_TARGET_OS
1380 splitUp xs = split split_marker xs
1382 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1384 -- That is, if "foo:bar:baz" is used, this interpreted as
1385 -- consisting of three entries, 'foo', 'bar', 'baz'.
1386 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1387 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1389 -- Notice that no attempt is made to fully replace the 'standard'
1390 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1391 -- that this will cause too much breakage for users & ':' will
1392 -- work fine even with DOS paths, if you're not insisting on being silly.
1395 splitUp (x:':':div:xs) | div `elem` dir_markers
1396 = ((x:':':div:p): splitUp rs)
1398 (p,rs) = findNextPath xs
1399 -- we used to check for existence of the path here, but that
1400 -- required the IO monad to be threaded through the command-line
1401 -- parser which is quite inconvenient. The
1402 splitUp xs = cons p (splitUp rs)
1404 (p,rs) = findNextPath xs
1409 -- will be called either when we've consumed nought or the
1410 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1411 -- finding the next split marker.
1413 case break (`elem` split_markers) xs of
1414 (p, d:ds) -> (p, ds)
1417 split_markers :: [Char]
1418 split_markers = [':', ';']
1420 dir_markers :: [Char]
1421 dir_markers = ['/', '\\']
1424 -- -----------------------------------------------------------------------------
1425 -- tmpDir, where we store temporary files.
1427 setTmpDir :: FilePath -> DynFlags -> DynFlags
1428 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1430 #if !defined(mingw32_HOST_OS)
1431 canonicalise p = normalisePath p
1433 -- Canonicalisation of temp path under win32 is a bit more
1434 -- involved: (a) strip trailing slash,
1435 -- (b) normalise slashes
1436 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1438 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1440 -- if we're operating under cygwin, and TMP/TEMP is of
1441 -- the form "/cygdrive/drive/path", translate this to
1442 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1443 -- understand /cygdrive paths.)
1445 | "/cygdrive/" `isPrefixOf` path =
1446 case drop (length "/cygdrive/") path of
1447 drive:xs@('/':_) -> drive:':':xs
1451 -- strip the trailing backslash (awful, but we only do this once).
1452 removeTrailingSlash path =
1459 -----------------------------------------------------------------------------
1462 setOptHpcDir :: String -> DynP ()
1463 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1465 -----------------------------------------------------------------------------
1466 -- Via-C compilation stuff
1468 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1469 [String]) -- for registerised HC compilations
1470 machdepCCOpts dflags
1471 #if alpha_TARGET_ARCH
1473 #ifdef HAVE_THREADED_RTS_SUPPORT
1477 -- For now, to suppress the gcc warning "call-clobbered
1478 -- register used for global register variable", we simply
1479 -- disable all warnings altogether using the -w flag. Oh well.
1481 #elif hppa_TARGET_ARCH
1482 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1483 -- (very nice, but too bad the HP /usr/include files don't agree.)
1484 = ( ["-D_HPUX_SOURCE"], [] )
1486 #elif m68k_TARGET_ARCH
1487 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1488 -- popping of args to routines to be explicit; if we let things
1489 -- be deferred 'til after an STGJUMP, imminent death is certain!
1491 -- -fomit-frame-pointer : *don't*
1492 -- It's better to have a6 completely tied up being a frame pointer
1493 -- rather than let GCC pick random things to do with it.
1494 -- (If we want to steal a6, then we would try to do things
1495 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1496 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1498 #elif i386_TARGET_ARCH
1499 -- -fno-defer-pop : basically the same game as for m68k
1501 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1502 -- the fp (%ebp) for our register maps.
1503 = let n_regs = stolen_x86_regs dflags
1506 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1507 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1510 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1511 -- Some gccs are configured with
1512 -- -momit-leaf-frame-pointer on by default, and it
1513 -- apparently takes precedence over
1514 -- -fomit-frame-pointer, so we disable it first here.
1515 "-mno-omit-leaf-frame-pointer",
1517 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1518 "-fno-unit-at-a-time",
1519 -- unit-at-a-time doesn't do us any good, and screws
1520 -- up -split-objs by moving the split markers around.
1521 -- It's only turned on with -O2, but put it here just
1522 -- in case someone uses -optc-O2.
1524 "-fomit-frame-pointer",
1525 -- we want -fno-builtin, because when gcc inlines
1526 -- built-in functions like memcpy() it tends to
1527 -- run out of registers, requiring -monly-n-regs
1529 "-DSTOLEN_X86_REGS="++show n_regs ]
1532 #elif ia64_TARGET_ARCH
1533 = ( [], ["-fomit-frame-pointer", "-G0"] )
1535 #elif x86_64_TARGET_ARCH
1536 = ( [], ["-fomit-frame-pointer",
1537 "-fno-asynchronous-unwind-tables",
1538 -- the unwind tables are unnecessary for HC code,
1539 -- and get in the way of -split-objs. Another option
1540 -- would be to throw them away in the mangler, but this
1542 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1543 "-fno-unit-at-a-time",
1544 -- unit-at-a-time doesn't do us any good, and screws
1545 -- up -split-objs by moving the split markers around.
1546 -- It's only turned on with -O2, but put it here just
1547 -- in case someone uses -optc-O2.
1550 -- calling builtins like strlen() using the FFI can
1551 -- cause gcc to run out of regs, so use the external
1555 #elif sparc_TARGET_ARCH
1557 -- For now, to suppress the gcc warning "call-clobbered
1558 -- register used for global register variable", we simply
1559 -- disable all warnings altogether using the -w flag. Oh well.
1561 #elif powerpc_apple_darwin_TARGET
1563 -- Disable Apple's precompiling preprocessor. It's a great thing
1564 -- for "normal" programs, but it doesn't support register variable
1566 = ( [], ["-no-cpp-precomp"] )
1571 picCCOpts :: DynFlags -> [String]
1573 #if darwin_TARGET_OS
1574 -- Apple prefers to do things the other way round.
1575 -- PIC is on by default.
1576 -- -mdynamic-no-pic:
1577 -- Turn off PIC code generation.
1579 -- Don't generate "common" symbols - these are unwanted
1580 -- in dynamic libraries.
1585 = ["-mdynamic-no-pic"]
1586 #elif mingw32_TARGET_OS
1587 -- no -fPIC for Windows
1596 -- -----------------------------------------------------------------------------
1601 #if defined(i386_TARGET_ARCH) \
1602 || defined(x86_64_TARGET_ARCH) \
1603 || defined(alpha_TARGET_ARCH) \
1604 || defined(hppa_TARGET_ARCH) \
1605 || defined(m68k_TARGET_ARCH) \
1606 || defined(mips_TARGET_ARCH) \
1607 || defined(powerpc_TARGET_ARCH) \
1608 || defined(rs6000_TARGET_ARCH) \
1609 || defined(sparc_TARGET_ARCH)