1 {-# OPTIONS -fno-warn-missing-fields #-}
2 -----------------------------------------------------------------------------
6 -- Most flags are dynamic flags, which means they can change from
7 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
8 -- multi-session GHC each session can be using different dynamic
9 -- flags. Dynamic flags can also be set at the prompt in GHCi.
11 -- (c) The University of Glasgow 2005
13 -----------------------------------------------------------------------------
20 GhcMode(..), isOneShot,
21 GhcLink(..), isNoLink,
25 -- Configuration of the core-to-core and stg-to-stg phases
29 SimplifierMode(..), FloatOutSwitches(..),
30 getCoreToDo, getStgToDo,
32 -- Manipulating DynFlags
33 defaultDynFlags, -- DynFlags
34 initDynFlags, -- DynFlags -> IO DynFlags
36 dopt, -- DynFlag -> DynFlags -> Bool
37 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
38 getOpts, -- (DynFlags -> [a]) -> IO [a]
49 machdepCCOpts, picCCOpts
52 #include "HsVersions.h"
54 import Module ( Module, mkModuleName, mkModule )
56 import PrelNames ( mAIN )
57 #ifdef i386_TARGET_ARCH
58 import StaticFlags ( opt_Static )
60 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
62 import {-# SOURCE #-} Packages (PackageState)
63 import DriverPhases ( Phase(..), phaseInputExt )
66 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
67 import Panic ( panic, GhcException(..) )
68 import UniqFM ( UniqFM )
69 import Util ( notNull, splitLongestPrefix, normalisePath )
70 import Maybes ( fromJust, orElse )
71 import SrcLoc ( SrcSpan )
73 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
75 import Data.IORef ( readIORef )
76 import Control.Exception ( throwDyn )
77 import Control.Monad ( when )
78 #ifdef mingw32_TARGET_OS
79 import Data.List ( isPrefixOf )
84 import Data.Char ( isDigit, isUpper )
85 import System.IO ( hPutStrLn, stderr )
87 -- -----------------------------------------------------------------------------
100 | Opt_D_dump_inlinings
101 | Opt_D_dump_occur_anal
105 | Opt_D_dump_simpl_iterations
114 | Opt_D_dump_worker_wrapper
115 | Opt_D_dump_rn_trace
116 | Opt_D_dump_rn_stats
118 | Opt_D_dump_simpl_stats
119 | Opt_D_dump_tc_trace
120 | Opt_D_dump_if_trace
126 | Opt_D_verbose_core2core
127 | Opt_D_verbose_stg2stg
129 | Opt_D_dump_hi_diffs
130 | Opt_D_dump_minimal_imports
131 | Opt_D_faststring_stats
136 | Opt_WarnIsError -- -Werror; makes warnings fatal
137 | Opt_WarnDuplicateExports
139 | Opt_WarnIncompletePatterns
140 | Opt_WarnIncompletePatternsRecUpd
141 | Opt_WarnMissingFields
142 | Opt_WarnMissingMethods
143 | Opt_WarnMissingSigs
144 | Opt_WarnNameShadowing
145 | Opt_WarnOverlappingPatterns
146 | Opt_WarnSimplePatterns
147 | Opt_WarnTypeDefaults
148 | Opt_WarnUnusedBinds
149 | Opt_WarnUnusedImports
150 | Opt_WarnUnusedMatches
151 | Opt_WarnDeprecations
152 | Opt_WarnDodgyImports
156 | Opt_AllowOverlappingInstances
157 | Opt_AllowUndecidableInstances
158 | Opt_AllowIncoherentInstances
159 | Opt_MonomorphismRestriction
161 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
164 | Opt_PArr -- Syntactic support for parallel arrays
165 | Opt_Arrows -- Arrow-notation syntax
169 | Opt_ImplicitPrelude
170 | Opt_ScopedTypeVariables
178 | Opt_IgnoreInterfacePragmas
179 | Opt_OmitInterfacePragmas
180 | Opt_DoLambdaEtaExpansion
182 | Opt_IgnoreBreakpoints
185 | Opt_UnboxStrictFields
194 | Opt_ExcessPrecision
195 | Opt_ReadUserPackageConf
199 | Opt_HideAllPackages
200 | Opt_PrintBindResult
214 data DynFlags = DynFlags {
217 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
218 stgToDo :: Maybe [StgToDo], -- similarly
219 hscTarget :: HscTarget,
220 hscOutName :: String, -- name of the output file
221 extCoreName :: String, -- name of the .core output file
222 verbosity :: Int, -- verbosity level
223 optLevel :: Int, -- optimisation level
224 maxSimplIterations :: Int, -- max simplifier iterations
225 ruleCheck :: Maybe String,
226 stolen_x86_regs :: Int,
227 cmdlineHcIncludes :: [String], -- -#includes
228 importPaths :: [FilePath],
230 mainFunIs :: Maybe String,
231 ctxtStkDepth :: Int, -- Typechecker context stack depth
233 thisPackage :: PackageId,
236 wayNames :: [WayName], -- way flags from the cmd line
237 buildTag :: String, -- the global "way" (eg. "p" for prof)
238 rtsBuildTag :: String, -- the RTS "way"
241 objectDir :: Maybe String,
242 hiDir :: Maybe String,
243 stubDir :: Maybe String,
249 outputFile :: Maybe String,
250 outputHi :: Maybe String,
252 includePaths :: [String],
253 libraryPaths :: [String],
254 frameworkPaths :: [String], -- used on darwin only
255 cmdlineFrameworks :: [String], -- ditto
256 tmpDir :: String, -- no trailing '/'
258 ghcUsagePath :: FilePath, -- Filled in by SysTools
259 ghciUsagePath :: FilePath, -- ditto
261 hpcDir :: String, -- ^ path to store the .mix files
263 -- options for particular phases
274 -- commands for particular phases
276 pgm_P :: (String,[Option]),
278 pgm_c :: (String,[Option]),
279 pgm_m :: (String,[Option]),
280 pgm_s :: (String,[Option]),
281 pgm_a :: (String,[Option]),
282 pgm_l :: (String,[Option]),
283 pgm_dll :: (String,[Option]),
285 pgm_sysman :: String,
288 extraPkgConfs :: [FilePath],
289 topDir :: FilePath, -- filled in by SysTools
290 systemPackageConfig :: FilePath, -- ditto
291 -- The -package-conf flags given on the command line, in the order
294 packageFlags :: [PackageFlag],
295 -- The -package and -hide-package flags from the command-line
298 -- NB. do not modify this field, it is calculated by
299 -- Packages.initPackages and Packages.updatePackages.
300 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
301 pkgState :: PackageState,
307 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
319 = BatchCompile -- | @ghc --make Main@
320 | Interactive -- | @ghc --interactive@
321 | OneShot -- | @ghc -c Foo.hs@
322 | JustTypecheck -- | Development environemnts, refactorer, etc.
326 isOneShot :: GhcMode -> Bool
327 isOneShot OneShot = True
328 isOneShot _other = False
330 data GhcLink -- What to do in the link step, if there is one
331 = -- Only relevant for modes
332 -- DoMake and StopBefore StopLn
333 NoLink -- Don't link at all
334 | StaticLink -- Ordinary linker [the default]
335 | MkDLL -- Make a DLL
337 isNoLink :: GhcLink -> Bool
338 isNoLink NoLink = True
339 isNoLink other = False
342 = ExposePackage String
344 | IgnorePackage String
348 | cGhcWithNativeCodeGen == "YES" = HscAsm
351 initDynFlags dflags = do
352 -- someday these will be dynamic flags
353 ways <- readIORef v_Ways
354 build_tag <- readIORef v_Build_tag
355 rts_build_tag <- readIORef v_RTS_Build_tag
358 buildTag = build_tag,
359 rtsBuildTag = rts_build_tag
365 ghcLink = StaticLink,
368 hscTarget = defaultHscTarget,
373 maxSimplIterations = 4,
376 cmdlineHcIncludes = [],
380 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
382 thisPackage = mainPackageId,
388 objectSuf = phaseInputExt StopLn,
389 hcSuf = phaseInputExt HCc,
392 outputFile = Nothing,
397 cmdlineFrameworks = [],
398 tmpDir = cDEFAULT_TMPDIR,
414 pkgDatabase = Nothing,
415 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
418 Opt_ReadUserPackageConf,
420 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
421 -- behaviour the default, to see if anyone notices
425 Opt_MonomorphismRestriction,
427 -- strictness is on by default, but this only
429 Opt_CSE, -- similarly for CSE.
430 Opt_FullLaziness, -- ...and for full laziness
432 Opt_DoLambdaEtaExpansion,
433 -- This one is important for a tiresome reason:
434 -- we want to make sure that the bindings for data
435 -- constructors are eta-expanded. This is probably
436 -- a good thing anyway, but it seems fragile.
440 -- and the default no-optimisation options:
441 Opt_IgnoreInterfacePragmas,
442 Opt_OmitInterfacePragmas,
446 ] ++ standardWarnings,
448 log_action = \severity srcSpan style msg ->
450 SevInfo -> hPutStrLn stderr (show (msg style))
451 SevFatal -> hPutStrLn stderr (show (msg style))
452 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
458 0 | print errors & warnings only
459 1 | minimal verbosity: print "compiling M ... done." for each module.
460 2 | equivalent to -dshow-passes
461 3 | equivalent to existing "ghc -v"
462 4 | "ghc -v -ddump-most"
463 5 | "ghc -v -ddump-all"
466 dopt :: DynFlag -> DynFlags -> Bool
467 dopt f dflags = f `elem` (flags dflags)
469 dopt_set :: DynFlags -> DynFlag -> DynFlags
470 dopt_set dfs f = dfs{ flags = f : flags dfs }
472 dopt_unset :: DynFlags -> DynFlag -> DynFlags
473 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
475 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
476 getOpts dflags opts = reverse (opts dflags)
477 -- We add to the options from the front, so we need to reverse the list
479 getVerbFlag :: DynFlags -> String
481 | verbosity dflags >= 3 = "-v"
484 setObjectDir f d = d{ objectDir = f}
485 setHiDir f d = d{ hiDir = f}
486 setStubDir f d = d{ stubDir = f}
488 setObjectSuf f d = d{ objectSuf = f}
489 setHiSuf f d = d{ hiSuf = f}
490 setHcSuf f d = d{ hcSuf = f}
492 setOutputFile f d = d{ outputFile = f}
493 setOutputHi f d = d{ outputHi = f}
495 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
496 -- Config.hs should really use Option.
497 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
499 setPgmL f d = d{ pgm_L = f}
500 setPgmF f d = d{ pgm_F = f}
501 setPgmc f d = d{ pgm_c = (f,[])}
502 setPgmm f d = d{ pgm_m = (f,[])}
503 setPgms f d = d{ pgm_s = (f,[])}
504 setPgma f d = d{ pgm_a = (f,[])}
505 setPgml f d = d{ pgm_l = (f,[])}
506 setPgmdll f d = d{ pgm_dll = (f,[])}
508 addOptL f d = d{ opt_L = f : opt_L d}
509 addOptP f d = d{ opt_P = f : opt_P d}
510 addOptF f d = d{ opt_F = f : opt_F d}
511 addOptc f d = d{ opt_c = f : opt_c d}
512 addOptm f d = d{ opt_m = f : opt_m d}
513 addOpta f d = d{ opt_a = f : opt_a d}
514 addOptl f d = d{ opt_l = f : opt_l d}
515 addOptdll f d = d{ opt_dll = f : opt_dll d}
516 addOptdep f d = d{ opt_dep = f : opt_dep d}
518 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
520 -- -----------------------------------------------------------------------------
521 -- Command-line options
523 -- When invoking external tools as part of the compilation pipeline, we
524 -- pass these a sequence of options on the command-line. Rather than
525 -- just using a list of Strings, we use a type that allows us to distinguish
526 -- between filepaths and 'other stuff'. [The reason being, of course, that
527 -- this type gives us a handle on transforming filenames, and filenames only,
528 -- to whatever format they're expected to be on a particular platform.]
531 = FileOption -- an entry that _contains_ filename(s) / filepaths.
532 String -- a non-filepath prefix that shouldn't be
533 -- transformed (e.g., "/out=")
534 String -- the filepath/filename portion
537 -----------------------------------------------------------------------------
538 -- Setting the optimisation level
540 updOptLevel :: Int -> DynFlags -> DynFlags
541 -- Set dynflags appropriate to the optimisation level
543 = dfs2{ optLevel = n }
545 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
546 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
549 | n == 0 = opt_0_dopts
550 | otherwise = opt_1_dopts
553 | n == 0 = opt_1_dopts
554 | otherwise = opt_0_dopts
557 Opt_IgnoreInterfacePragmas,
558 Opt_OmitInterfacePragmas
567 -- -----------------------------------------------------------------------------
568 -- Standard sets of warning options
571 = [ Opt_WarnDeprecations,
572 Opt_WarnOverlappingPatterns,
573 Opt_WarnMissingFields,
574 Opt_WarnMissingMethods,
575 Opt_WarnDuplicateExports
579 = standardWarnings ++
580 [ Opt_WarnUnusedBinds,
581 Opt_WarnUnusedMatches,
582 Opt_WarnUnusedImports,
583 Opt_WarnIncompletePatterns,
589 [ Opt_WarnTypeDefaults,
590 Opt_WarnNameShadowing,
596 -- -----------------------------------------------------------------------------
597 -- CoreToDo: abstraction of core-to-core passes to run.
599 data CoreToDo -- These are diff core-to-core passes,
600 -- which may be invoked in any order,
601 -- as many times as you like.
603 = CoreDoSimplify -- The core-to-core simplifier.
606 -- Each run of the simplifier can take a different
607 -- set of simplifier-specific flags.
609 | CoreDoFloatOutwards FloatOutSwitches
614 | CoreDoWorkerWrapper
617 | CoreDoOldStrictness
620 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
621 -- matching this string
623 | CoreDoNothing -- useful when building up lists of these things
625 data SimplifierMode -- See comments in SimplMonad
629 data SimplifierSwitch
630 = MaxSimplifierIterations Int
633 data FloatOutSwitches
634 = FloatOutSw Bool -- True <=> float lambdas to top level
635 Bool -- True <=> float constants to top level,
636 -- even if they do not escape a lambda
639 -- The core-to-core pass ordering is derived from the DynFlags:
641 getCoreToDo :: DynFlags -> [CoreToDo]
643 | Just todo <- coreToDo dflags = todo -- set explicitly by user
644 | otherwise = core_todo
646 opt_level = optLevel dflags
647 max_iter = maxSimplIterations dflags
648 strictness = dopt Opt_Strictness dflags
649 full_laziness = dopt Opt_FullLaziness dflags
650 cse = dopt Opt_CSE dflags
651 rule_check = ruleCheck dflags
654 if opt_level == 0 then
656 CoreDoSimplify (SimplPhase 0) [
657 MaxSimplifierIterations max_iter
660 else {- opt_level >= 1 -} [
662 -- initial simplify: mk specialiser happy: minimum effort please
663 CoreDoSimplify SimplGently [
665 -- Don't inline anything till full laziness has bitten
666 -- In particular, inlining wrappers inhibits floating
667 -- e.g. ...(case f x of ...)...
668 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
669 -- ==> ...(case x of I# x# -> case fw x# of ...)...
670 -- and now the redex (f x) isn't floatable any more
671 -- Similarly, don't apply any rules until after full
672 -- laziness. Notably, list fusion can prevent floating.
674 NoCaseOfCase, -- Don't do case-of-case transformations.
675 -- This makes full laziness work better
676 MaxSimplifierIterations max_iter
679 -- Specialisation is best done before full laziness
680 -- so that overloaded functions have all their dictionary lambdas manifest
683 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
688 CoreDoSimplify (SimplPhase 2) [
689 -- Want to run with inline phase 2 after the specialiser to give
690 -- maximum chance for fusion to work before we inline build/augment
691 -- in phase 1. This made a difference in 'ansi' where an
692 -- overloaded function wasn't inlined till too late.
693 MaxSimplifierIterations max_iter
695 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
697 CoreDoSimplify (SimplPhase 1) [
698 -- Need inline-phase2 here so that build/augment get
699 -- inlined. I found that spectral/hartel/genfft lost some useful
700 -- strictness in the function sumcode' if augment is not inlined
701 -- before strictness analysis runs
702 MaxSimplifierIterations max_iter
704 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
706 CoreDoSimplify (SimplPhase 0) [
707 -- Phase 0: allow all Ids to be inlined now
708 -- This gets foldr inlined before strictness analysis
710 MaxSimplifierIterations 3
711 -- At least 3 iterations because otherwise we land up with
712 -- huge dead expressions because of an infelicity in the
714 -- let k = BIG in foldr k z xs
715 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
716 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
720 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
722 #ifdef OLD_STRICTNESS
725 if strictness then CoreDoStrictness else CoreDoNothing,
729 CoreDoSimplify (SimplPhase 0) [
730 MaxSimplifierIterations max_iter
733 if full_laziness then
734 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
735 True) -- Float constants
737 -- nofib/spectral/hartel/wang doubles in speed if you
738 -- do full laziness late in the day. It only happens
739 -- after fusion and other stuff, so the early pass doesn't
740 -- catch it. For the record, the redex is
741 -- f_el22 (f_el21 r_midblock)
744 -- We want CSE to follow the final full-laziness pass, because it may
745 -- succeed in commoning up things floated out by full laziness.
746 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
748 if cse then CoreCSE else CoreDoNothing,
752 -- Case-liberation for -O2. This should be after
753 -- strictness analysis and the simplification which follows it.
755 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
760 (if opt_level >= 2 then
762 CoreDoSimplify (SimplPhase 0) [
763 MaxSimplifierIterations max_iter
764 ], -- Run the simplifier after LiberateCase to vastly
765 -- reduce the possiblility of shadowing
766 -- Reason: see Note [Shadowing] in SpecConstr.lhs
774 -- Final clean-up simplification:
775 [ CoreDoSimplify (SimplPhase 0) [
776 MaxSimplifierIterations max_iter
780 -- -----------------------------------------------------------------------------
781 -- StgToDo: abstraction of stg-to-stg passes to run.
784 = StgDoMassageForProfiling -- should be (next to) last
785 -- There's also setStgVarInfo, but its absolute "lastness"
786 -- is so critical that it is hardwired in (no flag).
789 getStgToDo :: DynFlags -> [StgToDo]
791 | Just todo <- stgToDo dflags = todo -- set explicitly by user
794 stg_stats = dopt Opt_StgStats dflags
796 todo1 = if stg_stats then [D_stg_stats] else []
798 todo2 | WayProf `elem` wayNames dflags
799 = StgDoMassageForProfiling : todo1
803 -- -----------------------------------------------------------------------------
807 allFlags = map ('-':) $
808 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
809 map ("fno-"++) flags ++
811 where ok (PrefixPred _ _) = False
813 flags = map fst fFlags
815 dynamic_flags :: [(String, OptKind DynP)]
817 ( "n" , NoArg (setDynFlag Opt_DryRun) )
818 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
819 , ( "F" , NoArg (setDynFlag Opt_Pp))
820 , ( "#include" , HasArg (addCmdlineHCInclude) )
821 , ( "v" , OptIntSuffix setVerbosity )
822 ------- Specific phases --------------------------------------------
823 , ( "pgmL" , HasArg (upd . setPgmL) )
824 , ( "pgmP" , HasArg (upd . setPgmP) )
825 , ( "pgmF" , HasArg (upd . setPgmF) )
826 , ( "pgmc" , HasArg (upd . setPgmc) )
827 , ( "pgmm" , HasArg (upd . setPgmm) )
828 , ( "pgms" , HasArg (upd . setPgms) )
829 , ( "pgma" , HasArg (upd . setPgma) )
830 , ( "pgml" , HasArg (upd . setPgml) )
831 , ( "pgmdll" , HasArg (upd . setPgmdll) )
833 , ( "optL" , HasArg (upd . addOptL) )
834 , ( "optP" , HasArg (upd . addOptP) )
835 , ( "optF" , HasArg (upd . addOptF) )
836 , ( "optc" , HasArg (upd . addOptc) )
837 , ( "optm" , HasArg (upd . addOptm) )
838 , ( "opta" , HasArg (upd . addOpta) )
839 , ( "optl" , HasArg (upd . addOptl) )
840 , ( "optdll" , HasArg (upd . addOptdll) )
841 , ( "optdep" , HasArg (upd . addOptdep) )
843 , ( "split-objs" , NoArg (if can_split
844 then setDynFlag Opt_SplitObjs
847 -------- Linking ----------------------------------------------------
848 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
849 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
850 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
852 ------- Libraries ---------------------------------------------------
853 , ( "L" , Prefix addLibraryPath )
854 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
857 ------- Frameworks --------------------------------------------------
858 -- -framework-path should really be -F ...
859 , ( "framework-path" , HasArg addFrameworkPath )
860 , ( "framework" , HasArg (upd . addCmdlineFramework) )
862 ------- Output Redirection ------------------------------------------
863 , ( "odir" , HasArg (upd . setObjectDir . Just))
864 , ( "o" , SepArg (upd . setOutputFile . Just))
865 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
866 , ( "osuf" , HasArg (upd . setObjectSuf))
867 , ( "hcsuf" , HasArg (upd . setHcSuf))
868 , ( "hisuf" , HasArg (upd . setHiSuf))
869 , ( "hidir" , HasArg (upd . setHiDir . Just))
870 , ( "tmpdir" , HasArg (upd . setTmpDir))
871 , ( "stubdir" , HasArg (upd . setStubDir . Just))
873 ------- Keeping temporary files -------------------------------------
874 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
875 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
876 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
877 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
879 ------- Miscellaneous ----------------------------------------------
880 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
881 , ( "main-is" , SepArg setMainIs )
882 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
883 , ( "hpcdir" , SepArg setOptHpcDir )
885 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
886 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
887 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
889 ------- Packages ----------------------------------------------------
890 , ( "package-conf" , HasArg extraPkgConf_ )
891 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
892 , ( "package-name" , HasArg (upd . setPackageName) )
893 , ( "package" , HasArg exposePackage )
894 , ( "hide-package" , HasArg hidePackage )
895 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
896 , ( "ignore-package" , HasArg ignorePackage )
897 , ( "syslib" , HasArg exposePackage ) -- for compatibility
899 ------ HsCpp opts ---------------------------------------------------
900 , ( "D", AnySuffix (upd . addOptP) )
901 , ( "U", AnySuffix (upd . addOptP) )
903 ------- Include/Import Paths ----------------------------------------
904 , ( "I" , Prefix addIncludePath)
905 , ( "i" , OptPrefix addImportPath )
907 ------ Debugging ----------------------------------------------------
908 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
910 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
911 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
912 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
913 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
914 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
915 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
916 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
917 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
918 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
919 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
920 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
921 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
922 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
923 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
924 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
925 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
926 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
927 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
928 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
929 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
930 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
931 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
932 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
933 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
934 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
935 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
936 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
937 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
938 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
939 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
940 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
941 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
942 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
943 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
944 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
945 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
946 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
947 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
949 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
950 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
951 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
952 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
953 setVerbosity (Just 2)) )
954 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
956 ------ Machine dependant (-m<blah>) stuff ---------------------------
958 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
959 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
960 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
962 ------ Warning opts -------------------------------------------------
963 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
964 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
965 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
966 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
967 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
969 ------ Optimisation flags ------------------------------------------
970 , ( "O" , NoArg (upd (setOptLevel 1)))
971 , ( "Onot" , NoArg (upd (setOptLevel 0)))
972 , ( "O" , PrefixPred (all isDigit)
973 (\f -> upd (setOptLevel (read f))))
975 , ( "fmax-simplifier-iterations",
976 PrefixPred (all isDigit)
978 dfs{ maxSimplIterations = read n })) )
981 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
983 ------ Compiler flags -----------------------------------------------
985 , ( "fno-code", NoArg (setTarget HscNothing))
986 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
987 , ( "fvia-c", NoArg (setTarget HscC) )
988 , ( "fvia-C", NoArg (setTarget HscC) )
990 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
991 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
993 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
994 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
996 -- the rest of the -f* and -fno-* flags
997 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
998 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
1001 -- these -f<blah> flags can all be reversed with -fno-<blah>
1004 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1005 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1006 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1007 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1008 ( "warn-missing-fields", Opt_WarnMissingFields ),
1009 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1010 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1011 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1012 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1013 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1014 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1015 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1016 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1017 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1018 ( "warn-deprecations", Opt_WarnDeprecations ),
1019 ( "warn-orphans", Opt_WarnOrphans ),
1020 ( "fi", Opt_FFI ), -- support `-ffi'...
1021 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1022 ( "arrows", Opt_Arrows ), -- arrow syntax
1023 ( "parr", Opt_PArr ),
1025 ( "implicit-prelude", Opt_ImplicitPrelude ),
1026 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1027 ( "bang-patterns", Opt_BangPatterns ),
1028 ( "indexed-types", Opt_IndexedTypes ),
1029 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1030 ( "mono-pat-binds", Opt_MonoPatBinds ),
1031 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1032 ( "implicit-params", Opt_ImplicitParams ),
1033 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1034 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1035 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1036 ( "generics", Opt_Generics ),
1037 ( "strictness", Opt_Strictness ),
1038 ( "full-laziness", Opt_FullLaziness ),
1040 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1041 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1042 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1043 ( "ignore-asserts", Opt_IgnoreAsserts ),
1044 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1045 ( "do-eta-reduction", Opt_DoEtaReduction ),
1046 ( "case-merge", Opt_CaseMerge ),
1047 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1048 ( "dicts-cheap", Opt_DictsCheap ),
1049 ( "excess-precision", Opt_ExcessPrecision ),
1050 ( "asm-mangling", Opt_DoAsmMangling ),
1051 ( "print-bind-result", Opt_PrintBindResult ),
1052 ( "force-recomp", Opt_ForceRecomp ),
1054 ( "hpc-tracer", Opt_Hpc_Tracer )
1058 glasgowExtsFlags = [
1062 Opt_ScopedTypeVariables,
1065 isFFlag f = f `elem` (map fst fFlags)
1066 getFFlag f = fromJust (lookup f fFlags)
1068 -- -----------------------------------------------------------------------------
1069 -- Parsing the dynamic flags.
1071 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1072 parseDynamicFlags dflags args = do
1073 let ((leftover,errs),dflags')
1074 = runCmdLine (processArgs dynamic_flags args) dflags
1075 when (not (null errs)) $ do
1076 throwDyn (UsageError (unlines errs))
1077 return (dflags', leftover)
1080 type DynP = CmdLineP DynFlags
1082 upd :: (DynFlags -> DynFlags) -> DynP ()
1084 dfs <- getCmdLineState
1085 putCmdLineState $! (f dfs)
1087 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1088 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1089 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1091 setDumpFlag :: DynFlag -> OptKind DynP
1092 setDumpFlag dump_flag
1093 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1094 -- Whenver we -ddump, switch off the recompilation checker,
1095 -- else you don't see the dump!
1097 setVerbosity :: Maybe Int -> DynP ()
1098 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1100 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1102 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1105 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1107 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1109 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1112 | Nothing <- unpackPackageId pid
1113 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1115 = \s -> s{ thisPackage = pid }
1117 pid = stringToPackageId p
1119 -- we can only switch between HscC, and HscAsmm with dynamic flags
1120 -- (-fvia-C, -fasm, -filx respectively).
1121 setTarget l = upd (\dfs -> case hscTarget dfs of
1122 HscC -> dfs{ hscTarget = l }
1123 HscAsm -> dfs{ hscTarget = l }
1126 setOptLevel :: Int -> DynFlags -> DynFlags
1127 setOptLevel n dflags
1128 | hscTarget dflags == HscInterpreted && n > 0
1130 -- not in IO any more, oh well:
1131 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1133 = updOptLevel n dflags
1136 setMainIs :: String -> DynP ()
1138 | not (null main_fn) -- The arg looked like "Foo.baz"
1139 = upd $ \d -> d{ mainFunIs = Just main_fn,
1140 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1142 | isUpper (head main_mod) -- The arg looked like "Foo"
1143 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1145 | otherwise -- The arg looked like "baz"
1146 = upd $ \d -> d{ mainFunIs = Just main_mod }
1148 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1150 -----------------------------------------------------------------------------
1151 -- Paths & Libraries
1153 -- -i on its own deletes the import paths
1154 addImportPath "" = upd (\s -> s{importPaths = []})
1155 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1159 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1162 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1164 addFrameworkPath p =
1165 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1167 split_marker = ':' -- not configurable (ToDo)
1169 splitPathList :: String -> [String]
1170 splitPathList s = filter notNull (splitUp s)
1171 -- empty paths are ignored: there might be a trailing
1172 -- ':' in the initial list, for example. Empty paths can
1173 -- cause confusion when they are translated into -I options
1174 -- for passing to gcc.
1176 #ifndef mingw32_TARGET_OS
1177 splitUp xs = split split_marker xs
1179 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1181 -- That is, if "foo:bar:baz" is used, this interpreted as
1182 -- consisting of three entries, 'foo', 'bar', 'baz'.
1183 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1184 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1186 -- Notice that no attempt is made to fully replace the 'standard'
1187 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1188 -- that this will cause too much breakage for users & ':' will
1189 -- work fine even with DOS paths, if you're not insisting on being silly.
1192 splitUp (x:':':div:xs) | div `elem` dir_markers
1193 = ((x:':':div:p): splitUp rs)
1195 (p,rs) = findNextPath xs
1196 -- we used to check for existence of the path here, but that
1197 -- required the IO monad to be threaded through the command-line
1198 -- parser which is quite inconvenient. The
1199 splitUp xs = cons p (splitUp rs)
1201 (p,rs) = findNextPath xs
1206 -- will be called either when we've consumed nought or the
1207 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1208 -- finding the next split marker.
1210 case break (`elem` split_markers) xs of
1211 (p, d:ds) -> (p, ds)
1214 split_markers :: [Char]
1215 split_markers = [':', ';']
1217 dir_markers :: [Char]
1218 dir_markers = ['/', '\\']
1221 -- -----------------------------------------------------------------------------
1222 -- tmpDir, where we store temporary files.
1224 setTmpDir :: FilePath -> DynFlags -> DynFlags
1225 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1227 #if !defined(mingw32_HOST_OS)
1228 canonicalise p = normalisePath p
1230 -- Canonicalisation of temp path under win32 is a bit more
1231 -- involved: (a) strip trailing slash,
1232 -- (b) normalise slashes
1233 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1235 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1237 -- if we're operating under cygwin, and TMP/TEMP is of
1238 -- the form "/cygdrive/drive/path", translate this to
1239 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1240 -- understand /cygdrive paths.)
1242 | "/cygdrive/" `isPrefixOf` path =
1243 case drop (length "/cygdrive/") path of
1244 drive:xs@('/':_) -> drive:':':xs
1248 -- strip the trailing backslash (awful, but we only do this once).
1249 removeTrailingSlash path =
1256 -----------------------------------------------------------------------------
1259 setOptHpcDir :: String -> DynP ()
1260 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1262 -----------------------------------------------------------------------------
1263 -- Via-C compilation stuff
1265 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1266 [String]) -- for registerised HC compilations
1267 machdepCCOpts dflags
1268 #if alpha_TARGET_ARCH
1270 #ifdef HAVE_THREADED_RTS_SUPPORT
1274 -- For now, to suppress the gcc warning "call-clobbered
1275 -- register used for global register variable", we simply
1276 -- disable all warnings altogether using the -w flag. Oh well.
1278 #elif hppa_TARGET_ARCH
1279 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1280 -- (very nice, but too bad the HP /usr/include files don't agree.)
1281 = ( ["-D_HPUX_SOURCE"], [] )
1283 #elif m68k_TARGET_ARCH
1284 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1285 -- popping of args to routines to be explicit; if we let things
1286 -- be deferred 'til after an STGJUMP, imminent death is certain!
1288 -- -fomit-frame-pointer : *don't*
1289 -- It's better to have a6 completely tied up being a frame pointer
1290 -- rather than let GCC pick random things to do with it.
1291 -- (If we want to steal a6, then we would try to do things
1292 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1293 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1295 #elif i386_TARGET_ARCH
1296 -- -fno-defer-pop : basically the same game as for m68k
1298 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1299 -- the fp (%ebp) for our register maps.
1300 = let n_regs = stolen_x86_regs dflags
1303 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1304 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1307 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1308 -- Some gccs are configured with
1309 -- -momit-leaf-frame-pointer on by default, and it
1310 -- apparently takes precedence over
1311 -- -fomit-frame-pointer, so we disable it first here.
1312 "-mno-omit-leaf-frame-pointer",
1314 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1315 "-fno-unit-at-a-time",
1316 -- unit-at-a-time doesn't do us any good, and screws
1317 -- up -split-objs by moving the split markers around.
1318 -- It's only turned on with -O2, but put it here just
1319 -- in case someone uses -optc-O2.
1321 "-fomit-frame-pointer",
1322 -- we want -fno-builtin, because when gcc inlines
1323 -- built-in functions like memcpy() it tends to
1324 -- run out of registers, requiring -monly-n-regs
1326 "-DSTOLEN_X86_REGS="++show n_regs ]
1329 #elif ia64_TARGET_ARCH
1330 = ( [], ["-fomit-frame-pointer", "-G0"] )
1332 #elif x86_64_TARGET_ARCH
1333 = ( [], ["-fomit-frame-pointer",
1334 "-fno-asynchronous-unwind-tables",
1335 -- the unwind tables are unnecessary for HC code,
1336 -- and get in the way of -split-objs. Another option
1337 -- would be to throw them away in the mangler, but this
1339 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1340 "-fno-unit-at-a-time",
1341 -- unit-at-a-time doesn't do us any good, and screws
1342 -- up -split-objs by moving the split markers around.
1343 -- It's only turned on with -O2, but put it here just
1344 -- in case someone uses -optc-O2.
1347 -- calling builtins like strlen() using the FFI can
1348 -- cause gcc to run out of regs, so use the external
1352 #elif sparc_TARGET_ARCH
1354 -- For now, to suppress the gcc warning "call-clobbered
1355 -- register used for global register variable", we simply
1356 -- disable all warnings altogether using the -w flag. Oh well.
1358 #elif powerpc_apple_darwin_TARGET
1360 -- Disable Apple's precompiling preprocessor. It's a great thing
1361 -- for "normal" programs, but it doesn't support register variable
1363 = ( [], ["-no-cpp-precomp"] )
1368 picCCOpts :: DynFlags -> [String]
1370 #if darwin_TARGET_OS
1371 -- Apple prefers to do things the other way round.
1372 -- PIC is on by default.
1373 -- -mdynamic-no-pic:
1374 -- Turn off PIC code generation.
1376 -- Don't generate "common" symbols - these are unwanted
1377 -- in dynamic libraries.
1382 = ["-mdynamic-no-pic"]
1383 #elif mingw32_TARGET_OS
1384 -- no -fPIC for Windows
1393 -- -----------------------------------------------------------------------------
1398 #if defined(i386_TARGET_ARCH) \
1399 || defined(x86_64_TARGET_ARCH) \
1400 || defined(alpha_TARGET_ARCH) \
1401 || defined(hppa_TARGET_ARCH) \
1402 || defined(m68k_TARGET_ARCH) \
1403 || defined(mips_TARGET_ARCH) \
1404 || defined(powerpc_TARGET_ARCH) \
1405 || defined(rs6000_TARGET_ARCH) \
1406 || defined(sparc_TARGET_ARCH)