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]
48 machdepCCOpts, picCCOpts,
51 #include "HsVersions.h"
53 import Module ( Module, mkModuleName, mkModule )
55 import PrelNames ( mAIN )
56 #ifdef i386_TARGET_ARCH
57 import StaticFlags ( opt_Static )
59 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
61 import {-# SOURCE #-} Packages (PackageState)
62 import DriverPhases ( Phase(..), phaseInputExt )
65 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
66 import Panic ( panic, GhcException(..) )
67 import UniqFM ( UniqFM )
68 import Util ( notNull, splitLongestPrefix, normalisePath )
69 import Maybes ( fromJust, orElse )
70 import SrcLoc ( SrcSpan )
72 import DATA_IOREF ( readIORef )
73 import EXCEPTION ( throwDyn )
75 #ifdef mingw32_TARGET_OS
76 import Data.List ( isPrefixOf )
81 import Char ( isDigit, isUpper )
83 import System.IO ( hPutStrLn, stderr )
84 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
86 -- -----------------------------------------------------------------------------
99 | Opt_D_dump_inlinings
100 | Opt_D_dump_occur_anal
104 | Opt_D_dump_simpl_iterations
113 | Opt_D_dump_worker_wrapper
114 | Opt_D_dump_rn_trace
115 | Opt_D_dump_rn_stats
117 | Opt_D_dump_simpl_stats
118 | Opt_D_dump_tc_trace
119 | Opt_D_dump_if_trace
124 | Opt_D_verbose_core2core
125 | Opt_D_verbose_stg2stg
127 | Opt_D_dump_hi_diffs
128 | Opt_D_dump_minimal_imports
129 | Opt_D_faststring_stats
134 | Opt_WarnIsError -- -Werror; makes warnings fatal
135 | Opt_WarnDuplicateExports
137 | Opt_WarnIncompletePatterns
138 | Opt_WarnIncompletePatternsRecUpd
139 | Opt_WarnMissingFields
140 | Opt_WarnMissingMethods
141 | Opt_WarnMissingSigs
142 | Opt_WarnNameShadowing
143 | Opt_WarnOverlappingPatterns
144 | Opt_WarnSimplePatterns
145 | Opt_WarnTypeDefaults
146 | Opt_WarnUnusedBinds
147 | Opt_WarnUnusedImports
148 | Opt_WarnUnusedMatches
149 | Opt_WarnDeprecations
150 | Opt_WarnDodgyImports
154 | Opt_AllowOverlappingInstances
155 | Opt_AllowUndecidableInstances
156 | Opt_AllowIncoherentInstances
157 | Opt_MonomorphismRestriction
159 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
162 | Opt_PArr -- Syntactic support for parallel arrays
163 | Opt_Arrows -- Arrow-notation syntax
167 | Opt_ImplicitPrelude
168 | Opt_ScopedTypeVariables
176 | Opt_IgnoreInterfacePragmas
177 | Opt_OmitInterfacePragmas
178 | Opt_DoLambdaEtaExpansion
180 | Opt_IgnoreBreakpoints
183 | Opt_UnboxStrictFields
192 | Opt_ExcessPrecision
193 | Opt_ReadUserPackageConf
197 | Opt_HideAllPackages
208 data DynFlags = DynFlags {
211 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
212 stgToDo :: Maybe [StgToDo], -- similarly
213 hscTarget :: HscTarget,
214 hscOutName :: String, -- name of the output file
215 extCoreName :: String, -- name of the .core output file
216 verbosity :: Int, -- verbosity level
217 optLevel :: Int, -- optimisation level
218 maxSimplIterations :: Int, -- max simplifier iterations
219 ruleCheck :: Maybe String,
220 stolen_x86_regs :: Int,
221 cmdlineHcIncludes :: [String], -- -#includes
222 importPaths :: [FilePath],
224 mainFunIs :: Maybe String,
225 ctxtStkDepth :: Int, -- Typechecker context stack depth
227 thisPackage :: PackageId,
230 wayNames :: [WayName], -- way flags from the cmd line
231 buildTag :: String, -- the global "way" (eg. "p" for prof)
232 rtsBuildTag :: String, -- the RTS "way"
235 objectDir :: Maybe String,
236 hiDir :: Maybe String,
237 stubDir :: Maybe String,
243 outputFile :: Maybe String,
244 outputHi :: Maybe String,
246 includePaths :: [String],
247 libraryPaths :: [String],
248 frameworkPaths :: [String], -- used on darwin only
249 cmdlineFrameworks :: [String], -- ditto
250 tmpDir :: String, -- no trailing '/'
252 ghcUsagePath :: FilePath, -- Filled in by SysTools
253 ghciUsagePath :: FilePath, -- ditto
255 -- options for particular phases
266 -- commands for particular phases
268 pgm_P :: (String,[Option]),
270 pgm_c :: (String,[Option]),
271 pgm_m :: (String,[Option]),
272 pgm_s :: (String,[Option]),
273 pgm_a :: (String,[Option]),
274 pgm_l :: (String,[Option]),
275 pgm_dll :: (String,[Option]),
277 pgm_sysman :: String,
280 extraPkgConfs :: [FilePath],
281 topDir :: FilePath, -- filled in by SysTools
282 systemPackageConfig :: FilePath, -- ditto
283 -- The -package-conf flags given on the command line, in the order
286 packageFlags :: [PackageFlag],
287 -- The -package and -hide-package flags from the command-line
290 -- NB. do not modify this field, it is calculated by
291 -- Packages.initPackages and Packages.updatePackages.
292 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
293 pkgState :: PackageState,
299 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
312 = BatchCompile -- | @ghc --make Main@
313 | Interactive -- | @ghc --interactive@
314 | OneShot -- | @ghc -c Foo.hs@
315 | JustTypecheck -- | Development environemnts, refactorer, etc.
319 isOneShot :: GhcMode -> Bool
320 isOneShot OneShot = True
321 isOneShot _other = False
323 data GhcLink -- What to do in the link step, if there is one
324 = -- Only relevant for modes
325 -- DoMake and StopBefore StopLn
326 NoLink -- Don't link at all
327 | StaticLink -- Ordinary linker [the default]
328 | MkDLL -- Make a DLL
330 isNoLink :: GhcLink -> Bool
331 isNoLink NoLink = True
332 isNoLink other = False
335 = ExposePackage String
337 | IgnorePackage String
341 | cGhcWithNativeCodeGen == "YES" = HscAsm
344 initDynFlags dflags = do
345 -- someday these will be dynamic flags
346 ways <- readIORef v_Ways
347 build_tag <- readIORef v_Build_tag
348 rts_build_tag <- readIORef v_RTS_Build_tag
351 buildTag = build_tag,
352 rtsBuildTag = rts_build_tag
358 ghcLink = StaticLink,
361 hscTarget = defaultHscTarget,
366 maxSimplIterations = 4,
369 cmdlineHcIncludes = [],
373 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
375 thisPackage = mainPackageId,
381 objectSuf = phaseInputExt StopLn,
382 hcSuf = phaseInputExt HCc,
385 outputFile = Nothing,
390 cmdlineFrameworks = [],
391 tmpDir = cDEFAULT_TMPDIR,
405 pkgDatabase = Nothing,
406 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
410 Opt_ReadUserPackageConf,
412 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
413 -- behaviour the default, to see if anyone notices
417 Opt_MonomorphismRestriction,
419 -- strictness is on by default, but this only
421 Opt_CSE, -- similarly for CSE.
422 Opt_FullLaziness, -- ...and for full laziness
424 Opt_DoLambdaEtaExpansion,
425 -- This one is important for a tiresome reason:
426 -- we want to make sure that the bindings for data
427 -- constructors are eta-expanded. This is probably
428 -- a good thing anyway, but it seems fragile.
432 -- and the default no-optimisation options:
433 Opt_IgnoreInterfacePragmas,
434 Opt_OmitInterfacePragmas
436 ] ++ standardWarnings,
438 log_action = \severity srcSpan style msg ->
440 SevInfo -> hPutStrLn stderr (show (msg style))
441 SevFatal -> hPutStrLn stderr (show (msg style))
442 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
448 0 | print errors & warnings only
449 1 | minimal verbosity: print "compiling M ... done." for each module.
450 2 | equivalent to -dshow-passes
451 3 | equivalent to existing "ghc -v"
452 4 | "ghc -v -ddump-most"
453 5 | "ghc -v -ddump-all"
456 dopt :: DynFlag -> DynFlags -> Bool
457 dopt f dflags = f `elem` (flags dflags)
459 dopt_set :: DynFlags -> DynFlag -> DynFlags
460 dopt_set dfs f = dfs{ flags = f : flags dfs }
462 dopt_unset :: DynFlags -> DynFlag -> DynFlags
463 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
465 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
466 getOpts dflags opts = reverse (opts dflags)
467 -- We add to the options from the front, so we need to reverse the list
469 getVerbFlag :: DynFlags -> String
471 | verbosity dflags >= 3 = "-v"
474 setObjectDir f d = d{ objectDir = f}
475 setHiDir f d = d{ hiDir = f}
476 setStubDir f d = d{ stubDir = f}
478 setObjectSuf f d = d{ objectSuf = f}
479 setHiSuf f d = d{ hiSuf = f}
480 setHcSuf f d = d{ hcSuf = f}
482 setOutputFile f d = d{ outputFile = f}
483 setOutputHi f d = d{ outputHi = f}
485 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
486 -- Config.hs should really use Option.
487 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
489 setPgmL f d = d{ pgm_L = f}
490 setPgmF f d = d{ pgm_F = f}
491 setPgmc f d = d{ pgm_c = (f,[])}
492 setPgmm f d = d{ pgm_m = (f,[])}
493 setPgms f d = d{ pgm_s = (f,[])}
494 setPgma f d = d{ pgm_a = (f,[])}
495 setPgml f d = d{ pgm_l = (f,[])}
496 setPgmdll f d = d{ pgm_dll = (f,[])}
498 addOptL f d = d{ opt_L = f : opt_L d}
499 addOptP f d = d{ opt_P = f : opt_P d}
500 addOptF f d = d{ opt_F = f : opt_F d}
501 addOptc f d = d{ opt_c = f : opt_c d}
502 addOptm f d = d{ opt_m = f : opt_m d}
503 addOpta f d = d{ opt_a = f : opt_a d}
504 addOptl f d = d{ opt_l = f : opt_l d}
505 addOptdll f d = d{ opt_dll = f : opt_dll d}
506 addOptdep f d = d{ opt_dep = f : opt_dep d}
508 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
510 -- -----------------------------------------------------------------------------
511 -- Command-line options
513 -- When invoking external tools as part of the compilation pipeline, we
514 -- pass these a sequence of options on the command-line. Rather than
515 -- just using a list of Strings, we use a type that allows us to distinguish
516 -- between filepaths and 'other stuff'. [The reason being, of course, that
517 -- this type gives us a handle on transforming filenames, and filenames only,
518 -- to whatever format they're expected to be on a particular platform.]
521 = FileOption -- an entry that _contains_ filename(s) / filepaths.
522 String -- a non-filepath prefix that shouldn't be
523 -- transformed (e.g., "/out=")
524 String -- the filepath/filename portion
527 -----------------------------------------------------------------------------
528 -- Setting the optimisation level
530 updOptLevel :: Int -> DynFlags -> DynFlags
531 -- Set dynflags appropriate to the optimisation level
534 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
535 else dfs2{ optLevel = n }
537 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
538 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
541 | n == 0 = opt_0_dopts
542 | otherwise = opt_1_dopts
545 | n == 0 = opt_1_dopts
546 | otherwise = opt_0_dopts
549 Opt_IgnoreInterfacePragmas,
550 Opt_OmitInterfacePragmas
559 -- -----------------------------------------------------------------------------
560 -- Standard sets of warning options
563 = [ Opt_WarnDeprecations,
564 Opt_WarnOverlappingPatterns,
565 Opt_WarnMissingFields,
566 Opt_WarnMissingMethods,
567 Opt_WarnDuplicateExports
571 = standardWarnings ++
572 [ Opt_WarnUnusedBinds,
573 Opt_WarnUnusedMatches,
574 Opt_WarnUnusedImports,
575 Opt_WarnIncompletePatterns,
581 [ Opt_WarnTypeDefaults,
582 Opt_WarnNameShadowing,
588 -- -----------------------------------------------------------------------------
589 -- CoreToDo: abstraction of core-to-core passes to run.
591 data CoreToDo -- These are diff core-to-core passes,
592 -- which may be invoked in any order,
593 -- as many times as you like.
595 = CoreDoSimplify -- The core-to-core simplifier.
598 -- Each run of the simplifier can take a different
599 -- set of simplifier-specific flags.
601 | CoreDoFloatOutwards FloatOutSwitches
606 | CoreDoWorkerWrapper
609 | CoreDoOldStrictness
612 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
613 -- matching this string
615 | CoreDoNothing -- useful when building up lists of these things
617 data SimplifierMode -- See comments in SimplMonad
621 data SimplifierSwitch
622 = MaxSimplifierIterations Int
625 data FloatOutSwitches
626 = FloatOutSw Bool -- True <=> float lambdas to top level
627 Bool -- True <=> float constants to top level,
628 -- even if they do not escape a lambda
631 -- The core-to-core pass ordering is derived from the DynFlags:
633 getCoreToDo :: DynFlags -> [CoreToDo]
635 | Just todo <- coreToDo dflags = todo -- set explicitly by user
636 | otherwise = core_todo
638 opt_level = optLevel dflags
639 max_iter = maxSimplIterations dflags
640 strictness = dopt Opt_Strictness dflags
641 full_laziness = dopt Opt_FullLaziness dflags
642 cse = dopt Opt_CSE dflags
643 rule_check = ruleCheck dflags
646 if opt_level == 0 then
648 CoreDoSimplify (SimplPhase 0) [
649 MaxSimplifierIterations max_iter
652 else {- opt_level >= 1 -} [
654 -- initial simplify: mk specialiser happy: minimum effort please
655 CoreDoSimplify SimplGently [
657 -- Don't inline anything till full laziness has bitten
658 -- In particular, inlining wrappers inhibits floating
659 -- e.g. ...(case f x of ...)...
660 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
661 -- ==> ...(case x of I# x# -> case fw x# of ...)...
662 -- and now the redex (f x) isn't floatable any more
663 -- Similarly, don't apply any rules until after full
664 -- laziness. Notably, list fusion can prevent floating.
666 NoCaseOfCase, -- Don't do case-of-case transformations.
667 -- This makes full laziness work better
668 MaxSimplifierIterations max_iter
671 -- Specialisation is best done before full laziness
672 -- so that overloaded functions have all their dictionary lambdas manifest
675 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
680 CoreDoSimplify (SimplPhase 2) [
681 -- Want to run with inline phase 2 after the specialiser to give
682 -- maximum chance for fusion to work before we inline build/augment
683 -- in phase 1. This made a difference in 'ansi' where an
684 -- overloaded function wasn't inlined till too late.
685 MaxSimplifierIterations max_iter
687 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
689 CoreDoSimplify (SimplPhase 1) [
690 -- Need inline-phase2 here so that build/augment get
691 -- inlined. I found that spectral/hartel/genfft lost some useful
692 -- strictness in the function sumcode' if augment is not inlined
693 -- before strictness analysis runs
694 MaxSimplifierIterations max_iter
696 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
698 CoreDoSimplify (SimplPhase 0) [
699 -- Phase 0: allow all Ids to be inlined now
700 -- This gets foldr inlined before strictness analysis
702 MaxSimplifierIterations 3
703 -- At least 3 iterations because otherwise we land up with
704 -- huge dead expressions because of an infelicity in the
706 -- let k = BIG in foldr k z xs
707 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
708 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
712 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
714 #ifdef OLD_STRICTNESS
717 if strictness then CoreDoStrictness else CoreDoNothing,
721 CoreDoSimplify (SimplPhase 0) [
722 MaxSimplifierIterations max_iter
725 if full_laziness then
726 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
727 True) -- Float constants
729 -- nofib/spectral/hartel/wang doubles in speed if you
730 -- do full laziness late in the day. It only happens
731 -- after fusion and other stuff, so the early pass doesn't
732 -- catch it. For the record, the redex is
733 -- f_el22 (f_el21 r_midblock)
736 -- We want CSE to follow the final full-laziness pass, because it may
737 -- succeed in commoning up things floated out by full laziness.
738 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
740 if cse then CoreCSE else CoreDoNothing,
744 -- Case-liberation for -O2. This should be after
745 -- strictness analysis and the simplification which follows it.
747 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
752 (if opt_level >= 2 then
754 CoreDoSimplify (SimplPhase 0) [
755 MaxSimplifierIterations max_iter
756 ], -- Run the simplifier after LiberateCase to vastly
757 -- reduce the possiblility of shadowing
758 -- Reason: see Note [Shadowing] in SpecConstr.lhs
766 -- Final clean-up simplification:
767 [ CoreDoSimplify (SimplPhase 0) [
768 MaxSimplifierIterations max_iter
772 -- -----------------------------------------------------------------------------
773 -- StgToDo: abstraction of stg-to-stg passes to run.
776 = StgDoMassageForProfiling -- should be (next to) last
777 -- There's also setStgVarInfo, but its absolute "lastness"
778 -- is so critical that it is hardwired in (no flag).
781 getStgToDo :: DynFlags -> [StgToDo]
783 | Just todo <- stgToDo dflags = todo -- set explicitly by user
786 stg_stats = dopt Opt_StgStats dflags
788 todo1 = if stg_stats then [D_stg_stats] else []
790 todo2 | WayProf `elem` wayNames dflags
791 = StgDoMassageForProfiling : todo1
795 -- -----------------------------------------------------------------------------
799 allFlags = map ('-':) $
800 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
801 map ("fno-"++) flags ++
803 where ok (PrefixPred _ _) = False
805 flags = map fst fFlags
807 dynamic_flags :: [(String, OptKind DynP)]
809 ( "n" , NoArg (setDynFlag Opt_DryRun) )
810 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
811 , ( "F" , NoArg (setDynFlag Opt_Pp))
812 , ( "#include" , HasArg (addCmdlineHCInclude) )
813 , ( "v" , OptIntSuffix setVerbosity )
815 ------- Specific phases --------------------------------------------
816 , ( "pgmL" , HasArg (upd . setPgmL) )
817 , ( "pgmP" , HasArg (upd . setPgmP) )
818 , ( "pgmF" , HasArg (upd . setPgmF) )
819 , ( "pgmc" , HasArg (upd . setPgmc) )
820 , ( "pgmm" , HasArg (upd . setPgmm) )
821 , ( "pgms" , HasArg (upd . setPgms) )
822 , ( "pgma" , HasArg (upd . setPgma) )
823 , ( "pgml" , HasArg (upd . setPgml) )
824 , ( "pgmdll" , HasArg (upd . setPgmdll) )
826 , ( "optL" , HasArg (upd . addOptL) )
827 , ( "optP" , HasArg (upd . addOptP) )
828 , ( "optF" , HasArg (upd . addOptF) )
829 , ( "optc" , HasArg (upd . addOptc) )
830 , ( "optm" , HasArg (upd . addOptm) )
831 , ( "opta" , HasArg (upd . addOpta) )
832 , ( "optl" , HasArg (upd . addOptl) )
833 , ( "optdll" , HasArg (upd . addOptdll) )
834 , ( "optdep" , HasArg (upd . addOptdep) )
836 , ( "split-objs" , NoArg (if can_split
837 then setDynFlag Opt_SplitObjs
840 -------- Linking ----------------------------------------------------
841 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
842 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
843 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
845 ------- Libraries ---------------------------------------------------
846 , ( "L" , Prefix addLibraryPath )
847 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
850 ------- Frameworks --------------------------------------------------
851 -- -framework-path should really be -F ...
852 , ( "framework-path" , HasArg addFrameworkPath )
853 , ( "framework" , HasArg (upd . addCmdlineFramework) )
855 ------- Output Redirection ------------------------------------------
856 , ( "odir" , HasArg (upd . setObjectDir . Just))
857 , ( "o" , SepArg (upd . setOutputFile . Just))
858 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
859 , ( "osuf" , HasArg (upd . setObjectSuf))
860 , ( "hcsuf" , HasArg (upd . setHcSuf))
861 , ( "hisuf" , HasArg (upd . setHiSuf))
862 , ( "hidir" , HasArg (upd . setHiDir . Just))
863 , ( "tmpdir" , HasArg (upd . setTmpDir))
864 , ( "stubdir" , HasArg (upd . setStubDir . Just))
866 ------- Keeping temporary files -------------------------------------
867 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
868 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
869 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
870 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
872 ------- Miscellaneous ----------------------------------------------
873 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
874 , ( "main-is" , SepArg setMainIs )
876 ------- recompilation checker --------------------------------------
877 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
878 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
880 ------- Packages ----------------------------------------------------
881 , ( "package-conf" , HasArg extraPkgConf_ )
882 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
883 , ( "package-name" , HasArg setPackageName )
884 , ( "package" , HasArg exposePackage )
885 , ( "hide-package" , HasArg hidePackage )
886 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
887 , ( "ignore-package" , HasArg ignorePackage )
888 , ( "syslib" , HasArg exposePackage ) -- for compatibility
890 ------ HsCpp opts ---------------------------------------------------
891 , ( "D", AnySuffix (upd . addOptP) )
892 , ( "U", AnySuffix (upd . addOptP) )
894 ------- Include/Import Paths ----------------------------------------
895 , ( "I" , Prefix addIncludePath)
896 , ( "i" , OptPrefix addImportPath )
898 ------ Debugging ----------------------------------------------------
899 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
901 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
902 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
903 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
904 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
905 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
906 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
907 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
908 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
909 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
910 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
911 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
912 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
913 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
914 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
915 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
916 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
917 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
918 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
919 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
920 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
921 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
922 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
923 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
924 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
925 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
926 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
927 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
928 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
929 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
930 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
931 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
932 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
933 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
934 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
935 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
936 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
937 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
938 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
939 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
940 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
941 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
942 setVerbosity (Just 2)) )
943 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
945 ------ Machine dependant (-m<blah>) stuff ---------------------------
947 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
948 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
949 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
951 ------ Warning opts -------------------------------------------------
952 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
953 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
954 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
955 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
956 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
958 ------ Optimisation flags ------------------------------------------
959 , ( "O" , NoArg (upd (setOptLevel 1)))
960 , ( "Onot" , NoArg (upd (setOptLevel 0)))
961 , ( "O" , PrefixPred (all isDigit)
962 (\f -> upd (setOptLevel (read f))))
964 , ( "fmax-simplifier-iterations",
965 PrefixPred (all isDigit)
967 dfs{ maxSimplIterations = read n })) )
970 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
972 ------ Compiler flags -----------------------------------------------
974 , ( "fno-code", NoArg (setTarget HscNothing))
975 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
976 , ( "fvia-c", NoArg (setTarget HscC) )
977 , ( "fvia-C", NoArg (setTarget HscC) )
978 , ( "filx", NoArg (setTarget HscILX) )
980 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
981 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
983 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
984 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
986 -- the rest of the -f* and -fno-* flags
987 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
988 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
991 -- these -f<blah> flags can all be reversed with -fno-<blah>
994 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
995 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
996 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
997 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
998 ( "warn-missing-fields", Opt_WarnMissingFields ),
999 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1000 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1001 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1002 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1003 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1004 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1005 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1006 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1007 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1008 ( "warn-deprecations", Opt_WarnDeprecations ),
1009 ( "warn-orphans", Opt_WarnOrphans ),
1010 ( "fi", Opt_FFI ), -- support `-ffi'...
1011 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1012 ( "arrows", Opt_Arrows ), -- arrow syntax
1013 ( "parr", Opt_PArr ),
1015 ( "implicit-prelude", Opt_ImplicitPrelude ),
1016 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1017 ( "bang-patterns", Opt_BangPatterns ),
1018 ( "indexed-types", Opt_IndexedTypes ),
1019 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1020 ( "mono-pat-binds", Opt_MonoPatBinds ),
1021 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1022 ( "implicit-params", Opt_ImplicitParams ),
1023 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1024 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1025 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1026 ( "generics", Opt_Generics ),
1027 ( "strictness", Opt_Strictness ),
1028 ( "full-laziness", Opt_FullLaziness ),
1030 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1031 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1032 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1033 ( "ignore-asserts", Opt_IgnoreAsserts ),
1034 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1035 ( "do-eta-reduction", Opt_DoEtaReduction ),
1036 ( "case-merge", Opt_CaseMerge ),
1037 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1038 ( "dicts-cheap", Opt_DictsCheap ),
1039 ( "excess-precision", Opt_ExcessPrecision ),
1040 ( "asm-mangling", Opt_DoAsmMangling )
1043 glasgowExtsFlags = [
1047 Opt_ScopedTypeVariables,
1050 isFFlag f = f `elem` (map fst fFlags)
1051 getFFlag f = fromJust (lookup f fFlags)
1053 -- -----------------------------------------------------------------------------
1054 -- Parsing the dynamic flags.
1056 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1057 parseDynamicFlags dflags args = do
1058 let ((leftover,errs),dflags')
1059 = runCmdLine (processArgs dynamic_flags args) dflags
1060 when (not (null errs)) $ do
1061 throwDyn (UsageError (unlines errs))
1062 return (dflags', leftover)
1065 type DynP = CmdLineP DynFlags
1067 upd :: (DynFlags -> DynFlags) -> DynP ()
1069 dfs <- getCmdLineState
1070 putCmdLineState $! (f dfs)
1072 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1073 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1074 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1076 setDumpFlag :: DynFlag -> OptKind DynP
1077 setDumpFlag dump_flag
1078 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1079 -- Whenver we -ddump, switch off the recompilation checker,
1080 -- else you don't see the dump!
1082 setVerbosity :: Maybe Int -> DynP ()
1083 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1085 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1087 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1090 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1092 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1094 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1096 | Nothing <- unpackPackageId pid
1097 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1099 = upd (\s -> s{ thisPackage = pid })
1101 pid = stringToPackageId p
1103 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1104 -- (-fvia-C, -fasm, -filx respectively).
1105 setTarget l = upd (\dfs -> case hscTarget dfs of
1106 HscC -> dfs{ hscTarget = l }
1107 HscAsm -> dfs{ hscTarget = l }
1108 HscILX -> dfs{ hscTarget = l }
1111 setOptLevel :: Int -> DynFlags -> DynFlags
1112 setOptLevel n dflags
1113 | hscTarget dflags == HscInterpreted && n > 0
1115 -- not in IO any more, oh well:
1116 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1118 = updOptLevel n dflags
1121 setMainIs :: String -> DynP ()
1123 | not (null main_fn) -- The arg looked like "Foo.baz"
1124 = upd $ \d -> d{ mainFunIs = Just main_fn,
1125 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1127 | isUpper (head main_mod) -- The arg looked like "Foo"
1128 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1130 | otherwise -- The arg looked like "baz"
1131 = upd $ \d -> d{ mainFunIs = Just main_mod }
1133 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1135 -----------------------------------------------------------------------------
1136 -- Paths & Libraries
1138 -- -i on its own deletes the import paths
1139 addImportPath "" = upd (\s -> s{importPaths = []})
1140 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1144 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1147 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1149 addFrameworkPath p =
1150 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1152 split_marker = ':' -- not configurable (ToDo)
1154 splitPathList :: String -> [String]
1155 splitPathList s = filter notNull (splitUp s)
1156 -- empty paths are ignored: there might be a trailing
1157 -- ':' in the initial list, for example. Empty paths can
1158 -- cause confusion when they are translated into -I options
1159 -- for passing to gcc.
1161 #ifndef mingw32_TARGET_OS
1162 splitUp xs = split split_marker xs
1164 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1166 -- That is, if "foo:bar:baz" is used, this interpreted as
1167 -- consisting of three entries, 'foo', 'bar', 'baz'.
1168 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1169 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1171 -- Notice that no attempt is made to fully replace the 'standard'
1172 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1173 -- that this will cause too much breakage for users & ':' will
1174 -- work fine even with DOS paths, if you're not insisting on being silly.
1177 splitUp (x:':':div:xs) | div `elem` dir_markers
1178 = ((x:':':div:p): splitUp rs)
1180 (p,rs) = findNextPath xs
1181 -- we used to check for existence of the path here, but that
1182 -- required the IO monad to be threaded through the command-line
1183 -- parser which is quite inconvenient. The
1184 splitUp xs = cons p (splitUp rs)
1186 (p,rs) = findNextPath xs
1191 -- will be called either when we've consumed nought or the
1192 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1193 -- finding the next split marker.
1195 case break (`elem` split_markers) xs of
1196 (p, d:ds) -> (p, ds)
1199 split_markers :: [Char]
1200 split_markers = [':', ';']
1202 dir_markers :: [Char]
1203 dir_markers = ['/', '\\']
1206 -- -----------------------------------------------------------------------------
1207 -- tmpDir, where we store temporary files.
1209 setTmpDir :: FilePath -> DynFlags -> DynFlags
1210 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1212 #if !defined(mingw32_HOST_OS)
1213 canonicalise p = normalisePath p
1215 -- Canonicalisation of temp path under win32 is a bit more
1216 -- involved: (a) strip trailing slash,
1217 -- (b) normalise slashes
1218 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1220 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1222 -- if we're operating under cygwin, and TMP/TEMP is of
1223 -- the form "/cygdrive/drive/path", translate this to
1224 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1225 -- understand /cygdrive paths.)
1227 | "/cygdrive/" `isPrefixOf` path =
1228 case drop (length "/cygdrive/") path of
1229 drive:xs@('/':_) -> drive:':':xs
1233 -- strip the trailing backslash (awful, but we only do this once).
1234 removeTrailingSlash path =
1241 -----------------------------------------------------------------------------
1242 -- Via-C compilation stuff
1244 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1245 [String]) -- for registerised HC compilations
1246 machdepCCOpts dflags
1247 #if alpha_TARGET_ARCH
1249 #ifdef HAVE_THREADED_RTS_SUPPORT
1253 -- For now, to suppress the gcc warning "call-clobbered
1254 -- register used for global register variable", we simply
1255 -- disable all warnings altogether using the -w flag. Oh well.
1257 #elif hppa_TARGET_ARCH
1258 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1259 -- (very nice, but too bad the HP /usr/include files don't agree.)
1260 = ( ["-D_HPUX_SOURCE"], [] )
1262 #elif m68k_TARGET_ARCH
1263 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1264 -- popping of args to routines to be explicit; if we let things
1265 -- be deferred 'til after an STGJUMP, imminent death is certain!
1267 -- -fomit-frame-pointer : *don't*
1268 -- It's better to have a6 completely tied up being a frame pointer
1269 -- rather than let GCC pick random things to do with it.
1270 -- (If we want to steal a6, then we would try to do things
1271 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1272 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1274 #elif i386_TARGET_ARCH
1275 -- -fno-defer-pop : basically the same game as for m68k
1277 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1278 -- the fp (%ebp) for our register maps.
1279 = let n_regs = stolen_x86_regs dflags
1282 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1283 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1286 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1287 -- Some gccs are configured with
1288 -- -momit-leaf-frame-pointer on by default, and it
1289 -- apparently takes precedence over
1290 -- -fomit-frame-pointer, so we disable it first here.
1291 "-mno-omit-leaf-frame-pointer",
1293 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1294 "-fno-unit-at-a-time",
1295 -- unit-at-a-time doesn't do us any good, and screws
1296 -- up -split-objs by moving the split markers around.
1297 -- It's only turned on with -O2, but put it here just
1298 -- in case someone uses -optc-O2.
1300 "-fomit-frame-pointer",
1301 -- we want -fno-builtin, because when gcc inlines
1302 -- built-in functions like memcpy() it tends to
1303 -- run out of registers, requiring -monly-n-regs
1305 "-DSTOLEN_X86_REGS="++show n_regs ]
1308 #elif ia64_TARGET_ARCH
1309 = ( [], ["-fomit-frame-pointer", "-G0"] )
1311 #elif x86_64_TARGET_ARCH
1312 = ( [], ["-fomit-frame-pointer",
1313 "-fno-asynchronous-unwind-tables",
1314 -- the unwind tables are unnecessary for HC code,
1315 -- and get in the way of -split-objs. Another option
1316 -- would be to throw them away in the mangler, but this
1318 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1319 "-fno-unit-at-a-time",
1320 -- unit-at-a-time doesn't do us any good, and screws
1321 -- up -split-objs by moving the split markers around.
1322 -- It's only turned on with -O2, but put it here just
1323 -- in case someone uses -optc-O2.
1326 -- calling builtins like strlen() using the FFI can
1327 -- cause gcc to run out of regs, so use the external
1331 #elif mips_TARGET_ARCH
1332 = ( ["-static"], [] )
1334 #elif sparc_TARGET_ARCH
1336 -- For now, to suppress the gcc warning "call-clobbered
1337 -- register used for global register variable", we simply
1338 -- disable all warnings altogether using the -w flag. Oh well.
1340 #elif powerpc_apple_darwin_TARGET
1342 -- Disable Apple's precompiling preprocessor. It's a great thing
1343 -- for "normal" programs, but it doesn't support register variable
1345 = ( [], ["-no-cpp-precomp"] )
1350 picCCOpts :: DynFlags -> [String]
1352 #if darwin_TARGET_OS
1353 -- Apple prefers to do things the other way round.
1354 -- PIC is on by default.
1355 -- -mdynamic-no-pic:
1356 -- Turn off PIC code generation.
1358 -- Don't generate "common" symbols - these are unwanted
1359 -- in dynamic libraries.
1364 = ["-mdynamic-no-pic"]
1365 #elif mingw32_TARGET_OS
1366 -- no -fPIC for Windows
1375 -- -----------------------------------------------------------------------------
1380 #if defined(i386_TARGET_ARCH) \
1381 || defined(x86_64_TARGET_ARCH) \
1382 || defined(alpha_TARGET_ARCH) \
1383 || defined(hppa_TARGET_ARCH) \
1384 || defined(m68k_TARGET_ARCH) \
1385 || defined(mips_TARGET_ARCH) \
1386 || defined(powerpc_TARGET_ARCH) \
1387 || defined(rs6000_TARGET_ARCH) \
1388 || defined(sparc_TARGET_ARCH)