1 -----------------------------------------------------------------------------
5 -- Most flags are dynamic flags, which means they can change from
6 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
7 -- multi-session GHC each session can be using different dynamic
8 -- flags. Dynamic flags can also be set at the prompt in GHCi.
10 -- (c) The University of Glasgow 2005
12 -----------------------------------------------------------------------------
19 GhcMode(..), isOneShot,
20 GhcLink(..), isNoLink,
24 -- Configuration of the core-to-core and stg-to-stg phases
28 SimplifierMode(..), FloatOutSwitches(..),
29 getCoreToDo, getStgToDo,
31 -- Manipulating DynFlags
32 defaultDynFlags, -- DynFlags
33 initDynFlags, -- DynFlags -> IO DynFlags
35 dopt, -- DynFlag -> DynFlags -> Bool
36 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
37 getOpts, -- (DynFlags -> [a]) -> IO [a]
47 machdepCCOpts, picCCOpts,
50 #include "HsVersions.h"
52 import Module ( Module, mkModuleName, mkModule )
54 import PrelNames ( mAIN )
55 #ifdef i386_TARGET_ARCH
56 import StaticFlags ( opt_Static )
58 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
60 import {-# SOURCE #-} Packages (PackageState)
61 import DriverPhases ( Phase(..), phaseInputExt )
64 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
65 import Panic ( panic, GhcException(..) )
66 import Util ( notNull, splitLongestPrefix, normalisePath )
67 import Maybes ( fromJust, orElse )
68 import SrcLoc ( SrcSpan )
70 import DATA_IOREF ( readIORef )
71 import EXCEPTION ( throwDyn )
73 #ifdef mingw32_TARGET_OS
74 import Data.List ( isPrefixOf )
79 import Char ( isDigit, isUpper )
81 import System.IO ( hPutStrLn, stderr )
82 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
84 -- -----------------------------------------------------------------------------
97 | Opt_D_dump_inlinings
98 | Opt_D_dump_occur_anal
102 | Opt_D_dump_simpl_iterations
111 | Opt_D_dump_worker_wrapper
112 | Opt_D_dump_rn_trace
113 | Opt_D_dump_rn_stats
115 | Opt_D_dump_simpl_stats
116 | Opt_D_dump_tc_trace
117 | Opt_D_dump_if_trace
122 | Opt_D_verbose_core2core
123 | Opt_D_verbose_stg2stg
125 | Opt_D_dump_hi_diffs
126 | Opt_D_dump_minimal_imports
127 | Opt_D_faststring_stats
132 | Opt_WarnIsError -- -Werror; makes warnings fatal
133 | Opt_WarnDuplicateExports
135 | Opt_WarnIncompletePatterns
136 | Opt_WarnIncompletePatternsRecUpd
137 | Opt_WarnMissingFields
138 | Opt_WarnMissingMethods
139 | Opt_WarnMissingSigs
140 | Opt_WarnNameShadowing
141 | Opt_WarnOverlappingPatterns
142 | Opt_WarnSimplePatterns
143 | Opt_WarnTypeDefaults
144 | Opt_WarnUnusedBinds
145 | Opt_WarnUnusedImports
146 | Opt_WarnUnusedMatches
147 | Opt_WarnDeprecations
148 | Opt_WarnDodgyImports
152 | Opt_AllowOverlappingInstances
153 | Opt_AllowUndecidableInstances
154 | Opt_AllowIncoherentInstances
155 | Opt_MonomorphismRestriction
159 | Opt_PArr -- syntactic support for parallel arrays
160 | Opt_Arrows -- Arrow-notation syntax
164 | Opt_ImplicitPrelude
165 | Opt_ScopedTypeVariables
172 | Opt_IgnoreInterfacePragmas
173 | Opt_OmitInterfacePragmas
174 | Opt_DoLambdaEtaExpansion
176 | Opt_IgnoreBreakpoints
179 | Opt_UnboxStrictFields
188 | Opt_ExcessPrecision
189 | Opt_ReadUserPackageConf
193 | Opt_HideAllPackages
204 data DynFlags = DynFlags {
207 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
208 stgToDo :: Maybe [StgToDo], -- similarly
209 hscTarget :: HscTarget,
210 hscOutName :: String, -- name of the output file
211 extCoreName :: String, -- name of the .core output file
212 verbosity :: Int, -- verbosity level
213 optLevel :: Int, -- optimisation level
214 maxSimplIterations :: Int, -- max simplifier iterations
215 ruleCheck :: Maybe String,
216 stolen_x86_regs :: Int,
217 cmdlineHcIncludes :: [String], -- -#includes
218 importPaths :: [FilePath],
220 mainFunIs :: Maybe String,
221 ctxtStkDepth :: Int, -- Typechecker context stack depth
223 thisPackage :: PackageId,
226 wayNames :: [WayName], -- way flags from the cmd line
227 buildTag :: String, -- the global "way" (eg. "p" for prof)
228 rtsBuildTag :: String, -- the RTS "way"
231 objectDir :: Maybe String,
232 hiDir :: Maybe String,
233 stubDir :: Maybe String,
239 outputFile :: Maybe String,
240 outputHi :: Maybe String,
242 includePaths :: [String],
243 libraryPaths :: [String],
244 frameworkPaths :: [String], -- used on darwin only
245 cmdlineFrameworks :: [String], -- ditto
246 tmpDir :: String, -- no trailing '/'
248 -- options for particular phases
259 -- commands for particular phases
261 pgm_P :: (String,[Option]),
263 pgm_c :: (String,[Option]),
264 pgm_m :: (String,[Option]),
265 pgm_s :: (String,[Option]),
266 pgm_a :: (String,[Option]),
267 pgm_l :: (String,[Option]),
268 pgm_dll :: (String,[Option]),
271 extraPkgConfs :: [FilePath],
272 -- The -package-conf flags given on the command line, in the order
275 packageFlags :: [PackageFlag],
276 -- The -package and -hide-package flags from the command-line
279 pkgState :: PackageState,
285 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
298 = BatchCompile -- | @ghc --make Main@
299 | Interactive -- | @ghc --interactive@
300 | OneShot -- | @ghc -c Foo.hs@
301 | JustTypecheck -- | Development environemnts, refactorer, etc.
305 isOneShot :: GhcMode -> Bool
306 isOneShot OneShot = True
307 isOneShot _other = False
309 data GhcLink -- What to do in the link step, if there is one
310 = -- Only relevant for modes
311 -- DoMake and StopBefore StopLn
312 NoLink -- Don't link at all
313 | StaticLink -- Ordinary linker [the default]
314 | MkDLL -- Make a DLL
316 isNoLink :: GhcLink -> Bool
317 isNoLink NoLink = True
318 isNoLink other = False
321 = ExposePackage String
323 | IgnorePackage String
326 | cGhcWithNativeCodeGen == "YES" = HscAsm
329 initDynFlags dflags = do
330 -- someday these will be dynamic flags
331 ways <- readIORef v_Ways
332 build_tag <- readIORef v_Build_tag
333 rts_build_tag <- readIORef v_RTS_Build_tag
336 buildTag = build_tag,
337 rtsBuildTag = rts_build_tag
343 ghcLink = StaticLink,
346 hscTarget = defaultHscTarget,
351 maxSimplIterations = 4,
354 cmdlineHcIncludes = [],
358 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
360 thisPackage = mainPackageId,
362 wayNames = panic "ways",
363 buildTag = panic "buildTag",
364 rtsBuildTag = panic "rtsBuildTag",
370 objectSuf = phaseInputExt StopLn,
371 hcSuf = phaseInputExt HCc,
374 outputFile = Nothing,
379 cmdlineFrameworks = [],
380 tmpDir = cDEFAULT_TMPDIR,
392 pgm_L = panic "pgm_L",
393 pgm_P = panic "pgm_P",
394 pgm_F = panic "pgm_F",
395 pgm_c = panic "pgm_c",
396 pgm_m = panic "pgm_m",
397 pgm_s = panic "pgm_s",
398 pgm_a = panic "pgm_a",
399 pgm_l = panic "pgm_l",
400 pgm_dll = panic "pgm_mkdll",
404 pkgState = panic "pkgState",
408 Opt_ReadUserPackageConf,
410 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
411 -- behaviour the default, to see if anyone notices
415 Opt_MonomorphismRestriction,
417 -- strictness is on by default, but this only
419 Opt_CSE, -- similarly for CSE.
420 Opt_FullLaziness, -- ...and for full laziness
422 Opt_DoLambdaEtaExpansion,
423 -- This one is important for a tiresome reason:
424 -- we want to make sure that the bindings for data
425 -- constructors are eta-expanded. This is probably
426 -- a good thing anyway, but it seems fragile.
430 -- and the default no-optimisation options:
431 Opt_IgnoreInterfacePragmas,
432 Opt_OmitInterfacePragmas
434 ] ++ standardWarnings,
436 log_action = \severity srcSpan style msg ->
438 SevInfo -> hPutStrLn stderr (show (msg style))
439 SevFatal -> hPutStrLn stderr (show (msg style))
440 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
446 0 | print errors & warnings only
447 1 | minimal verbosity: print "compiling M ... done." for each module.
448 2 | equivalent to -dshow-passes
449 3 | equivalent to existing "ghc -v"
450 4 | "ghc -v -ddump-most"
451 5 | "ghc -v -ddump-all"
454 dopt :: DynFlag -> DynFlags -> Bool
455 dopt f dflags = f `elem` (flags dflags)
457 dopt_set :: DynFlags -> DynFlag -> DynFlags
458 dopt_set dfs f = dfs{ flags = f : flags dfs }
460 dopt_unset :: DynFlags -> DynFlag -> DynFlags
461 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
463 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
464 getOpts dflags opts = reverse (opts dflags)
465 -- We add to the options from the front, so we need to reverse the list
467 getVerbFlag :: DynFlags -> String
469 | verbosity dflags >= 3 = "-v"
472 setObjectDir f d = d{ objectDir = f}
473 setHiDir f d = d{ hiDir = f}
474 setStubDir f d = d{ stubDir = f}
476 setObjectSuf f d = d{ objectSuf = f}
477 setHiSuf f d = d{ hiSuf = f}
478 setHcSuf f d = d{ hcSuf = f}
480 setOutputFile f d = d{ outputFile = f}
481 setOutputHi f d = d{ outputHi = f}
483 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
484 -- Config.hs should really use Option.
485 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
487 setPgmL f d = d{ pgm_L = f}
488 setPgmF f d = d{ pgm_F = f}
489 setPgmc f d = d{ pgm_c = (f,[])}
490 setPgmm f d = d{ pgm_m = (f,[])}
491 setPgms f d = d{ pgm_s = (f,[])}
492 setPgma f d = d{ pgm_a = (f,[])}
493 setPgml f d = d{ pgm_l = (f,[])}
494 setPgmdll f d = d{ pgm_dll = (f,[])}
496 addOptL f d = d{ opt_L = f : opt_L d}
497 addOptP f d = d{ opt_P = f : opt_P d}
498 addOptF f d = d{ opt_F = f : opt_F d}
499 addOptc f d = d{ opt_c = f : opt_c d}
500 addOptm f d = d{ opt_m = f : opt_m d}
501 addOpta f d = d{ opt_a = f : opt_a d}
502 addOptl f d = d{ opt_l = f : opt_l d}
503 addOptdll f d = d{ opt_dll = f : opt_dll d}
504 addOptdep f d = d{ opt_dep = f : opt_dep d}
506 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
508 -- -----------------------------------------------------------------------------
509 -- Command-line options
511 -- When invoking external tools as part of the compilation pipeline, we
512 -- pass these a sequence of options on the command-line. Rather than
513 -- just using a list of Strings, we use a type that allows us to distinguish
514 -- between filepaths and 'other stuff'. [The reason being, of course, that
515 -- this type gives us a handle on transforming filenames, and filenames only,
516 -- to whatever format they're expected to be on a particular platform.]
519 = FileOption -- an entry that _contains_ filename(s) / filepaths.
520 String -- a non-filepath prefix that shouldn't be
521 -- transformed (e.g., "/out=")
522 String -- the filepath/filename portion
525 -----------------------------------------------------------------------------
526 -- Setting the optimisation level
528 updOptLevel :: Int -> DynFlags -> DynFlags
529 -- Set dynflags appropriate to the optimisation level
532 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
533 else dfs2{ optLevel = n }
535 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
536 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
539 | n == 0 = opt_0_dopts
540 | otherwise = opt_1_dopts
543 | n == 0 = opt_1_dopts
544 | otherwise = opt_0_dopts
547 Opt_IgnoreInterfacePragmas,
548 Opt_OmitInterfacePragmas
557 -- -----------------------------------------------------------------------------
558 -- Standard sets of warning options
561 = [ Opt_WarnDeprecations,
562 Opt_WarnOverlappingPatterns,
563 Opt_WarnMissingFields,
564 Opt_WarnMissingMethods,
565 Opt_WarnDuplicateExports
569 = standardWarnings ++
570 [ Opt_WarnUnusedBinds,
571 Opt_WarnUnusedMatches,
572 Opt_WarnUnusedImports,
573 Opt_WarnIncompletePatterns,
579 [ Opt_WarnTypeDefaults,
580 Opt_WarnNameShadowing,
586 -- -----------------------------------------------------------------------------
587 -- CoreToDo: abstraction of core-to-core passes to run.
589 data CoreToDo -- These are diff core-to-core passes,
590 -- which may be invoked in any order,
591 -- as many times as you like.
593 = CoreDoSimplify -- The core-to-core simplifier.
596 -- Each run of the simplifier can take a different
597 -- set of simplifier-specific flags.
599 | CoreDoFloatOutwards FloatOutSwitches
604 | CoreDoWorkerWrapper
607 | CoreDoOldStrictness
610 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
611 -- matching this string
613 | CoreDoNothing -- useful when building up lists of these things
615 data SimplifierMode -- See comments in SimplMonad
619 data SimplifierSwitch
620 = MaxSimplifierIterations Int
623 data FloatOutSwitches
624 = FloatOutSw Bool -- True <=> float lambdas to top level
625 Bool -- True <=> float constants to top level,
626 -- even if they do not escape a lambda
629 -- The core-to-core pass ordering is derived from the DynFlags:
631 getCoreToDo :: DynFlags -> [CoreToDo]
633 | Just todo <- coreToDo dflags = todo -- set explicitly by user
634 | otherwise = core_todo
636 opt_level = optLevel dflags
637 max_iter = maxSimplIterations dflags
638 strictness = dopt Opt_Strictness dflags
639 full_laziness = dopt Opt_FullLaziness dflags
640 cse = dopt Opt_CSE dflags
641 rule_check = ruleCheck dflags
644 if opt_level == 0 then
646 CoreDoSimplify (SimplPhase 0) [
647 MaxSimplifierIterations max_iter
650 else {- opt_level >= 1 -} [
652 -- initial simplify: mk specialiser happy: minimum effort please
653 CoreDoSimplify SimplGently [
655 -- Don't inline anything till full laziness has bitten
656 -- In particular, inlining wrappers inhibits floating
657 -- e.g. ...(case f x of ...)...
658 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
659 -- ==> ...(case x of I# x# -> case fw x# of ...)...
660 -- and now the redex (f x) isn't floatable any more
661 -- Similarly, don't apply any rules until after full
662 -- laziness. Notably, list fusion can prevent floating.
664 NoCaseOfCase, -- Don't do case-of-case transformations.
665 -- This makes full laziness work better
666 MaxSimplifierIterations max_iter
669 -- Specialisation is best done before full laziness
670 -- so that overloaded functions have all their dictionary lambdas manifest
673 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
678 CoreDoSimplify (SimplPhase 2) [
679 -- Want to run with inline phase 2 after the specialiser to give
680 -- maximum chance for fusion to work before we inline build/augment
681 -- in phase 1. This made a difference in 'ansi' where an
682 -- overloaded function wasn't inlined till too late.
683 MaxSimplifierIterations max_iter
685 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
687 CoreDoSimplify (SimplPhase 1) [
688 -- Need inline-phase2 here so that build/augment get
689 -- inlined. I found that spectral/hartel/genfft lost some useful
690 -- strictness in the function sumcode' if augment is not inlined
691 -- before strictness analysis runs
692 MaxSimplifierIterations max_iter
694 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
696 CoreDoSimplify (SimplPhase 0) [
697 -- Phase 0: allow all Ids to be inlined now
698 -- This gets foldr inlined before strictness analysis
700 MaxSimplifierIterations 3
701 -- At least 3 iterations because otherwise we land up with
702 -- huge dead expressions because of an infelicity in the
704 -- let k = BIG in foldr k z xs
705 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
706 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
710 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
712 #ifdef OLD_STRICTNESS
715 if strictness then CoreDoStrictness else CoreDoNothing,
719 CoreDoSimplify (SimplPhase 0) [
720 MaxSimplifierIterations max_iter
723 if full_laziness then
724 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
725 True) -- Float constants
727 -- nofib/spectral/hartel/wang doubles in speed if you
728 -- do full laziness late in the day. It only happens
729 -- after fusion and other stuff, so the early pass doesn't
730 -- catch it. For the record, the redex is
731 -- f_el22 (f_el21 r_midblock)
734 -- We want CSE to follow the final full-laziness pass, because it may
735 -- succeed in commoning up things floated out by full laziness.
736 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
738 if cse then CoreCSE else CoreDoNothing,
742 -- Case-liberation for -O2. This should be after
743 -- strictness analysis and the simplification which follows it.
745 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
750 (if opt_level >= 2 then
752 CoreDoSimplify (SimplPhase 0) [
753 MaxSimplifierIterations max_iter
754 ], -- Run the simplifier after LiberateCase to vastly
755 -- reduce the possiblility of shadowing
756 -- Reason: see Note [Shadowing] in SpecConstr.lhs
764 -- Final clean-up simplification:
765 [ CoreDoSimplify (SimplPhase 0) [
766 MaxSimplifierIterations max_iter
770 -- -----------------------------------------------------------------------------
771 -- StgToDo: abstraction of stg-to-stg passes to run.
774 = StgDoMassageForProfiling -- should be (next to) last
775 -- There's also setStgVarInfo, but its absolute "lastness"
776 -- is so critical that it is hardwired in (no flag).
779 getStgToDo :: DynFlags -> [StgToDo]
781 | Just todo <- stgToDo dflags = todo -- set explicitly by user
784 stg_stats = dopt Opt_StgStats dflags
786 todo1 = if stg_stats then [D_stg_stats] else []
788 todo2 | WayProf `elem` wayNames dflags
789 = StgDoMassageForProfiling : todo1
793 -- -----------------------------------------------------------------------------
797 allFlags = map ('-':) $
798 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
799 map ("fno-"++) flags ++
801 where ok (PrefixPred _ _) = False
803 flags = map fst fFlags
805 dynamic_flags :: [(String, OptKind DynP)]
807 ( "n" , NoArg (setDynFlag Opt_DryRun) )
808 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
809 , ( "F" , NoArg (setDynFlag Opt_Pp))
810 , ( "#include" , HasArg (addCmdlineHCInclude) )
811 , ( "v" , OptIntSuffix setVerbosity )
813 ------- Specific phases --------------------------------------------
814 , ( "pgmL" , HasArg (upd . setPgmL) )
815 , ( "pgmP" , HasArg (upd . setPgmP) )
816 , ( "pgmF" , HasArg (upd . setPgmF) )
817 , ( "pgmc" , HasArg (upd . setPgmc) )
818 , ( "pgmm" , HasArg (upd . setPgmm) )
819 , ( "pgms" , HasArg (upd . setPgms) )
820 , ( "pgma" , HasArg (upd . setPgma) )
821 , ( "pgml" , HasArg (upd . setPgml) )
822 , ( "pgmdll" , HasArg (upd . setPgmdll) )
824 , ( "optL" , HasArg (upd . addOptL) )
825 , ( "optP" , HasArg (upd . addOptP) )
826 , ( "optF" , HasArg (upd . addOptF) )
827 , ( "optc" , HasArg (upd . addOptc) )
828 , ( "optm" , HasArg (upd . addOptm) )
829 , ( "opta" , HasArg (upd . addOpta) )
830 , ( "optl" , HasArg (upd . addOptl) )
831 , ( "optdll" , HasArg (upd . addOptdll) )
832 , ( "optdep" , HasArg (upd . addOptdep) )
834 , ( "split-objs" , NoArg (if can_split
835 then setDynFlag Opt_SplitObjs
838 -------- Linking ----------------------------------------------------
839 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
840 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
841 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
843 ------- Libraries ---------------------------------------------------
844 , ( "L" , Prefix addLibraryPath )
845 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
848 ------- Frameworks --------------------------------------------------
849 -- -framework-path should really be -F ...
850 , ( "framework-path" , HasArg addFrameworkPath )
851 , ( "framework" , HasArg (upd . addCmdlineFramework) )
853 ------- Output Redirection ------------------------------------------
854 , ( "odir" , HasArg (upd . setObjectDir . Just))
855 , ( "o" , SepArg (upd . setOutputFile . Just))
856 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
857 , ( "osuf" , HasArg (upd . setObjectSuf))
858 , ( "hcsuf" , HasArg (upd . setHcSuf))
859 , ( "hisuf" , HasArg (upd . setHiSuf))
860 , ( "hidir" , HasArg (upd . setHiDir . Just))
861 , ( "tmpdir" , HasArg (upd . setTmpDir))
862 , ( "stubdir" , HasArg (upd . setStubDir . Just))
864 ------- Keeping temporary files -------------------------------------
865 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
866 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
867 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
868 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
870 ------- Miscellaneous ----------------------------------------------
871 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
872 , ( "main-is" , SepArg setMainIs )
874 ------- recompilation checker --------------------------------------
875 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
876 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
878 ------- Packages ----------------------------------------------------
879 , ( "package-conf" , HasArg extraPkgConf_ )
880 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
881 , ( "package-name" , HasArg setPackageName )
882 , ( "package" , HasArg exposePackage )
883 , ( "hide-package" , HasArg hidePackage )
884 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
885 , ( "ignore-package" , HasArg ignorePackage )
886 , ( "syslib" , HasArg exposePackage ) -- for compatibility
888 ------ HsCpp opts ---------------------------------------------------
889 , ( "D", AnySuffix (upd . addOptP) )
890 , ( "U", AnySuffix (upd . addOptP) )
892 ------- Include/Import Paths ----------------------------------------
893 , ( "I" , Prefix addIncludePath)
894 , ( "i" , OptPrefix addImportPath )
896 ------ Debugging ----------------------------------------------------
897 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
899 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
900 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
901 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
902 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
903 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
904 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
905 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
906 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
907 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
908 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
909 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
910 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
911 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
912 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
913 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
914 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
915 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
916 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
917 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
918 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
919 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
920 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
921 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
922 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
923 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
924 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
925 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
926 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
927 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
928 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
929 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
930 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
931 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
932 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
933 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
934 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
935 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
936 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
937 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
938 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
939 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
940 setVerbosity (Just 2)) )
941 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
943 ------ Machine dependant (-m<blah>) stuff ---------------------------
945 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
946 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
947 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
949 ------ Warning opts -------------------------------------------------
950 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
951 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
952 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
953 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
954 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
956 ------ Optimisation flags ------------------------------------------
957 , ( "O" , NoArg (upd (setOptLevel 1)))
958 , ( "Onot" , NoArg (upd (setOptLevel 0)))
959 , ( "O" , PrefixPred (all isDigit)
960 (\f -> upd (setOptLevel (read f))))
962 , ( "fmax-simplifier-iterations",
963 PrefixPred (all isDigit)
965 dfs{ maxSimplIterations = read n })) )
968 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
970 ------ Compiler flags -----------------------------------------------
972 , ( "fno-code", NoArg (setTarget HscNothing))
973 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
974 , ( "fvia-c", NoArg (setTarget HscC) )
975 , ( "fvia-C", NoArg (setTarget HscC) )
976 , ( "filx", NoArg (setTarget HscILX) )
978 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
979 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
981 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
982 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
984 -- the rest of the -f* and -fno-* flags
985 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
986 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
989 -- these -f<blah> flags can all be reversed with -fno-<blah>
992 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
993 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
994 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
995 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
996 ( "warn-missing-fields", Opt_WarnMissingFields ),
997 ( "warn-missing-methods", Opt_WarnMissingMethods ),
998 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
999 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1000 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1001 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1002 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1003 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1004 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1005 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1006 ( "warn-deprecations", Opt_WarnDeprecations ),
1007 ( "warn-orphans", Opt_WarnOrphans ),
1008 ( "fi", Opt_FFI ), -- support `-ffi'...
1009 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1010 ( "arrows", Opt_Arrows ), -- arrow syntax
1011 ( "parr", Opt_PArr ),
1013 ( "implicit-prelude", Opt_ImplicitPrelude ),
1014 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1015 ( "bang-patterns", Opt_BangPatterns ),
1016 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1017 ( "mono-pat-binds", Opt_MonoPatBinds ),
1018 ( "implicit-params", Opt_ImplicitParams ),
1019 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1020 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1021 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1022 ( "generics", Opt_Generics ),
1023 ( "strictness", Opt_Strictness ),
1024 ( "full-laziness", Opt_FullLaziness ),
1026 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1027 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1028 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1029 ( "ignore-asserts", Opt_IgnoreAsserts ),
1030 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1031 ( "do-eta-reduction", Opt_DoEtaReduction ),
1032 ( "case-merge", Opt_CaseMerge ),
1033 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1034 ( "dicts-cheap", Opt_DictsCheap ),
1035 ( "excess-precision", Opt_ExcessPrecision ),
1036 ( "asm-mangling", Opt_DoAsmMangling )
1039 glasgowExtsFlags = [
1043 Opt_ScopedTypeVariables,
1046 isFFlag f = f `elem` (map fst fFlags)
1047 getFFlag f = fromJust (lookup f fFlags)
1049 -- -----------------------------------------------------------------------------
1050 -- Parsing the dynamic flags.
1052 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1053 parseDynamicFlags dflags args = do
1054 let ((leftover,errs),dflags')
1055 = runCmdLine (processArgs dynamic_flags args) dflags
1056 when (not (null errs)) $ do
1057 throwDyn (UsageError (unlines errs))
1058 return (dflags', leftover)
1061 type DynP = CmdLineP DynFlags
1063 upd :: (DynFlags -> DynFlags) -> DynP ()
1065 dfs <- getCmdLineState
1066 putCmdLineState $! (f dfs)
1068 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1069 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1070 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1072 setDumpFlag :: DynFlag -> OptKind DynP
1073 setDumpFlag dump_flag
1074 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1075 -- Whenver we -ddump, switch off the recompilation checker,
1076 -- else you don't see the dump!
1078 setVerbosity :: Maybe Int -> DynP ()
1079 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1081 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1083 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1086 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1088 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1090 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1092 | Nothing <- unpackPackageId pid
1093 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1095 = upd (\s -> s{ thisPackage = pid })
1097 pid = stringToPackageId p
1099 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1100 -- (-fvia-C, -fasm, -filx respectively).
1101 setTarget l = upd (\dfs -> case hscTarget dfs of
1102 HscC -> dfs{ hscTarget = l }
1103 HscAsm -> dfs{ hscTarget = l }
1104 HscILX -> dfs{ hscTarget = l }
1107 setOptLevel :: Int -> DynFlags -> DynFlags
1108 setOptLevel n dflags
1109 | hscTarget dflags == HscInterpreted && n > 0
1111 -- not in IO any more, oh well:
1112 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1114 = updOptLevel n dflags
1117 setMainIs :: String -> DynP ()
1119 | not (null main_fn) -- The arg looked like "Foo.baz"
1120 = upd $ \d -> d{ mainFunIs = Just main_fn,
1121 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1123 | isUpper (head main_mod) -- The arg looked like "Foo"
1124 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1126 | otherwise -- The arg looked like "baz"
1127 = upd $ \d -> d{ mainFunIs = Just main_mod }
1129 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1131 -----------------------------------------------------------------------------
1132 -- Paths & Libraries
1134 -- -i on its own deletes the import paths
1135 addImportPath "" = upd (\s -> s{importPaths = []})
1136 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1140 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1143 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1145 addFrameworkPath p =
1146 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1148 split_marker = ':' -- not configurable (ToDo)
1150 splitPathList :: String -> [String]
1151 splitPathList s = filter notNull (splitUp s)
1152 -- empty paths are ignored: there might be a trailing
1153 -- ':' in the initial list, for example. Empty paths can
1154 -- cause confusion when they are translated into -I options
1155 -- for passing to gcc.
1157 #ifndef mingw32_TARGET_OS
1158 splitUp xs = split split_marker xs
1160 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1162 -- That is, if "foo:bar:baz" is used, this interpreted as
1163 -- consisting of three entries, 'foo', 'bar', 'baz'.
1164 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1165 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1167 -- Notice that no attempt is made to fully replace the 'standard'
1168 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1169 -- that this will cause too much breakage for users & ':' will
1170 -- work fine even with DOS paths, if you're not insisting on being silly.
1173 splitUp (x:':':div:xs) | div `elem` dir_markers
1174 = ((x:':':div:p): splitUp rs)
1176 (p,rs) = findNextPath xs
1177 -- we used to check for existence of the path here, but that
1178 -- required the IO monad to be threaded through the command-line
1179 -- parser which is quite inconvenient. The
1180 splitUp xs = cons p (splitUp rs)
1182 (p,rs) = findNextPath xs
1187 -- will be called either when we've consumed nought or the
1188 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1189 -- finding the next split marker.
1191 case break (`elem` split_markers) xs of
1192 (p, d:ds) -> (p, ds)
1195 split_markers :: [Char]
1196 split_markers = [':', ';']
1198 dir_markers :: [Char]
1199 dir_markers = ['/', '\\']
1202 -- -----------------------------------------------------------------------------
1203 -- tmpDir, where we store temporary files.
1205 setTmpDir :: FilePath -> DynFlags -> DynFlags
1206 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1208 #if !defined(mingw32_HOST_OS)
1209 canonicalise p = normalisePath p
1211 -- Canonicalisation of temp path under win32 is a bit more
1212 -- involved: (a) strip trailing slash,
1213 -- (b) normalise slashes
1214 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1216 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1218 -- if we're operating under cygwin, and TMP/TEMP is of
1219 -- the form "/cygdrive/drive/path", translate this to
1220 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1221 -- understand /cygdrive paths.)
1223 | "/cygdrive/" `isPrefixOf` path =
1224 case drop (length "/cygdrive/") path of
1225 drive:xs@('/':_) -> drive:':':xs
1229 -- strip the trailing backslash (awful, but we only do this once).
1230 removeTrailingSlash path =
1237 -----------------------------------------------------------------------------
1238 -- Via-C compilation stuff
1240 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1241 [String]) -- for registerised HC compilations
1242 machdepCCOpts dflags
1243 #if alpha_TARGET_ARCH
1245 #ifdef HAVE_THREADED_RTS_SUPPORT
1249 -- For now, to suppress the gcc warning "call-clobbered
1250 -- register used for global register variable", we simply
1251 -- disable all warnings altogether using the -w flag. Oh well.
1253 #elif hppa_TARGET_ARCH
1254 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1255 -- (very nice, but too bad the HP /usr/include files don't agree.)
1256 = ( ["-D_HPUX_SOURCE"], [] )
1258 #elif m68k_TARGET_ARCH
1259 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1260 -- popping of args to routines to be explicit; if we let things
1261 -- be deferred 'til after an STGJUMP, imminent death is certain!
1263 -- -fomit-frame-pointer : *don't*
1264 -- It's better to have a6 completely tied up being a frame pointer
1265 -- rather than let GCC pick random things to do with it.
1266 -- (If we want to steal a6, then we would try to do things
1267 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1268 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1270 #elif i386_TARGET_ARCH
1271 -- -fno-defer-pop : basically the same game as for m68k
1273 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1274 -- the fp (%ebp) for our register maps.
1275 = let n_regs = stolen_x86_regs dflags
1278 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1279 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1282 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1283 -- Some gccs are configured with
1284 -- -momit-leaf-frame-pointer on by default, and it
1285 -- apparently takes precedence over
1286 -- -fomit-frame-pointer, so we disable it first here.
1287 "-mno-omit-leaf-frame-pointer",
1289 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1290 "-fno-unit-at-a-time",
1291 -- unit-at-a-time doesn't do us any good, and screws
1292 -- up -split-objs by moving the split markers around.
1293 -- It's only turned on with -O2, but put it here just
1294 -- in case someone uses -optc-O2.
1296 "-fomit-frame-pointer",
1297 -- we want -fno-builtin, because when gcc inlines
1298 -- built-in functions like memcpy() it tends to
1299 -- run out of registers, requiring -monly-n-regs
1301 "-DSTOLEN_X86_REGS="++show n_regs ]
1304 #elif ia64_TARGET_ARCH
1305 = ( [], ["-fomit-frame-pointer", "-G0"] )
1307 #elif x86_64_TARGET_ARCH
1308 = ( [], ["-fomit-frame-pointer",
1309 "-fno-asynchronous-unwind-tables",
1310 -- the unwind tables are unnecessary for HC code,
1311 -- and get in the way of -split-objs. Another option
1312 -- would be to throw them away in the mangler, but this
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.
1322 -- calling builtins like strlen() using the FFI can
1323 -- cause gcc to run out of regs, so use the external
1327 #elif mips_TARGET_ARCH
1328 = ( ["-static"], [] )
1330 #elif sparc_TARGET_ARCH
1332 -- For now, to suppress the gcc warning "call-clobbered
1333 -- register used for global register variable", we simply
1334 -- disable all warnings altogether using the -w flag. Oh well.
1336 #elif powerpc_apple_darwin_TARGET
1338 -- Disable Apple's precompiling preprocessor. It's a great thing
1339 -- for "normal" programs, but it doesn't support register variable
1341 = ( [], ["-no-cpp-precomp"] )
1346 picCCOpts :: DynFlags -> [String]
1348 #if darwin_TARGET_OS
1349 -- Apple prefers to do things the other way round.
1350 -- PIC is on by default.
1351 -- -mdynamic-no-pic:
1352 -- Turn off PIC code generation.
1354 -- Don't generate "common" symbols - these are unwanted
1355 -- in dynamic libraries.
1360 = ["-mdynamic-no-pic"]
1361 #elif mingw32_TARGET_OS
1362 -- no -fPIC for Windows
1371 -- -----------------------------------------------------------------------------
1376 #if defined(i386_TARGET_ARCH) \
1377 || defined(x86_64_TARGET_ARCH) \
1378 || defined(alpha_TARGET_ARCH) \
1379 || defined(hppa_TARGET_ARCH) \
1380 || defined(m68k_TARGET_ARCH) \
1381 || defined(mips_TARGET_ARCH) \
1382 || defined(powerpc_TARGET_ARCH) \
1383 || defined(rs6000_TARGET_ARCH) \
1384 || defined(sparc_TARGET_ARCH)