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
170 | Opt_UnliftedFFITypes
171 | Opt_PArr -- Syntactic support for parallel arrays
172 | Opt_Arrows -- Arrow-notation syntax
176 | Opt_ImplicitPrelude
177 | Opt_ScopedTypeVariables
181 | Opt_OverloadedStrings
182 | Opt_DisambiguateRecordFields
183 | Opt_RecordWildCards
186 | Opt_RelaxedPolyRec -- -X=RelaxedPolyRec
187 | Opt_StandaloneDeriving
188 | Opt_DeriveDataTypeable
189 | Opt_TypeSynonymInstances
190 | Opt_FlexibleContexts
191 | Opt_FlexibleInstances
192 | Opt_ConstrainedClassMethods
193 | Opt_MultiParamTypeClasses
194 | Opt_FunctionalDependencies
196 | Opt_PolymorphicComponents
197 | Opt_ExistentialQuantification
201 | Opt_PatternSignatures
202 | Opt_ParallelListComp
203 | Opt_GeneralizedNewtypeDeriving
206 | Opt_PartiallyAppliedClosedTypeSynonyms
211 | Opt_PrintExplicitForalls
219 | Opt_IgnoreInterfacePragmas
220 | Opt_OmitInterfacePragmas
221 | Opt_DoLambdaEtaExpansion
223 | Opt_IgnoreBreakpoints
226 | Opt_UnboxStrictFields
237 | Opt_ExcessPrecision
238 | Opt_ReadUserPackageConf
242 | Opt_HideAllPackages
243 | Opt_PrintBindResult
246 | Opt_BreakOnException
257 data DynFlags = DynFlags {
260 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
261 stgToDo :: Maybe [StgToDo], -- similarly
262 hscTarget :: HscTarget,
263 hscOutName :: String, -- name of the output file
264 extCoreName :: String, -- name of the .core output file
265 verbosity :: Int, -- verbosity level
266 optLevel :: Int, -- optimisation level
267 maxSimplIterations :: Int, -- max simplifier iterations
268 ruleCheck :: Maybe String,
270 specThreshold :: Int, -- Threshold for function specialisation
272 stolen_x86_regs :: Int,
273 cmdlineHcIncludes :: [String], -- -#includes
274 importPaths :: [FilePath],
276 mainFunIs :: Maybe String,
277 ctxtStkDepth :: Int, -- Typechecker context stack depth
279 thisPackage :: PackageId,
282 wayNames :: [WayName], -- way flags from the cmd line
283 buildTag :: String, -- the global "way" (eg. "p" for prof)
284 rtsBuildTag :: String, -- the RTS "way"
287 objectDir :: Maybe String,
288 hiDir :: Maybe String,
289 stubDir :: Maybe String,
295 outputFile :: Maybe String,
296 outputHi :: Maybe String,
298 includePaths :: [String],
299 libraryPaths :: [String],
300 frameworkPaths :: [String], -- used on darwin only
301 cmdlineFrameworks :: [String], -- ditto
302 tmpDir :: String, -- no trailing '/'
304 ghcUsagePath :: FilePath, -- Filled in by SysTools
305 ghciUsagePath :: FilePath, -- ditto
307 hpcDir :: String, -- ^ path to store the .mix files
309 -- options for particular phases
320 -- commands for particular phases
322 pgm_P :: (String,[Option]),
324 pgm_c :: (String,[Option]),
325 pgm_m :: (String,[Option]),
326 pgm_s :: (String,[Option]),
327 pgm_a :: (String,[Option]),
328 pgm_l :: (String,[Option]),
329 pgm_dll :: (String,[Option]),
331 pgm_sysman :: String,
334 extraPkgConfs :: [FilePath],
335 topDir :: FilePath, -- filled in by SysTools
336 systemPackageConfig :: FilePath, -- ditto
337 -- The -package-conf flags given on the command line, in the order
340 packageFlags :: [PackageFlag],
341 -- The -package and -hide-package flags from the command-line
344 -- NB. do not modify this field, it is calculated by
345 -- Packages.initPackages and Packages.updatePackages.
346 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
347 pkgState :: PackageState,
353 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
364 -- | will this target result in an object file on the disk?
365 isObjectTarget :: HscTarget -> Bool
366 isObjectTarget HscC = True
367 isObjectTarget HscAsm = True
368 isObjectTarget _ = False
370 -- | The 'GhcMode' tells us whether we're doing multi-module
371 -- compilation (controlled via the "GHC" API) or one-shot
372 -- (single-module) compilation. This makes a difference primarily to
373 -- the "Finder": in one-shot mode we look for interface files for
374 -- imported modules, but in multi-module mode we look for source files
375 -- in order to check whether they need to be recompiled.
377 = CompManager -- ^ --make, GHCi, etc.
378 | OneShot -- ^ ghc -c Foo.hs
379 | MkDepend -- ^ ghc -M, see Finder for why we need this
382 isOneShot :: GhcMode -> Bool
383 isOneShot OneShot = True
384 isOneShot _other = False
386 -- | What kind of linking to do.
387 data GhcLink -- What to do in the link step, if there is one
388 = NoLink -- Don't link at all
389 | LinkBinary -- Link object code into a binary
390 | LinkInMemory -- Use the in-memory dynamic linker
391 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
394 isNoLink :: GhcLink -> Bool
395 isNoLink NoLink = True
396 isNoLink other = False
399 = ExposePackage String
401 | IgnorePackage String
404 defaultHscTarget = defaultObjectTarget
406 -- | the 'HscTarget' value corresponding to the default way to create
407 -- object files on the current platform.
409 | cGhcWithNativeCodeGen == "YES" = HscAsm
412 initDynFlags dflags = do
413 -- someday these will be dynamic flags
414 ways <- readIORef v_Ways
415 build_tag <- readIORef v_Build_tag
416 rts_build_tag <- readIORef v_RTS_Build_tag
419 buildTag = build_tag,
420 rtsBuildTag = rts_build_tag
425 ghcMode = CompManager,
426 ghcLink = LinkBinary,
429 hscTarget = defaultHscTarget,
434 maxSimplIterations = 4,
438 cmdlineHcIncludes = [],
442 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
444 thisPackage = mainPackageId,
450 objectSuf = phaseInputExt StopLn,
451 hcSuf = phaseInputExt HCc,
454 outputFile = Nothing,
459 cmdlineFrameworks = [],
460 tmpDir = cDEFAULT_TMPDIR,
476 pkgDatabase = Nothing,
477 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
479 Opt_ReadUserPackageConf,
481 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
482 -- behaviour the default, to see if anyone notices
486 Opt_MonomorphismRestriction,
491 Opt_PrintBindResult ]
492 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
493 -- The default -O0 options
496 log_action = \severity srcSpan style msg ->
498 SevInfo -> hPutStrLn stderr (show (msg style))
499 SevFatal -> hPutStrLn stderr (show (msg style))
500 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
506 0 | print errors & warnings only
507 1 | minimal verbosity: print "compiling M ... done." for each module.
508 2 | equivalent to -dshow-passes
509 3 | equivalent to existing "ghc -v"
510 4 | "ghc -v -ddump-most"
511 5 | "ghc -v -ddump-all"
514 dopt :: DynFlag -> DynFlags -> Bool
515 dopt f dflags = f `elem` (flags dflags)
517 dopt_set :: DynFlags -> DynFlag -> DynFlags
518 dopt_set dfs f = dfs{ flags = f : flags dfs }
520 dopt_unset :: DynFlags -> DynFlag -> DynFlags
521 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
523 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
524 getOpts dflags opts = reverse (opts dflags)
525 -- We add to the options from the front, so we need to reverse the list
527 getVerbFlag :: DynFlags -> String
529 | verbosity dflags >= 3 = "-v"
532 setObjectDir f d = d{ objectDir = f}
533 setHiDir f d = d{ hiDir = f}
534 setStubDir f d = d{ stubDir = f}
536 setObjectSuf f d = d{ objectSuf = f}
537 setHiSuf f d = d{ hiSuf = f}
538 setHcSuf f d = d{ hcSuf = f}
540 setOutputFile f d = d{ outputFile = f}
541 setOutputHi f d = d{ outputHi = f}
543 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
544 -- Config.hs should really use Option.
545 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
547 setPgmL f d = d{ pgm_L = f}
548 setPgmF f d = d{ pgm_F = f}
549 setPgmc f d = d{ pgm_c = (f,[])}
550 setPgmm f d = d{ pgm_m = (f,[])}
551 setPgms f d = d{ pgm_s = (f,[])}
552 setPgma f d = d{ pgm_a = (f,[])}
553 setPgml f d = d{ pgm_l = (f,[])}
554 setPgmdll f d = d{ pgm_dll = (f,[])}
556 addOptL f d = d{ opt_L = f : opt_L d}
557 addOptP f d = d{ opt_P = f : opt_P d}
558 addOptF f d = d{ opt_F = f : opt_F d}
559 addOptc f d = d{ opt_c = f : opt_c d}
560 addOptm f d = d{ opt_m = f : opt_m d}
561 addOpta f d = d{ opt_a = f : opt_a d}
562 addOptl f d = d{ opt_l = f : opt_l d}
563 addOptdll f d = d{ opt_dll = f : opt_dll d}
564 addOptdep f d = d{ opt_dep = f : opt_dep d}
566 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
568 -- -----------------------------------------------------------------------------
569 -- Command-line options
571 -- When invoking external tools as part of the compilation pipeline, we
572 -- pass these a sequence of options on the command-line. Rather than
573 -- just using a list of Strings, we use a type that allows us to distinguish
574 -- between filepaths and 'other stuff'. [The reason being, of course, that
575 -- this type gives us a handle on transforming filenames, and filenames only,
576 -- to whatever format they're expected to be on a particular platform.]
579 = FileOption -- an entry that _contains_ filename(s) / filepaths.
580 String -- a non-filepath prefix that shouldn't be
581 -- transformed (e.g., "/out=")
582 String -- the filepath/filename portion
585 -----------------------------------------------------------------------------
586 -- Setting the optimisation level
588 updOptLevel :: Int -> DynFlags -> DynFlags
589 -- Set dynflags appropriate to the optimisation level
591 = dfs2{ optLevel = final_n }
593 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
594 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
595 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
597 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
598 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
600 optLevelFlags :: [([Int], DynFlag)]
602 = [ ([0], Opt_IgnoreInterfacePragmas)
603 , ([0], Opt_OmitInterfacePragmas)
605 , ([1,2], Opt_IgnoreAsserts)
606 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
608 , ([1,2], Opt_DoEtaReduction)
609 , ([1,2], Opt_CaseMerge)
610 , ([1,2], Opt_Strictness)
612 , ([1,2], Opt_FullLaziness)
614 , ([2], Opt_LiberateCase)
615 , ([2], Opt_SpecConstr)
617 , ([0,1,2], Opt_DoLambdaEtaExpansion)
618 -- This one is important for a tiresome reason:
619 -- we want to make sure that the bindings for data
620 -- constructors are eta-expanded. This is probably
621 -- a good thing anyway, but it seems fragile.
624 -- -----------------------------------------------------------------------------
625 -- Standard sets of warning options
628 = [ Opt_WarnDeprecations,
629 Opt_WarnOverlappingPatterns,
630 Opt_WarnMissingFields,
631 Opt_WarnMissingMethods,
632 Opt_WarnDuplicateExports
636 = standardWarnings ++
637 [ Opt_WarnUnusedBinds,
638 Opt_WarnUnusedMatches,
639 Opt_WarnUnusedImports,
640 Opt_WarnIncompletePatterns,
646 [ Opt_WarnTypeDefaults,
647 Opt_WarnNameShadowing,
653 -- minuswRemovesOpts should be every warning option
656 [Opt_WarnImplicitPrelude,
657 Opt_WarnIncompletePatternsRecUpd,
658 Opt_WarnSimplePatterns,
659 Opt_WarnMonomorphism,
663 -- -----------------------------------------------------------------------------
664 -- CoreToDo: abstraction of core-to-core passes to run.
666 data CoreToDo -- These are diff core-to-core passes,
667 -- which may be invoked in any order,
668 -- as many times as you like.
670 = CoreDoSimplify -- The core-to-core simplifier.
673 -- Each run of the simplifier can take a different
674 -- set of simplifier-specific flags.
676 | CoreDoFloatOutwards FloatOutSwitches
681 | CoreDoWorkerWrapper
684 | CoreDoOldStrictness
687 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
688 -- matching this string
689 | CoreDoVectorisation
690 | CoreDoNothing -- Useful when building up
691 | CoreDoPasses [CoreToDo] -- lists of these things
693 data SimplifierMode -- See comments in SimplMonad
697 data SimplifierSwitch
698 = MaxSimplifierIterations Int
701 data FloatOutSwitches
702 = FloatOutSw Bool -- True <=> float lambdas to top level
703 Bool -- True <=> float constants to top level,
704 -- even if they do not escape a lambda
707 -- The core-to-core pass ordering is derived from the DynFlags:
708 runWhen :: Bool -> CoreToDo -> CoreToDo
709 runWhen True do_this = do_this
710 runWhen False do_this = CoreDoNothing
712 getCoreToDo :: DynFlags -> [CoreToDo]
714 | Just todo <- coreToDo dflags = todo -- set explicitly by user
715 | otherwise = core_todo
717 opt_level = optLevel dflags
718 max_iter = maxSimplIterations dflags
719 strictness = dopt Opt_Strictness dflags
720 full_laziness = dopt Opt_FullLaziness dflags
721 cse = dopt Opt_CSE dflags
722 spec_constr = dopt Opt_SpecConstr dflags
723 liberate_case = dopt Opt_LiberateCase dflags
724 rule_check = ruleCheck dflags
725 vectorisation = dopt Opt_Vectorise dflags
728 if opt_level == 0 then
730 CoreDoSimplify (SimplPhase 0) [
731 MaxSimplifierIterations max_iter
734 else {- opt_level >= 1 -} [
736 -- initial simplify: mk specialiser happy: minimum effort please
737 CoreDoSimplify SimplGently [
739 -- Don't inline anything till full laziness has bitten
740 -- In particular, inlining wrappers inhibits floating
741 -- e.g. ...(case f x of ...)...
742 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
743 -- ==> ...(case x of I# x# -> case fw x# of ...)...
744 -- and now the redex (f x) isn't floatable any more
745 -- Similarly, don't apply any rules until after full
746 -- laziness. Notably, list fusion can prevent floating.
748 NoCaseOfCase, -- Don't do case-of-case transformations.
749 -- This makes full laziness work better
750 MaxSimplifierIterations max_iter
754 -- We run vectorisation here for now, but we might also try to run
756 runWhen vectorisation (CoreDoPasses [
758 CoreDoSimplify SimplGently
760 MaxSimplifierIterations max_iter]]),
762 -- Specialisation is best done before full laziness
763 -- so that overloaded functions have all their dictionary lambdas manifest
766 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
770 CoreDoSimplify (SimplPhase 2) [
771 -- Want to run with inline phase 2 after the specialiser to give
772 -- maximum chance for fusion to work before we inline build/augment
773 -- in phase 1. This made a difference in 'ansi' where an
774 -- overloaded function wasn't inlined till too late.
775 MaxSimplifierIterations max_iter
777 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
779 CoreDoSimplify (SimplPhase 1) [
780 -- Need inline-phase2 here so that build/augment get
781 -- inlined. I found that spectral/hartel/genfft lost some useful
782 -- strictness in the function sumcode' if augment is not inlined
783 -- before strictness analysis runs
784 MaxSimplifierIterations max_iter
786 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
788 CoreDoSimplify (SimplPhase 0) [
789 -- Phase 0: allow all Ids to be inlined now
790 -- This gets foldr inlined before strictness analysis
792 MaxSimplifierIterations 3
793 -- At least 3 iterations because otherwise we land up with
794 -- huge dead expressions because of an infelicity in the
796 -- let k = BIG in foldr k z xs
797 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
798 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
802 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
804 #ifdef OLD_STRICTNESS
807 runWhen strictness (CoreDoPasses [
811 CoreDoSimplify (SimplPhase 0) [
812 MaxSimplifierIterations max_iter
815 runWhen full_laziness
816 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
817 True)), -- Float constants
818 -- nofib/spectral/hartel/wang doubles in speed if you
819 -- do full laziness late in the day. It only happens
820 -- after fusion and other stuff, so the early pass doesn't
821 -- catch it. For the record, the redex is
822 -- f_el22 (f_el21 r_midblock)
826 -- We want CSE to follow the final full-laziness pass, because it may
827 -- succeed in commoning up things floated out by full laziness.
828 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
832 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
834 -- Case-liberation for -O2. This should be after
835 -- strictness analysis and the simplification which follows it.
836 runWhen liberate_case (CoreDoPasses [
838 CoreDoSimplify (SimplPhase 0) [
839 MaxSimplifierIterations max_iter
840 ] ]), -- Run the simplifier after LiberateCase to vastly
841 -- reduce the possiblility of shadowing
842 -- Reason: see Note [Shadowing] in SpecConstr.lhs
844 runWhen spec_constr CoreDoSpecConstr,
846 -- Final clean-up simplification:
847 CoreDoSimplify (SimplPhase 0) [
848 MaxSimplifierIterations max_iter
852 -- -----------------------------------------------------------------------------
853 -- StgToDo: abstraction of stg-to-stg passes to run.
856 = StgDoMassageForProfiling -- should be (next to) last
857 -- There's also setStgVarInfo, but its absolute "lastness"
858 -- is so critical that it is hardwired in (no flag).
861 getStgToDo :: DynFlags -> [StgToDo]
863 | Just todo <- stgToDo dflags = todo -- set explicitly by user
866 stg_stats = dopt Opt_StgStats dflags
868 todo1 = if stg_stats then [D_stg_stats] else []
870 todo2 | WayProf `elem` wayNames dflags
871 = StgDoMassageForProfiling : todo1
875 -- -----------------------------------------------------------------------------
879 allFlags = map ('-':) $
880 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
881 map ("fno-"++) flags ++
883 where ok (PrefixPred _ _) = False
885 flags = map fst fFlags
887 dynamic_flags :: [(String, OptKind DynP)]
889 ( "n" , NoArg (setDynFlag Opt_DryRun) )
890 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
891 , ( "F" , NoArg (setDynFlag Opt_Pp))
892 , ( "#include" , HasArg (addCmdlineHCInclude) )
893 , ( "v" , OptIntSuffix setVerbosity )
895 ------- Specific phases --------------------------------------------
896 , ( "pgmL" , HasArg (upd . setPgmL) )
897 , ( "pgmP" , HasArg (upd . setPgmP) )
898 , ( "pgmF" , HasArg (upd . setPgmF) )
899 , ( "pgmc" , HasArg (upd . setPgmc) )
900 , ( "pgmm" , HasArg (upd . setPgmm) )
901 , ( "pgms" , HasArg (upd . setPgms) )
902 , ( "pgma" , HasArg (upd . setPgma) )
903 , ( "pgml" , HasArg (upd . setPgml) )
904 , ( "pgmdll" , HasArg (upd . setPgmdll) )
906 , ( "optL" , HasArg (upd . addOptL) )
907 , ( "optP" , HasArg (upd . addOptP) )
908 , ( "optF" , HasArg (upd . addOptF) )
909 , ( "optc" , HasArg (upd . addOptc) )
910 , ( "optm" , HasArg (upd . addOptm) )
911 , ( "opta" , HasArg (upd . addOpta) )
912 , ( "optl" , HasArg (upd . addOptl) )
913 , ( "optdll" , HasArg (upd . addOptdll) )
914 , ( "optdep" , HasArg (upd . addOptdep) )
916 , ( "split-objs" , NoArg (if can_split
917 then setDynFlag Opt_SplitObjs
920 -------- Linking ----------------------------------------------------
921 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
922 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
923 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
925 ------- Libraries ---------------------------------------------------
926 , ( "L" , Prefix addLibraryPath )
927 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
930 ------- Frameworks --------------------------------------------------
931 -- -framework-path should really be -F ...
932 , ( "framework-path" , HasArg addFrameworkPath )
933 , ( "framework" , HasArg (upd . addCmdlineFramework) )
935 ------- Output Redirection ------------------------------------------
936 , ( "odir" , HasArg (upd . setObjectDir . Just))
937 , ( "o" , SepArg (upd . setOutputFile . Just))
938 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
939 , ( "osuf" , HasArg (upd . setObjectSuf))
940 , ( "hcsuf" , HasArg (upd . setHcSuf))
941 , ( "hisuf" , HasArg (upd . setHiSuf))
942 , ( "hidir" , HasArg (upd . setHiDir . Just))
943 , ( "tmpdir" , HasArg (upd . setTmpDir))
944 , ( "stubdir" , HasArg (upd . setStubDir . Just))
946 ------- Keeping temporary files -------------------------------------
947 -- These can be singular (think ghc -c) or plural (think ghc --make)
948 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
949 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
950 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
951 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
952 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
953 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
954 -- This only makes sense as plural
955 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
957 ------- Miscellaneous ----------------------------------------------
958 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
959 , ( "main-is" , SepArg setMainIs )
960 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
961 , ( "hpcdir" , SepArg setOptHpcDir )
963 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
964 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
965 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
967 ------- Packages ----------------------------------------------------
968 , ( "package-conf" , HasArg extraPkgConf_ )
969 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
970 , ( "package-name" , HasArg (upd . setPackageName) )
971 , ( "package" , HasArg exposePackage )
972 , ( "hide-package" , HasArg hidePackage )
973 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
974 , ( "ignore-package" , HasArg ignorePackage )
975 , ( "syslib" , HasArg exposePackage ) -- for compatibility
977 ------ HsCpp opts ---------------------------------------------------
978 , ( "D", AnySuffix (upd . addOptP) )
979 , ( "U", AnySuffix (upd . addOptP) )
981 ------- Include/Import Paths ----------------------------------------
982 , ( "I" , Prefix addIncludePath)
983 , ( "i" , OptPrefix addImportPath )
985 ------ Debugging ----------------------------------------------------
986 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
988 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
989 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
990 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
991 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
992 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
993 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
994 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
995 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
996 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
997 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
998 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
999 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
1000 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
1001 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
1002 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
1003 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
1004 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
1005 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
1006 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
1007 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
1008 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
1009 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
1010 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
1011 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
1012 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
1013 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
1014 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
1015 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
1016 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
1017 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
1018 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
1019 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
1020 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
1021 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
1022 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
1023 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
1024 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
1025 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
1026 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
1027 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
1029 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
1030 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
1031 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
1032 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1033 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1034 setVerbosity (Just 2)) )
1035 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1037 ------ Machine dependant (-m<blah>) stuff ---------------------------
1039 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1040 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1041 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1043 ------ Warning opts -------------------------------------------------
1044 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1045 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1046 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1047 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1048 , ( "w" , NoArg (mapM_ unSetDynFlag minuswRemovesOpts) )
1050 ------ Optimisation flags ------------------------------------------
1051 , ( "O" , NoArg (upd (setOptLevel 1)))
1052 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1053 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1054 -- If the number is missing, use 1
1056 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1057 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1059 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1060 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1061 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1063 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1064 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1066 ------ Compiler flags -----------------------------------------------
1068 , ( "fasm", NoArg (setObjTarget HscAsm) )
1069 , ( "fvia-c", NoArg (setObjTarget HscC) )
1070 , ( "fvia-C", NoArg (setObjTarget HscC) )
1072 , ( "fno-code", NoArg (setTarget HscNothing))
1073 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1074 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1076 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1077 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1079 -- the rest of the -f* and -fno-* flags
1080 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1081 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1083 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1084 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1085 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1087 -- the rest of the -X* and -Xno-* flags
1088 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1089 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1092 -- these -f<blah> flags can all be reversed with -fno-<blah>
1095 ( "warn-dodgy-imports", Opt_WarnDodgyImports ),
1096 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1097 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1098 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1099 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1100 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1101 ( "warn-missing-fields", Opt_WarnMissingFields ),
1102 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1103 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1104 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1105 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1106 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1107 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1108 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1109 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1110 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1111 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1112 ( "warn-deprecations", Opt_WarnDeprecations ),
1113 ( "warn-orphans", Opt_WarnOrphans ),
1114 ( "warn-tabs", Opt_WarnTabs ),
1115 ( "print-explicit-foralls", Opt_PrintExplicitForalls ),
1116 ( "strictness", Opt_Strictness ),
1117 ( "full-laziness", Opt_FullLaziness ),
1118 ( "liberate-case", Opt_LiberateCase ),
1119 ( "spec-constr", Opt_SpecConstr ),
1121 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1122 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1123 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1124 ( "ignore-asserts", Opt_IgnoreAsserts ),
1125 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1126 ( "do-eta-reduction", Opt_DoEtaReduction ),
1127 ( "case-merge", Opt_CaseMerge ),
1128 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1129 ( "dicts-cheap", Opt_DictsCheap ),
1130 ( "excess-precision", Opt_ExcessPrecision ),
1131 ( "asm-mangling", Opt_DoAsmMangling ),
1132 ( "print-bind-result", Opt_PrintBindResult ),
1133 ( "force-recomp", Opt_ForceRecomp ),
1134 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1135 ( "rewrite-rules", Opt_RewriteRules ),
1136 ( "break-on-exception", Opt_BreakOnException ),
1137 ( "vectorise", Opt_Vectorise )
1141 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1142 xFlags :: [(String, DynFlag)]
1145 ( "PatternGuards", Opt_PatternGuards ),
1146 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1147 ( "MagicHash", Opt_MagicHash ),
1148 ( "PolymorphicComponents", Opt_PolymorphicComponents ),
1149 ( "ExistentialQuantification", Opt_ExistentialQuantification ),
1150 ( "KindSignatures", Opt_KindSignatures ),
1151 ( "PatternSignatures", Opt_PatternSignatures ),
1152 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1153 ( "ParallelListComp", Opt_ParallelListComp ),
1154 ( "FI", Opt_FFI ), -- support `-ffi'...
1155 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1156 ( "ForeignFunctionInterface", Opt_FFI ),
1157 ( "UnliftedFFITypes", Opt_UnliftedFFITypes ),
1159 ( "PartiallyAppliedClosedTypeSynonyms", Opt_PartiallyAppliedClosedTypeSynonyms ),
1160 ( "Rank2Types", Opt_Rank2Types ),
1161 ( "RankNTypes", Opt_RankNTypes ),
1162 ( "TypeOperators", Opt_TypeOperators ),
1163 ( "RecursiveDo", Opt_RecursiveDo ),
1164 ( "Arrows", Opt_Arrows ), -- arrow syntax
1165 ( "Parr", Opt_PArr ),
1167 ( "TH", Opt_TH ), -- support -fth
1168 ( "TemplateHaskelll", Opt_TH ),
1170 ( "Generics", Opt_Generics ),
1172 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1174 ( "RecordWildCards", Opt_RecordWildCards ),
1175 ( "RecordPuns", Opt_RecordPuns ),
1176 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1178 ( "OverloadedStrings", Opt_OverloadedStrings ),
1179 ( "GADTs", Opt_GADTs ),
1180 ( "TypeFamilies", Opt_TypeFamilies ),
1181 ( "BangPatterns", Opt_BangPatterns ),
1182 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1183 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1184 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1185 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1186 ( "ImplicitParams", Opt_ImplicitParams ),
1187 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1188 ( "UnboxedTuples", Opt_UnboxedTuples ),
1189 ( "StandaloneDeriving", Opt_StandaloneDeriving ),
1190 ( "DeriveDataTypeable", Opt_DeriveDataTypeable ),
1191 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1192 ( "FlexibleContexts", Opt_FlexibleContexts ),
1193 ( "FlexibleInstances", Opt_FlexibleInstances ),
1194 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods ),
1195 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1196 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1197 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1198 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1199 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1200 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1203 impliedFlags :: [(DynFlag, [DynFlag])]
1205 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1208 glasgowExtsFlags = [
1209 Opt_PrintExplicitForalls
1211 , Opt_UnliftedFFITypes
1213 , Opt_ImplicitParams
1214 , Opt_ScopedTypeVariables
1216 , Opt_TypeSynonymInstances
1217 , Opt_StandaloneDeriving
1218 , Opt_DeriveDataTypeable
1219 , Opt_FlexibleContexts
1220 , Opt_FlexibleInstances
1221 , Opt_ConstrainedClassMethods
1222 , Opt_MultiParamTypeClasses
1223 , Opt_FunctionalDependencies
1225 , Opt_PolymorphicComponents
1226 , Opt_ExistentialQuantification
1229 , Opt_PartiallyAppliedClosedTypeSynonyms
1233 , Opt_ParallelListComp
1234 , Opt_EmptyDataDecls
1235 , Opt_KindSignatures
1236 , Opt_PatternSignatures
1237 , Opt_GeneralizedNewtypeDeriving
1238 , Opt_TypeFamilies ]
1241 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1243 isFlag flags f = is_flag flags (normaliseFlag f)
1246 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1249 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1250 -- nf is normalised alreadly
1253 getFlag, getNoFlag :: [(String,a)] -> String -> a
1255 getFlag flags f = get_flag flags (normaliseFlag f)
1257 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1258 -- The flag should be a no-flag already
1260 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1262 [] -> panic ("get_flag " ++ nf)
1265 noFlag_maybe :: String -> Maybe String
1266 -- The input is normalised already
1267 noFlag_maybe ('n' : 'o' : f) = Just f
1268 noFlag_maybe other = Nothing
1270 normaliseFlag :: String -> String
1271 -- Normalise a option flag by
1272 -- * map to lower case
1273 -- * removing hyphens
1274 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1275 normaliseFlag [] = []
1276 normaliseFlag ('-':s) = normaliseFlag s
1277 normaliseFlag (c:s) = toLower c : normaliseFlag s
1279 -- -----------------------------------------------------------------------------
1280 -- Parsing the dynamic flags.
1282 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1283 parseDynamicFlags dflags args = do
1284 let ((leftover,errs),dflags')
1285 = runCmdLine (processArgs dynamic_flags args) dflags
1286 when (not (null errs)) $ do
1287 throwDyn (UsageError (unlines errs))
1288 return (dflags', leftover)
1291 type DynP = CmdLineP DynFlags
1293 upd :: (DynFlags -> DynFlags) -> DynP ()
1295 dfs <- getCmdLineState
1296 putCmdLineState $! (f dfs)
1298 --------------------------
1299 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1300 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1302 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1303 -- When you set f, set the ones it implies
1304 -- When you un-set f, however, we don't un-set the things it implies
1305 -- (except for -fno-glasgow-exts, which is treated specially)
1307 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1309 --------------------------
1310 setDumpFlag :: DynFlag -> OptKind DynP
1311 setDumpFlag dump_flag
1312 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1313 -- Whenver we -ddump, switch off the recompilation checker,
1314 -- else you don't see the dump!
1316 setVerbosity :: Maybe Int -> DynP ()
1317 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1319 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1321 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1324 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1326 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1328 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1331 | Nothing <- unpackPackageId pid
1332 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1334 = \s -> s{ thisPackage = pid }
1336 pid = stringToPackageId p
1338 -- If we're linking a binary, then only targets that produce object
1339 -- code are allowed (requests for other target types are ignored).
1340 setTarget l = upd set
1343 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1346 -- Changes the target only if we're compiling object code. This is
1347 -- used by -fasm and -fvia-C, which switch from one to the other, but
1348 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1349 -- can be safely used in an OPTIONS_GHC pragma.
1350 setObjTarget l = upd set
1353 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1356 setOptLevel :: Int -> DynFlags -> DynFlags
1357 setOptLevel n dflags
1358 | hscTarget dflags == HscInterpreted && n > 0
1360 -- not in IO any more, oh well:
1361 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1363 = updOptLevel n dflags
1366 setMainIs :: String -> DynP ()
1368 | not (null main_fn) -- The arg looked like "Foo.baz"
1369 = upd $ \d -> d{ mainFunIs = Just main_fn,
1370 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1372 | isUpper (head main_mod) -- The arg looked like "Foo"
1373 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1375 | otherwise -- The arg looked like "baz"
1376 = upd $ \d -> d{ mainFunIs = Just main_mod }
1378 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1380 -----------------------------------------------------------------------------
1381 -- Paths & Libraries
1383 -- -i on its own deletes the import paths
1384 addImportPath "" = upd (\s -> s{importPaths = []})
1385 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1389 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1392 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1394 addFrameworkPath p =
1395 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1397 split_marker = ':' -- not configurable (ToDo)
1399 splitPathList :: String -> [String]
1400 splitPathList s = filter notNull (splitUp s)
1401 -- empty paths are ignored: there might be a trailing
1402 -- ':' in the initial list, for example. Empty paths can
1403 -- cause confusion when they are translated into -I options
1404 -- for passing to gcc.
1406 #ifndef mingw32_TARGET_OS
1407 splitUp xs = split split_marker xs
1409 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1411 -- That is, if "foo:bar:baz" is used, this interpreted as
1412 -- consisting of three entries, 'foo', 'bar', 'baz'.
1413 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1414 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1416 -- Notice that no attempt is made to fully replace the 'standard'
1417 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1418 -- that this will cause too much breakage for users & ':' will
1419 -- work fine even with DOS paths, if you're not insisting on being silly.
1422 splitUp (x:':':div:xs) | div `elem` dir_markers
1423 = ((x:':':div:p): splitUp rs)
1425 (p,rs) = findNextPath xs
1426 -- we used to check for existence of the path here, but that
1427 -- required the IO monad to be threaded through the command-line
1428 -- parser which is quite inconvenient. The
1429 splitUp xs = cons p (splitUp rs)
1431 (p,rs) = findNextPath xs
1436 -- will be called either when we've consumed nought or the
1437 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1438 -- finding the next split marker.
1440 case break (`elem` split_markers) xs of
1441 (p, d:ds) -> (p, ds)
1444 split_markers :: [Char]
1445 split_markers = [':', ';']
1447 dir_markers :: [Char]
1448 dir_markers = ['/', '\\']
1451 -- -----------------------------------------------------------------------------
1452 -- tmpDir, where we store temporary files.
1454 setTmpDir :: FilePath -> DynFlags -> DynFlags
1455 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1457 #if !defined(mingw32_HOST_OS)
1458 canonicalise p = normalisePath p
1460 -- Canonicalisation of temp path under win32 is a bit more
1461 -- involved: (a) strip trailing slash,
1462 -- (b) normalise slashes
1463 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1465 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1467 -- if we're operating under cygwin, and TMP/TEMP is of
1468 -- the form "/cygdrive/drive/path", translate this to
1469 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1470 -- understand /cygdrive paths.)
1472 | "/cygdrive/" `isPrefixOf` path =
1473 case drop (length "/cygdrive/") path of
1474 drive:xs@('/':_) -> drive:':':xs
1478 -- strip the trailing backslash (awful, but we only do this once).
1479 removeTrailingSlash path =
1486 -----------------------------------------------------------------------------
1489 setOptHpcDir :: String -> DynP ()
1490 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1492 -----------------------------------------------------------------------------
1493 -- Via-C compilation stuff
1495 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1496 [String]) -- for registerised HC compilations
1497 machdepCCOpts dflags
1498 #if alpha_TARGET_ARCH
1500 #ifdef HAVE_THREADED_RTS_SUPPORT
1504 -- For now, to suppress the gcc warning "call-clobbered
1505 -- register used for global register variable", we simply
1506 -- disable all warnings altogether using the -w flag. Oh well.
1508 #elif hppa_TARGET_ARCH
1509 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1510 -- (very nice, but too bad the HP /usr/include files don't agree.)
1511 = ( ["-D_HPUX_SOURCE"], [] )
1513 #elif m68k_TARGET_ARCH
1514 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1515 -- popping of args to routines to be explicit; if we let things
1516 -- be deferred 'til after an STGJUMP, imminent death is certain!
1518 -- -fomit-frame-pointer : *don't*
1519 -- It's better to have a6 completely tied up being a frame pointer
1520 -- rather than let GCC pick random things to do with it.
1521 -- (If we want to steal a6, then we would try to do things
1522 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1523 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1525 #elif i386_TARGET_ARCH
1526 -- -fno-defer-pop : basically the same game as for m68k
1528 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1529 -- the fp (%ebp) for our register maps.
1530 = let n_regs = stolen_x86_regs dflags
1533 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1534 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1537 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1538 -- Some gccs are configured with
1539 -- -momit-leaf-frame-pointer on by default, and it
1540 -- apparently takes precedence over
1541 -- -fomit-frame-pointer, so we disable it first here.
1542 "-mno-omit-leaf-frame-pointer",
1544 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1545 "-fno-unit-at-a-time",
1546 -- unit-at-a-time doesn't do us any good, and screws
1547 -- up -split-objs by moving the split markers around.
1548 -- It's only turned on with -O2, but put it here just
1549 -- in case someone uses -optc-O2.
1551 "-fomit-frame-pointer",
1552 -- we want -fno-builtin, because when gcc inlines
1553 -- built-in functions like memcpy() it tends to
1554 -- run out of registers, requiring -monly-n-regs
1556 "-DSTOLEN_X86_REGS="++show n_regs ]
1559 #elif ia64_TARGET_ARCH
1560 = ( [], ["-fomit-frame-pointer", "-G0"] )
1562 #elif x86_64_TARGET_ARCH
1563 = ( [], ["-fomit-frame-pointer",
1564 "-fno-asynchronous-unwind-tables",
1565 -- the unwind tables are unnecessary for HC code,
1566 -- and get in the way of -split-objs. Another option
1567 -- would be to throw them away in the mangler, but this
1569 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1570 "-fno-unit-at-a-time",
1571 -- unit-at-a-time doesn't do us any good, and screws
1572 -- up -split-objs by moving the split markers around.
1573 -- It's only turned on with -O2, but put it here just
1574 -- in case someone uses -optc-O2.
1577 -- calling builtins like strlen() using the FFI can
1578 -- cause gcc to run out of regs, so use the external
1582 #elif sparc_TARGET_ARCH
1584 -- For now, to suppress the gcc warning "call-clobbered
1585 -- register used for global register variable", we simply
1586 -- disable all warnings altogether using the -w flag. Oh well.
1588 #elif powerpc_apple_darwin_TARGET
1590 -- Disable Apple's precompiling preprocessor. It's a great thing
1591 -- for "normal" programs, but it doesn't support register variable
1593 = ( [], ["-no-cpp-precomp"] )
1598 picCCOpts :: DynFlags -> [String]
1600 #if darwin_TARGET_OS
1601 -- Apple prefers to do things the other way round.
1602 -- PIC is on by default.
1603 -- -mdynamic-no-pic:
1604 -- Turn off PIC code generation.
1606 -- Don't generate "common" symbols - these are unwanted
1607 -- in dynamic libraries.
1612 = ["-mdynamic-no-pic"]
1613 #elif mingw32_TARGET_OS
1614 -- no -fPIC for Windows
1623 -- -----------------------------------------------------------------------------
1628 #if defined(i386_TARGET_ARCH) \
1629 || defined(x86_64_TARGET_ARCH) \
1630 || defined(alpha_TARGET_ARCH) \
1631 || defined(hppa_TARGET_ARCH) \
1632 || defined(m68k_TARGET_ARCH) \
1633 || defined(mips_TARGET_ARCH) \
1634 || defined(powerpc_TARGET_ARCH) \
1635 || defined(rs6000_TARGET_ARCH) \
1636 || defined(sparc_TARGET_ARCH)