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
157 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
160 | Opt_PArr -- Syntactic support for parallel arrays
161 | Opt_Arrows -- Arrow-notation syntax
165 | Opt_ImplicitPrelude
166 | Opt_ScopedTypeVariables
173 | Opt_IgnoreInterfacePragmas
174 | Opt_OmitInterfacePragmas
175 | Opt_DoLambdaEtaExpansion
177 | Opt_IgnoreBreakpoints
180 | Opt_UnboxStrictFields
189 | Opt_ExcessPrecision
190 | Opt_ReadUserPackageConf
194 | Opt_HideAllPackages
205 data DynFlags = DynFlags {
208 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
209 stgToDo :: Maybe [StgToDo], -- similarly
210 hscTarget :: HscTarget,
211 hscOutName :: String, -- name of the output file
212 extCoreName :: String, -- name of the .core output file
213 verbosity :: Int, -- verbosity level
214 optLevel :: Int, -- optimisation level
215 maxSimplIterations :: Int, -- max simplifier iterations
216 ruleCheck :: Maybe String,
217 stolen_x86_regs :: Int,
218 cmdlineHcIncludes :: [String], -- -#includes
219 importPaths :: [FilePath],
221 mainFunIs :: Maybe String,
222 ctxtStkDepth :: Int, -- Typechecker context stack depth
224 thisPackage :: PackageId,
227 wayNames :: [WayName], -- way flags from the cmd line
228 buildTag :: String, -- the global "way" (eg. "p" for prof)
229 rtsBuildTag :: String, -- the RTS "way"
232 objectDir :: Maybe String,
233 hiDir :: Maybe String,
234 stubDir :: Maybe String,
240 outputFile :: Maybe String,
241 outputHi :: Maybe String,
243 includePaths :: [String],
244 libraryPaths :: [String],
245 frameworkPaths :: [String], -- used on darwin only
246 cmdlineFrameworks :: [String], -- ditto
247 tmpDir :: String, -- no trailing '/'
249 -- options for particular phases
260 -- commands for particular phases
262 pgm_P :: (String,[Option]),
264 pgm_c :: (String,[Option]),
265 pgm_m :: (String,[Option]),
266 pgm_s :: (String,[Option]),
267 pgm_a :: (String,[Option]),
268 pgm_l :: (String,[Option]),
269 pgm_dll :: (String,[Option]),
272 extraPkgConfs :: [FilePath],
273 -- The -package-conf flags given on the command line, in the order
276 packageFlags :: [PackageFlag],
277 -- The -package and -hide-package flags from the command-line
280 pkgState :: PackageState,
286 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
299 = BatchCompile -- | @ghc --make Main@
300 | Interactive -- | @ghc --interactive@
301 | OneShot -- | @ghc -c Foo.hs@
302 | JustTypecheck -- | Development environemnts, refactorer, etc.
306 isOneShot :: GhcMode -> Bool
307 isOneShot OneShot = True
308 isOneShot _other = False
310 data GhcLink -- What to do in the link step, if there is one
311 = -- Only relevant for modes
312 -- DoMake and StopBefore StopLn
313 NoLink -- Don't link at all
314 | StaticLink -- Ordinary linker [the default]
315 | MkDLL -- Make a DLL
317 isNoLink :: GhcLink -> Bool
318 isNoLink NoLink = True
319 isNoLink other = False
322 = ExposePackage String
324 | IgnorePackage String
327 | cGhcWithNativeCodeGen == "YES" = HscAsm
330 initDynFlags dflags = do
331 -- someday these will be dynamic flags
332 ways <- readIORef v_Ways
333 build_tag <- readIORef v_Build_tag
334 rts_build_tag <- readIORef v_RTS_Build_tag
337 buildTag = build_tag,
338 rtsBuildTag = rts_build_tag
344 ghcLink = StaticLink,
347 hscTarget = defaultHscTarget,
352 maxSimplIterations = 4,
355 cmdlineHcIncludes = [],
359 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
361 thisPackage = mainPackageId,
363 wayNames = panic "ways",
364 buildTag = panic "buildTag",
365 rtsBuildTag = panic "rtsBuildTag",
371 objectSuf = phaseInputExt StopLn,
372 hcSuf = phaseInputExt HCc,
375 outputFile = Nothing,
380 cmdlineFrameworks = [],
381 tmpDir = cDEFAULT_TMPDIR,
393 pgm_L = panic "pgm_L",
394 pgm_P = panic "pgm_P",
395 pgm_F = panic "pgm_F",
396 pgm_c = panic "pgm_c",
397 pgm_m = panic "pgm_m",
398 pgm_s = panic "pgm_s",
399 pgm_a = panic "pgm_a",
400 pgm_l = panic "pgm_l",
401 pgm_dll = panic "pgm_mkdll",
405 pkgState = panic "pkgState",
409 Opt_ReadUserPackageConf,
411 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
412 -- behaviour the default, to see if anyone notices
416 Opt_MonomorphismRestriction,
418 -- strictness is on by default, but this only
420 Opt_CSE, -- similarly for CSE.
421 Opt_FullLaziness, -- ...and for full laziness
423 Opt_DoLambdaEtaExpansion,
424 -- This one is important for a tiresome reason:
425 -- we want to make sure that the bindings for data
426 -- constructors are eta-expanded. This is probably
427 -- a good thing anyway, but it seems fragile.
431 -- and the default no-optimisation options:
432 Opt_IgnoreInterfacePragmas,
433 Opt_OmitInterfacePragmas
435 ] ++ standardWarnings,
437 log_action = \severity srcSpan style msg ->
439 SevInfo -> hPutStrLn stderr (show (msg style))
440 SevFatal -> hPutStrLn stderr (show (msg style))
441 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
447 0 | print errors & warnings only
448 1 | minimal verbosity: print "compiling M ... done." for each module.
449 2 | equivalent to -dshow-passes
450 3 | equivalent to existing "ghc -v"
451 4 | "ghc -v -ddump-most"
452 5 | "ghc -v -ddump-all"
455 dopt :: DynFlag -> DynFlags -> Bool
456 dopt f dflags = f `elem` (flags dflags)
458 dopt_set :: DynFlags -> DynFlag -> DynFlags
459 dopt_set dfs f = dfs{ flags = f : flags dfs }
461 dopt_unset :: DynFlags -> DynFlag -> DynFlags
462 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
464 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
465 getOpts dflags opts = reverse (opts dflags)
466 -- We add to the options from the front, so we need to reverse the list
468 getVerbFlag :: DynFlags -> String
470 | verbosity dflags >= 3 = "-v"
473 setObjectDir f d = d{ objectDir = f}
474 setHiDir f d = d{ hiDir = f}
475 setStubDir f d = d{ stubDir = f}
477 setObjectSuf f d = d{ objectSuf = f}
478 setHiSuf f d = d{ hiSuf = f}
479 setHcSuf f d = d{ hcSuf = f}
481 setOutputFile f d = d{ outputFile = f}
482 setOutputHi f d = d{ outputHi = f}
484 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
485 -- Config.hs should really use Option.
486 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
488 setPgmL f d = d{ pgm_L = f}
489 setPgmF f d = d{ pgm_F = f}
490 setPgmc f d = d{ pgm_c = (f,[])}
491 setPgmm f d = d{ pgm_m = (f,[])}
492 setPgms f d = d{ pgm_s = (f,[])}
493 setPgma f d = d{ pgm_a = (f,[])}
494 setPgml f d = d{ pgm_l = (f,[])}
495 setPgmdll f d = d{ pgm_dll = (f,[])}
497 addOptL f d = d{ opt_L = f : opt_L d}
498 addOptP f d = d{ opt_P = f : opt_P d}
499 addOptF f d = d{ opt_F = f : opt_F d}
500 addOptc f d = d{ opt_c = f : opt_c d}
501 addOptm f d = d{ opt_m = f : opt_m d}
502 addOpta f d = d{ opt_a = f : opt_a d}
503 addOptl f d = d{ opt_l = f : opt_l d}
504 addOptdll f d = d{ opt_dll = f : opt_dll d}
505 addOptdep f d = d{ opt_dep = f : opt_dep d}
507 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
509 -- -----------------------------------------------------------------------------
510 -- Command-line options
512 -- When invoking external tools as part of the compilation pipeline, we
513 -- pass these a sequence of options on the command-line. Rather than
514 -- just using a list of Strings, we use a type that allows us to distinguish
515 -- between filepaths and 'other stuff'. [The reason being, of course, that
516 -- this type gives us a handle on transforming filenames, and filenames only,
517 -- to whatever format they're expected to be on a particular platform.]
520 = FileOption -- an entry that _contains_ filename(s) / filepaths.
521 String -- a non-filepath prefix that shouldn't be
522 -- transformed (e.g., "/out=")
523 String -- the filepath/filename portion
526 -----------------------------------------------------------------------------
527 -- Setting the optimisation level
529 updOptLevel :: Int -> DynFlags -> DynFlags
530 -- Set dynflags appropriate to the optimisation level
533 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
534 else dfs2{ optLevel = n }
536 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
537 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
540 | n == 0 = opt_0_dopts
541 | otherwise = opt_1_dopts
544 | n == 0 = opt_1_dopts
545 | otherwise = opt_0_dopts
548 Opt_IgnoreInterfacePragmas,
549 Opt_OmitInterfacePragmas
558 -- -----------------------------------------------------------------------------
559 -- Standard sets of warning options
562 = [ Opt_WarnDeprecations,
563 Opt_WarnOverlappingPatterns,
564 Opt_WarnMissingFields,
565 Opt_WarnMissingMethods,
566 Opt_WarnDuplicateExports
570 = standardWarnings ++
571 [ Opt_WarnUnusedBinds,
572 Opt_WarnUnusedMatches,
573 Opt_WarnUnusedImports,
574 Opt_WarnIncompletePatterns,
580 [ Opt_WarnTypeDefaults,
581 Opt_WarnNameShadowing,
587 -- -----------------------------------------------------------------------------
588 -- CoreToDo: abstraction of core-to-core passes to run.
590 data CoreToDo -- These are diff core-to-core passes,
591 -- which may be invoked in any order,
592 -- as many times as you like.
594 = CoreDoSimplify -- The core-to-core simplifier.
597 -- Each run of the simplifier can take a different
598 -- set of simplifier-specific flags.
600 | CoreDoFloatOutwards FloatOutSwitches
605 | CoreDoWorkerWrapper
608 | CoreDoOldStrictness
611 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
612 -- matching this string
614 | CoreDoNothing -- useful when building up lists of these things
616 data SimplifierMode -- See comments in SimplMonad
620 data SimplifierSwitch
621 = MaxSimplifierIterations Int
624 data FloatOutSwitches
625 = FloatOutSw Bool -- True <=> float lambdas to top level
626 Bool -- True <=> float constants to top level,
627 -- even if they do not escape a lambda
630 -- The core-to-core pass ordering is derived from the DynFlags:
632 getCoreToDo :: DynFlags -> [CoreToDo]
634 | Just todo <- coreToDo dflags = todo -- set explicitly by user
635 | otherwise = core_todo
637 opt_level = optLevel dflags
638 max_iter = maxSimplIterations dflags
639 strictness = dopt Opt_Strictness dflags
640 full_laziness = dopt Opt_FullLaziness dflags
641 cse = dopt Opt_CSE dflags
642 rule_check = ruleCheck dflags
645 if opt_level == 0 then
647 CoreDoSimplify (SimplPhase 0) [
648 MaxSimplifierIterations max_iter
651 else {- opt_level >= 1 -} [
653 -- initial simplify: mk specialiser happy: minimum effort please
654 CoreDoSimplify SimplGently [
656 -- Don't inline anything till full laziness has bitten
657 -- In particular, inlining wrappers inhibits floating
658 -- e.g. ...(case f x of ...)...
659 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
660 -- ==> ...(case x of I# x# -> case fw x# of ...)...
661 -- and now the redex (f x) isn't floatable any more
662 -- Similarly, don't apply any rules until after full
663 -- laziness. Notably, list fusion can prevent floating.
665 NoCaseOfCase, -- Don't do case-of-case transformations.
666 -- This makes full laziness work better
667 MaxSimplifierIterations max_iter
670 -- Specialisation is best done before full laziness
671 -- so that overloaded functions have all their dictionary lambdas manifest
674 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
679 CoreDoSimplify (SimplPhase 2) [
680 -- Want to run with inline phase 2 after the specialiser to give
681 -- maximum chance for fusion to work before we inline build/augment
682 -- in phase 1. This made a difference in 'ansi' where an
683 -- overloaded function wasn't inlined till too late.
684 MaxSimplifierIterations max_iter
686 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
688 CoreDoSimplify (SimplPhase 1) [
689 -- Need inline-phase2 here so that build/augment get
690 -- inlined. I found that spectral/hartel/genfft lost some useful
691 -- strictness in the function sumcode' if augment is not inlined
692 -- before strictness analysis runs
693 MaxSimplifierIterations max_iter
695 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
697 CoreDoSimplify (SimplPhase 0) [
698 -- Phase 0: allow all Ids to be inlined now
699 -- This gets foldr inlined before strictness analysis
701 MaxSimplifierIterations 3
702 -- At least 3 iterations because otherwise we land up with
703 -- huge dead expressions because of an infelicity in the
705 -- let k = BIG in foldr k z xs
706 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
707 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
711 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
713 #ifdef OLD_STRICTNESS
716 if strictness then CoreDoStrictness else CoreDoNothing,
720 CoreDoSimplify (SimplPhase 0) [
721 MaxSimplifierIterations max_iter
724 if full_laziness then
725 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
726 True) -- Float constants
728 -- nofib/spectral/hartel/wang doubles in speed if you
729 -- do full laziness late in the day. It only happens
730 -- after fusion and other stuff, so the early pass doesn't
731 -- catch it. For the record, the redex is
732 -- f_el22 (f_el21 r_midblock)
735 -- We want CSE to follow the final full-laziness pass, because it may
736 -- succeed in commoning up things floated out by full laziness.
737 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
739 if cse then CoreCSE else CoreDoNothing,
743 -- Case-liberation for -O2. This should be after
744 -- strictness analysis and the simplification which follows it.
746 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
751 (if opt_level >= 2 then
753 CoreDoSimplify (SimplPhase 0) [
754 MaxSimplifierIterations max_iter
755 ], -- Run the simplifier after LiberateCase to vastly
756 -- reduce the possiblility of shadowing
757 -- Reason: see Note [Shadowing] in SpecConstr.lhs
765 -- Final clean-up simplification:
766 [ CoreDoSimplify (SimplPhase 0) [
767 MaxSimplifierIterations max_iter
771 -- -----------------------------------------------------------------------------
772 -- StgToDo: abstraction of stg-to-stg passes to run.
775 = StgDoMassageForProfiling -- should be (next to) last
776 -- There's also setStgVarInfo, but its absolute "lastness"
777 -- is so critical that it is hardwired in (no flag).
780 getStgToDo :: DynFlags -> [StgToDo]
782 | Just todo <- stgToDo dflags = todo -- set explicitly by user
785 stg_stats = dopt Opt_StgStats dflags
787 todo1 = if stg_stats then [D_stg_stats] else []
789 todo2 | WayProf `elem` wayNames dflags
790 = StgDoMassageForProfiling : todo1
794 -- -----------------------------------------------------------------------------
798 allFlags = map ('-':) $
799 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
800 map ("fno-"++) flags ++
802 where ok (PrefixPred _ _) = False
804 flags = map fst fFlags
806 dynamic_flags :: [(String, OptKind DynP)]
808 ( "n" , NoArg (setDynFlag Opt_DryRun) )
809 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
810 , ( "F" , NoArg (setDynFlag Opt_Pp))
811 , ( "#include" , HasArg (addCmdlineHCInclude) )
812 , ( "v" , OptIntSuffix setVerbosity )
814 ------- Specific phases --------------------------------------------
815 , ( "pgmL" , HasArg (upd . setPgmL) )
816 , ( "pgmP" , HasArg (upd . setPgmP) )
817 , ( "pgmF" , HasArg (upd . setPgmF) )
818 , ( "pgmc" , HasArg (upd . setPgmc) )
819 , ( "pgmm" , HasArg (upd . setPgmm) )
820 , ( "pgms" , HasArg (upd . setPgms) )
821 , ( "pgma" , HasArg (upd . setPgma) )
822 , ( "pgml" , HasArg (upd . setPgml) )
823 , ( "pgmdll" , HasArg (upd . setPgmdll) )
825 , ( "optL" , HasArg (upd . addOptL) )
826 , ( "optP" , HasArg (upd . addOptP) )
827 , ( "optF" , HasArg (upd . addOptF) )
828 , ( "optc" , HasArg (upd . addOptc) )
829 , ( "optm" , HasArg (upd . addOptm) )
830 , ( "opta" , HasArg (upd . addOpta) )
831 , ( "optl" , HasArg (upd . addOptl) )
832 , ( "optdll" , HasArg (upd . addOptdll) )
833 , ( "optdep" , HasArg (upd . addOptdep) )
835 , ( "split-objs" , NoArg (if can_split
836 then setDynFlag Opt_SplitObjs
839 -------- Linking ----------------------------------------------------
840 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
841 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
842 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
844 ------- Libraries ---------------------------------------------------
845 , ( "L" , Prefix addLibraryPath )
846 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
849 ------- Frameworks --------------------------------------------------
850 -- -framework-path should really be -F ...
851 , ( "framework-path" , HasArg addFrameworkPath )
852 , ( "framework" , HasArg (upd . addCmdlineFramework) )
854 ------- Output Redirection ------------------------------------------
855 , ( "odir" , HasArg (upd . setObjectDir . Just))
856 , ( "o" , SepArg (upd . setOutputFile . Just))
857 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
858 , ( "osuf" , HasArg (upd . setObjectSuf))
859 , ( "hcsuf" , HasArg (upd . setHcSuf))
860 , ( "hisuf" , HasArg (upd . setHiSuf))
861 , ( "hidir" , HasArg (upd . setHiDir . Just))
862 , ( "tmpdir" , HasArg (upd . setTmpDir))
863 , ( "stubdir" , HasArg (upd . setStubDir . Just))
865 ------- Keeping temporary files -------------------------------------
866 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
867 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
868 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
869 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
871 ------- Miscellaneous ----------------------------------------------
872 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
873 , ( "main-is" , SepArg setMainIs )
875 ------- recompilation checker --------------------------------------
876 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
877 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
879 ------- Packages ----------------------------------------------------
880 , ( "package-conf" , HasArg extraPkgConf_ )
881 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
882 , ( "package-name" , HasArg setPackageName )
883 , ( "package" , HasArg exposePackage )
884 , ( "hide-package" , HasArg hidePackage )
885 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
886 , ( "ignore-package" , HasArg ignorePackage )
887 , ( "syslib" , HasArg exposePackage ) -- for compatibility
889 ------ HsCpp opts ---------------------------------------------------
890 , ( "D", AnySuffix (upd . addOptP) )
891 , ( "U", AnySuffix (upd . addOptP) )
893 ------- Include/Import Paths ----------------------------------------
894 , ( "I" , Prefix addIncludePath)
895 , ( "i" , OptPrefix addImportPath )
897 ------ Debugging ----------------------------------------------------
898 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
900 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
901 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
902 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
903 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
904 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
905 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
906 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
907 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
908 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
909 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
910 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
911 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
912 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
913 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
914 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
915 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
916 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
917 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
918 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
919 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
920 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
921 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
922 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
923 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
924 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
925 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
926 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
927 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
928 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
929 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
930 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
931 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
932 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
933 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
934 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
935 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
936 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
937 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
938 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
939 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
940 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
941 setVerbosity (Just 2)) )
942 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
944 ------ Machine dependant (-m<blah>) stuff ---------------------------
946 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
947 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
948 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
950 ------ Warning opts -------------------------------------------------
951 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
952 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
953 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
954 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
955 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
957 ------ Optimisation flags ------------------------------------------
958 , ( "O" , NoArg (upd (setOptLevel 1)))
959 , ( "Onot" , NoArg (upd (setOptLevel 0)))
960 , ( "O" , PrefixPred (all isDigit)
961 (\f -> upd (setOptLevel (read f))))
963 , ( "fmax-simplifier-iterations",
964 PrefixPred (all isDigit)
966 dfs{ maxSimplIterations = read n })) )
969 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
971 ------ Compiler flags -----------------------------------------------
973 , ( "fno-code", NoArg (setTarget HscNothing))
974 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
975 , ( "fvia-c", NoArg (setTarget HscC) )
976 , ( "fvia-C", NoArg (setTarget HscC) )
977 , ( "filx", NoArg (setTarget HscILX) )
979 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
980 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
982 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
983 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
985 -- the rest of the -f* and -fno-* flags
986 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
987 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
990 -- these -f<blah> flags can all be reversed with -fno-<blah>
993 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
994 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
995 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
996 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
997 ( "warn-missing-fields", Opt_WarnMissingFields ),
998 ( "warn-missing-methods", Opt_WarnMissingMethods ),
999 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1000 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1001 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1002 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1003 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1004 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1005 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1006 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1007 ( "warn-deprecations", Opt_WarnDeprecations ),
1008 ( "warn-orphans", Opt_WarnOrphans ),
1009 ( "fi", Opt_FFI ), -- support `-ffi'...
1010 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1011 ( "arrows", Opt_Arrows ), -- arrow syntax
1012 ( "parr", Opt_PArr ),
1014 ( "implicit-prelude", Opt_ImplicitPrelude ),
1015 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1016 ( "bang-patterns", Opt_BangPatterns ),
1017 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1018 ( "mono-pat-binds", Opt_MonoPatBinds ),
1019 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1020 ( "implicit-params", Opt_ImplicitParams ),
1021 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1022 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1023 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1024 ( "generics", Opt_Generics ),
1025 ( "strictness", Opt_Strictness ),
1026 ( "full-laziness", Opt_FullLaziness ),
1028 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1029 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1030 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1031 ( "ignore-asserts", Opt_IgnoreAsserts ),
1032 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1033 ( "do-eta-reduction", Opt_DoEtaReduction ),
1034 ( "case-merge", Opt_CaseMerge ),
1035 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1036 ( "dicts-cheap", Opt_DictsCheap ),
1037 ( "excess-precision", Opt_ExcessPrecision ),
1038 ( "asm-mangling", Opt_DoAsmMangling )
1041 glasgowExtsFlags = [
1045 Opt_ScopedTypeVariables,
1048 isFFlag f = f `elem` (map fst fFlags)
1049 getFFlag f = fromJust (lookup f fFlags)
1051 -- -----------------------------------------------------------------------------
1052 -- Parsing the dynamic flags.
1054 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1055 parseDynamicFlags dflags args = do
1056 let ((leftover,errs),dflags')
1057 = runCmdLine (processArgs dynamic_flags args) dflags
1058 when (not (null errs)) $ do
1059 throwDyn (UsageError (unlines errs))
1060 return (dflags', leftover)
1063 type DynP = CmdLineP DynFlags
1065 upd :: (DynFlags -> DynFlags) -> DynP ()
1067 dfs <- getCmdLineState
1068 putCmdLineState $! (f dfs)
1070 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1071 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1072 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1074 setDumpFlag :: DynFlag -> OptKind DynP
1075 setDumpFlag dump_flag
1076 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1077 -- Whenver we -ddump, switch off the recompilation checker,
1078 -- else you don't see the dump!
1080 setVerbosity :: Maybe Int -> DynP ()
1081 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1083 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1085 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1088 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1090 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1092 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1094 | Nothing <- unpackPackageId pid
1095 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1097 = upd (\s -> s{ thisPackage = pid })
1099 pid = stringToPackageId p
1101 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1102 -- (-fvia-C, -fasm, -filx respectively).
1103 setTarget l = upd (\dfs -> case hscTarget dfs of
1104 HscC -> dfs{ hscTarget = l }
1105 HscAsm -> dfs{ hscTarget = l }
1106 HscILX -> dfs{ hscTarget = l }
1109 setOptLevel :: Int -> DynFlags -> DynFlags
1110 setOptLevel n dflags
1111 | hscTarget dflags == HscInterpreted && n > 0
1113 -- not in IO any more, oh well:
1114 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1116 = updOptLevel n dflags
1119 setMainIs :: String -> DynP ()
1121 | not (null main_fn) -- The arg looked like "Foo.baz"
1122 = upd $ \d -> d{ mainFunIs = Just main_fn,
1123 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1125 | isUpper (head main_mod) -- The arg looked like "Foo"
1126 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1128 | otherwise -- The arg looked like "baz"
1129 = upd $ \d -> d{ mainFunIs = Just main_mod }
1131 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1133 -----------------------------------------------------------------------------
1134 -- Paths & Libraries
1136 -- -i on its own deletes the import paths
1137 addImportPath "" = upd (\s -> s{importPaths = []})
1138 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1142 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1145 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1147 addFrameworkPath p =
1148 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1150 split_marker = ':' -- not configurable (ToDo)
1152 splitPathList :: String -> [String]
1153 splitPathList s = filter notNull (splitUp s)
1154 -- empty paths are ignored: there might be a trailing
1155 -- ':' in the initial list, for example. Empty paths can
1156 -- cause confusion when they are translated into -I options
1157 -- for passing to gcc.
1159 #ifndef mingw32_TARGET_OS
1160 splitUp xs = split split_marker xs
1162 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1164 -- That is, if "foo:bar:baz" is used, this interpreted as
1165 -- consisting of three entries, 'foo', 'bar', 'baz'.
1166 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1167 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1169 -- Notice that no attempt is made to fully replace the 'standard'
1170 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1171 -- that this will cause too much breakage for users & ':' will
1172 -- work fine even with DOS paths, if you're not insisting on being silly.
1175 splitUp (x:':':div:xs) | div `elem` dir_markers
1176 = ((x:':':div:p): splitUp rs)
1178 (p,rs) = findNextPath xs
1179 -- we used to check for existence of the path here, but that
1180 -- required the IO monad to be threaded through the command-line
1181 -- parser which is quite inconvenient. The
1182 splitUp xs = cons p (splitUp rs)
1184 (p,rs) = findNextPath xs
1189 -- will be called either when we've consumed nought or the
1190 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1191 -- finding the next split marker.
1193 case break (`elem` split_markers) xs of
1194 (p, d:ds) -> (p, ds)
1197 split_markers :: [Char]
1198 split_markers = [':', ';']
1200 dir_markers :: [Char]
1201 dir_markers = ['/', '\\']
1204 -- -----------------------------------------------------------------------------
1205 -- tmpDir, where we store temporary files.
1207 setTmpDir :: FilePath -> DynFlags -> DynFlags
1208 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1210 #if !defined(mingw32_HOST_OS)
1211 canonicalise p = normalisePath p
1213 -- Canonicalisation of temp path under win32 is a bit more
1214 -- involved: (a) strip trailing slash,
1215 -- (b) normalise slashes
1216 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1218 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1220 -- if we're operating under cygwin, and TMP/TEMP is of
1221 -- the form "/cygdrive/drive/path", translate this to
1222 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1223 -- understand /cygdrive paths.)
1225 | "/cygdrive/" `isPrefixOf` path =
1226 case drop (length "/cygdrive/") path of
1227 drive:xs@('/':_) -> drive:':':xs
1231 -- strip the trailing backslash (awful, but we only do this once).
1232 removeTrailingSlash path =
1239 -----------------------------------------------------------------------------
1240 -- Via-C compilation stuff
1242 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1243 [String]) -- for registerised HC compilations
1244 machdepCCOpts dflags
1245 #if alpha_TARGET_ARCH
1247 #ifdef HAVE_THREADED_RTS_SUPPORT
1251 -- For now, to suppress the gcc warning "call-clobbered
1252 -- register used for global register variable", we simply
1253 -- disable all warnings altogether using the -w flag. Oh well.
1255 #elif hppa_TARGET_ARCH
1256 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1257 -- (very nice, but too bad the HP /usr/include files don't agree.)
1258 = ( ["-D_HPUX_SOURCE"], [] )
1260 #elif m68k_TARGET_ARCH
1261 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1262 -- popping of args to routines to be explicit; if we let things
1263 -- be deferred 'til after an STGJUMP, imminent death is certain!
1265 -- -fomit-frame-pointer : *don't*
1266 -- It's better to have a6 completely tied up being a frame pointer
1267 -- rather than let GCC pick random things to do with it.
1268 -- (If we want to steal a6, then we would try to do things
1269 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1270 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1272 #elif i386_TARGET_ARCH
1273 -- -fno-defer-pop : basically the same game as for m68k
1275 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1276 -- the fp (%ebp) for our register maps.
1277 = let n_regs = stolen_x86_regs dflags
1280 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1281 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1284 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1285 -- Some gccs are configured with
1286 -- -momit-leaf-frame-pointer on by default, and it
1287 -- apparently takes precedence over
1288 -- -fomit-frame-pointer, so we disable it first here.
1289 "-mno-omit-leaf-frame-pointer",
1291 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1292 "-fno-unit-at-a-time",
1293 -- unit-at-a-time doesn't do us any good, and screws
1294 -- up -split-objs by moving the split markers around.
1295 -- It's only turned on with -O2, but put it here just
1296 -- in case someone uses -optc-O2.
1298 "-fomit-frame-pointer",
1299 -- we want -fno-builtin, because when gcc inlines
1300 -- built-in functions like memcpy() it tends to
1301 -- run out of registers, requiring -monly-n-regs
1303 "-DSTOLEN_X86_REGS="++show n_regs ]
1306 #elif ia64_TARGET_ARCH
1307 = ( [], ["-fomit-frame-pointer", "-G0"] )
1309 #elif x86_64_TARGET_ARCH
1310 = ( [], ["-fomit-frame-pointer",
1311 "-fno-asynchronous-unwind-tables",
1312 -- the unwind tables are unnecessary for HC code,
1313 -- and get in the way of -split-objs. Another option
1314 -- would be to throw them away in the mangler, but this
1316 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1317 "-fno-unit-at-a-time",
1318 -- unit-at-a-time doesn't do us any good, and screws
1319 -- up -split-objs by moving the split markers around.
1320 -- It's only turned on with -O2, but put it here just
1321 -- in case someone uses -optc-O2.
1324 -- calling builtins like strlen() using the FFI can
1325 -- cause gcc to run out of regs, so use the external
1329 #elif mips_TARGET_ARCH
1330 = ( ["-static"], [] )
1332 #elif sparc_TARGET_ARCH
1334 -- For now, to suppress the gcc warning "call-clobbered
1335 -- register used for global register variable", we simply
1336 -- disable all warnings altogether using the -w flag. Oh well.
1338 #elif powerpc_apple_darwin_TARGET
1340 -- Disable Apple's precompiling preprocessor. It's a great thing
1341 -- for "normal" programs, but it doesn't support register variable
1343 = ( [], ["-no-cpp-precomp"] )
1348 picCCOpts :: DynFlags -> [String]
1350 #if darwin_TARGET_OS
1351 -- Apple prefers to do things the other way round.
1352 -- PIC is on by default.
1353 -- -mdynamic-no-pic:
1354 -- Turn off PIC code generation.
1356 -- Don't generate "common" symbols - these are unwanted
1357 -- in dynamic libraries.
1362 = ["-mdynamic-no-pic"]
1363 #elif mingw32_TARGET_OS
1364 -- no -fPIC for Windows
1373 -- -----------------------------------------------------------------------------
1378 #if defined(i386_TARGET_ARCH) \
1379 || defined(x86_64_TARGET_ARCH) \
1380 || defined(alpha_TARGET_ARCH) \
1381 || defined(hppa_TARGET_ARCH) \
1382 || defined(m68k_TARGET_ARCH) \
1383 || defined(mips_TARGET_ARCH) \
1384 || defined(powerpc_TARGET_ARCH) \
1385 || defined(rs6000_TARGET_ARCH) \
1386 || defined(sparc_TARGET_ARCH)