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 )
76 import Char ( isDigit, isUpper )
78 import System.IO ( hPutStrLn, stderr )
79 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
81 -- -----------------------------------------------------------------------------
94 | Opt_D_dump_inlinings
95 | Opt_D_dump_occur_anal
99 | Opt_D_dump_simpl_iterations
108 | Opt_D_dump_worker_wrapper
109 | Opt_D_dump_rn_trace
110 | Opt_D_dump_rn_stats
112 | Opt_D_dump_simpl_stats
113 | Opt_D_dump_tc_trace
114 | Opt_D_dump_if_trace
119 | Opt_D_verbose_core2core
120 | Opt_D_verbose_stg2stg
122 | Opt_D_dump_hi_diffs
123 | Opt_D_dump_minimal_imports
124 | Opt_D_faststring_stats
129 | Opt_WarnIsError -- -Werror; makes warnings fatal
130 | Opt_WarnDuplicateExports
132 | Opt_WarnIncompletePatterns
133 | Opt_WarnIncompletePatternsRecUpd
134 | Opt_WarnMissingFields
135 | Opt_WarnMissingMethods
136 | Opt_WarnMissingSigs
137 | Opt_WarnNameShadowing
138 | Opt_WarnOverlappingPatterns
139 | Opt_WarnSimplePatterns
140 | Opt_WarnTypeDefaults
141 | Opt_WarnUnusedBinds
142 | Opt_WarnUnusedImports
143 | Opt_WarnUnusedMatches
144 | Opt_WarnDeprecations
145 | Opt_WarnDodgyImports
149 | Opt_AllowOverlappingInstances
150 | Opt_AllowUndecidableInstances
151 | Opt_AllowIncoherentInstances
152 | Opt_MonomorphismRestriction
156 | Opt_PArr -- syntactic support for parallel arrays
157 | Opt_Arrows -- Arrow-notation syntax
161 | Opt_ImplicitPrelude
162 | Opt_ScopedTypeVariables
169 | Opt_IgnoreInterfacePragmas
170 | Opt_OmitInterfacePragmas
171 | Opt_DoLambdaEtaExpansion
173 | Opt_IgnoreBreakpoints
176 | Opt_UnboxStrictFields
185 | Opt_ExcessPrecision
186 | Opt_ReadUserPackageConf
190 | Opt_HideAllPackages
201 data DynFlags = DynFlags {
204 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
205 stgToDo :: Maybe [StgToDo], -- similarly
206 hscTarget :: HscTarget,
207 hscOutName :: String, -- name of the output file
208 extCoreName :: String, -- name of the .core output file
209 verbosity :: Int, -- verbosity level
210 optLevel :: Int, -- optimisation level
211 maxSimplIterations :: Int, -- max simplifier iterations
212 ruleCheck :: Maybe String,
213 stolen_x86_regs :: Int,
214 cmdlineHcIncludes :: [String], -- -#includes
215 importPaths :: [FilePath],
217 mainFunIs :: Maybe String,
218 ctxtStkDepth :: Int, -- Typechecker context stack depth
220 thisPackage :: PackageId,
223 wayNames :: [WayName], -- way flags from the cmd line
224 buildTag :: String, -- the global "way" (eg. "p" for prof)
225 rtsBuildTag :: String, -- the RTS "way"
228 objectDir :: Maybe String,
229 hiDir :: Maybe String,
230 stubDir :: Maybe String,
236 outputFile :: Maybe String,
237 outputHi :: Maybe String,
239 includePaths :: [String],
240 libraryPaths :: [String],
241 frameworkPaths :: [String], -- used on darwin only
242 cmdlineFrameworks :: [String], -- ditto
243 tmpDir :: String, -- no trailing '/'
245 -- options for particular phases
256 -- commands for particular phases
258 pgm_P :: (String,[Option]),
260 pgm_c :: (String,[Option]),
261 pgm_m :: (String,[Option]),
262 pgm_s :: (String,[Option]),
263 pgm_a :: (String,[Option]),
264 pgm_l :: (String,[Option]),
265 pgm_dll :: (String,[Option]),
268 extraPkgConfs :: [FilePath],
269 -- The -package-conf flags given on the command line, in the order
272 packageFlags :: [PackageFlag],
273 -- The -package and -hide-package flags from the command-line
276 pkgState :: PackageState,
282 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
295 = BatchCompile -- | @ghc --make Main@
296 | Interactive -- | @ghc --interactive@
297 | OneShot -- | @ghc -c Foo.hs@
298 | JustTypecheck -- | Development environemnts, refactorer, etc.
302 isOneShot :: GhcMode -> Bool
303 isOneShot OneShot = True
304 isOneShot _other = False
306 data GhcLink -- What to do in the link step, if there is one
307 = -- Only relevant for modes
308 -- DoMake and StopBefore StopLn
309 NoLink -- Don't link at all
310 | StaticLink -- Ordinary linker [the default]
311 | MkDLL -- Make a DLL
313 isNoLink :: GhcLink -> Bool
314 isNoLink NoLink = True
315 isNoLink other = False
318 = ExposePackage String
320 | IgnorePackage String
323 | cGhcWithNativeCodeGen == "YES" = HscAsm
326 initDynFlags dflags = do
327 -- someday these will be dynamic flags
328 ways <- readIORef v_Ways
329 build_tag <- readIORef v_Build_tag
330 rts_build_tag <- readIORef v_RTS_Build_tag
333 buildTag = build_tag,
334 rtsBuildTag = rts_build_tag
340 ghcLink = StaticLink,
343 hscTarget = defaultHscTarget,
348 maxSimplIterations = 4,
351 cmdlineHcIncludes = [],
355 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
357 thisPackage = mainPackageId,
359 wayNames = panic "ways",
360 buildTag = panic "buildTag",
361 rtsBuildTag = panic "rtsBuildTag",
367 objectSuf = phaseInputExt StopLn,
368 hcSuf = phaseInputExt HCc,
371 outputFile = Nothing,
376 cmdlineFrameworks = [],
377 tmpDir = cDEFAULT_TMPDIR,
389 pgm_L = panic "pgm_L",
390 pgm_P = panic "pgm_P",
391 pgm_F = panic "pgm_F",
392 pgm_c = panic "pgm_c",
393 pgm_m = panic "pgm_m",
394 pgm_s = panic "pgm_s",
395 pgm_a = panic "pgm_a",
396 pgm_l = panic "pgm_l",
397 pgm_dll = panic "pgm_mkdll",
401 pkgState = panic "pkgState",
405 Opt_ReadUserPackageConf,
407 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
408 -- behaviour the default, to see if anyone notices
412 Opt_MonomorphismRestriction,
414 -- strictness is on by default, but this only
416 Opt_CSE, -- similarly for CSE.
417 Opt_FullLaziness, -- ...and for full laziness
419 Opt_DoLambdaEtaExpansion,
420 -- This one is important for a tiresome reason:
421 -- we want to make sure that the bindings for data
422 -- constructors are eta-expanded. This is probably
423 -- a good thing anyway, but it seems fragile.
427 -- and the default no-optimisation options:
428 Opt_IgnoreInterfacePragmas,
429 Opt_OmitInterfacePragmas
431 ] ++ standardWarnings,
433 log_action = \severity srcSpan style msg ->
435 SevInfo -> hPutStrLn stderr (show (msg style))
436 SevFatal -> hPutStrLn stderr (show (msg style))
437 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
443 0 | print errors & warnings only
444 1 | minimal verbosity: print "compiling M ... done." for each module.
445 2 | equivalent to -dshow-passes
446 3 | equivalent to existing "ghc -v"
447 4 | "ghc -v -ddump-most"
448 5 | "ghc -v -ddump-all"
451 dopt :: DynFlag -> DynFlags -> Bool
452 dopt f dflags = f `elem` (flags dflags)
454 dopt_set :: DynFlags -> DynFlag -> DynFlags
455 dopt_set dfs f = dfs{ flags = f : flags dfs }
457 dopt_unset :: DynFlags -> DynFlag -> DynFlags
458 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
460 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
461 getOpts dflags opts = reverse (opts dflags)
462 -- We add to the options from the front, so we need to reverse the list
464 getVerbFlag :: DynFlags -> String
466 | verbosity dflags >= 3 = "-v"
469 setObjectDir f d = d{ objectDir = f}
470 setHiDir f d = d{ hiDir = f}
471 setStubDir f d = d{ stubDir = f}
473 setObjectSuf f d = d{ objectSuf = f}
474 setHiSuf f d = d{ hiSuf = f}
475 setHcSuf f d = d{ hcSuf = f}
477 setOutputFile f d = d{ outputFile = f}
478 setOutputHi f d = d{ outputHi = f}
480 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
481 -- Config.hs should really use Option.
482 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
484 setPgmL f d = d{ pgm_L = f}
485 setPgmF f d = d{ pgm_F = f}
486 setPgmc f d = d{ pgm_c = (f,[])}
487 setPgmm f d = d{ pgm_m = (f,[])}
488 setPgms f d = d{ pgm_s = (f,[])}
489 setPgma f d = d{ pgm_a = (f,[])}
490 setPgml f d = d{ pgm_l = (f,[])}
491 setPgmdll f d = d{ pgm_dll = (f,[])}
493 addOptL f d = d{ opt_L = f : opt_L d}
494 addOptP f d = d{ opt_P = f : opt_P d}
495 addOptF f d = d{ opt_F = f : opt_F d}
496 addOptc f d = d{ opt_c = f : opt_c d}
497 addOptm f d = d{ opt_m = f : opt_m d}
498 addOpta f d = d{ opt_a = f : opt_a d}
499 addOptl f d = d{ opt_l = f : opt_l d}
500 addOptdll f d = d{ opt_dll = f : opt_dll d}
501 addOptdep f d = d{ opt_dep = f : opt_dep d}
503 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
505 -- -----------------------------------------------------------------------------
506 -- Command-line options
508 -- When invoking external tools as part of the compilation pipeline, we
509 -- pass these a sequence of options on the command-line. Rather than
510 -- just using a list of Strings, we use a type that allows us to distinguish
511 -- between filepaths and 'other stuff'. [The reason being, of course, that
512 -- this type gives us a handle on transforming filenames, and filenames only,
513 -- to whatever format they're expected to be on a particular platform.]
516 = FileOption -- an entry that _contains_ filename(s) / filepaths.
517 String -- a non-filepath prefix that shouldn't be
518 -- transformed (e.g., "/out=")
519 String -- the filepath/filename portion
522 -----------------------------------------------------------------------------
523 -- Setting the optimisation level
525 updOptLevel :: Int -> DynFlags -> DynFlags
526 -- Set dynflags appropriate to the optimisation level
529 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
530 else dfs2{ optLevel = n }
532 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
533 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
536 | n == 0 = opt_0_dopts
537 | otherwise = opt_1_dopts
540 | n == 0 = opt_1_dopts
541 | otherwise = opt_0_dopts
544 Opt_IgnoreInterfacePragmas,
545 Opt_OmitInterfacePragmas
554 -- -----------------------------------------------------------------------------
555 -- Standard sets of warning options
558 = [ Opt_WarnDeprecations,
559 Opt_WarnOverlappingPatterns,
560 Opt_WarnMissingFields,
561 Opt_WarnMissingMethods,
562 Opt_WarnDuplicateExports
566 = standardWarnings ++
567 [ Opt_WarnUnusedBinds,
568 Opt_WarnUnusedMatches,
569 Opt_WarnUnusedImports,
570 Opt_WarnIncompletePatterns,
576 [ Opt_WarnTypeDefaults,
577 Opt_WarnNameShadowing,
583 -- -----------------------------------------------------------------------------
584 -- CoreToDo: abstraction of core-to-core passes to run.
586 data CoreToDo -- These are diff core-to-core passes,
587 -- which may be invoked in any order,
588 -- as many times as you like.
590 = CoreDoSimplify -- The core-to-core simplifier.
593 -- Each run of the simplifier can take a different
594 -- set of simplifier-specific flags.
596 | CoreDoFloatOutwards FloatOutSwitches
601 | CoreDoWorkerWrapper
604 | CoreDoOldStrictness
607 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
608 -- matching this string
610 | CoreDoNothing -- useful when building up lists of these things
612 data SimplifierMode -- See comments in SimplMonad
616 data SimplifierSwitch
617 = MaxSimplifierIterations Int
620 data FloatOutSwitches
621 = FloatOutSw Bool -- True <=> float lambdas to top level
622 Bool -- True <=> float constants to top level,
623 -- even if they do not escape a lambda
626 -- The core-to-core pass ordering is derived from the DynFlags:
628 getCoreToDo :: DynFlags -> [CoreToDo]
630 | Just todo <- coreToDo dflags = todo -- set explicitly by user
631 | otherwise = core_todo
633 opt_level = optLevel dflags
634 max_iter = maxSimplIterations dflags
635 strictness = dopt Opt_Strictness dflags
636 full_laziness = dopt Opt_FullLaziness dflags
637 cse = dopt Opt_CSE dflags
638 rule_check = ruleCheck dflags
641 if opt_level == 0 then
643 CoreDoSimplify (SimplPhase 0) [
644 MaxSimplifierIterations max_iter
647 else {- opt_level >= 1 -} [
649 -- initial simplify: mk specialiser happy: minimum effort please
650 CoreDoSimplify SimplGently [
652 -- Don't inline anything till full laziness has bitten
653 -- In particular, inlining wrappers inhibits floating
654 -- e.g. ...(case f x of ...)...
655 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
656 -- ==> ...(case x of I# x# -> case fw x# of ...)...
657 -- and now the redex (f x) isn't floatable any more
658 -- Similarly, don't apply any rules until after full
659 -- laziness. Notably, list fusion can prevent floating.
661 NoCaseOfCase, -- Don't do case-of-case transformations.
662 -- This makes full laziness work better
663 MaxSimplifierIterations max_iter
666 -- Specialisation is best done before full laziness
667 -- so that overloaded functions have all their dictionary lambdas manifest
670 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
675 CoreDoSimplify (SimplPhase 2) [
676 -- Want to run with inline phase 2 after the specialiser to give
677 -- maximum chance for fusion to work before we inline build/augment
678 -- in phase 1. This made a difference in 'ansi' where an
679 -- overloaded function wasn't inlined till too late.
680 MaxSimplifierIterations max_iter
682 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
684 CoreDoSimplify (SimplPhase 1) [
685 -- Need inline-phase2 here so that build/augment get
686 -- inlined. I found that spectral/hartel/genfft lost some useful
687 -- strictness in the function sumcode' if augment is not inlined
688 -- before strictness analysis runs
689 MaxSimplifierIterations max_iter
691 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
693 CoreDoSimplify (SimplPhase 0) [
694 -- Phase 0: allow all Ids to be inlined now
695 -- This gets foldr inlined before strictness analysis
697 MaxSimplifierIterations 3
698 -- At least 3 iterations because otherwise we land up with
699 -- huge dead expressions because of an infelicity in the
701 -- let k = BIG in foldr k z xs
702 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
703 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
707 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
709 #ifdef OLD_STRICTNESS
712 if strictness then CoreDoStrictness else CoreDoNothing,
716 CoreDoSimplify (SimplPhase 0) [
717 MaxSimplifierIterations max_iter
720 if full_laziness then
721 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
722 True) -- Float constants
724 -- nofib/spectral/hartel/wang doubles in speed if you
725 -- do full laziness late in the day. It only happens
726 -- after fusion and other stuff, so the early pass doesn't
727 -- catch it. For the record, the redex is
728 -- f_el22 (f_el21 r_midblock)
731 -- We want CSE to follow the final full-laziness pass, because it may
732 -- succeed in commoning up things floated out by full laziness.
733 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
735 if cse then CoreCSE else CoreDoNothing,
739 -- Case-liberation for -O2. This should be after
740 -- strictness analysis and the simplification which follows it.
742 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
747 (if opt_level >= 2 then
749 CoreDoSimplify (SimplPhase 0) [
750 MaxSimplifierIterations max_iter
751 ], -- Run the simplifier after LiberateCase to vastly
752 -- reduce the possiblility of shadowing
753 -- Reason: see Note [Shadowing] in SpecConstr.lhs
761 -- Final clean-up simplification:
762 [ CoreDoSimplify (SimplPhase 0) [
763 MaxSimplifierIterations max_iter
767 -- -----------------------------------------------------------------------------
768 -- StgToDo: abstraction of stg-to-stg passes to run.
771 = StgDoMassageForProfiling -- should be (next to) last
772 -- There's also setStgVarInfo, but its absolute "lastness"
773 -- is so critical that it is hardwired in (no flag).
776 getStgToDo :: DynFlags -> [StgToDo]
778 | Just todo <- stgToDo dflags = todo -- set explicitly by user
781 stg_stats = dopt Opt_StgStats dflags
783 todo1 = if stg_stats then [D_stg_stats] else []
785 todo2 | WayProf `elem` wayNames dflags
786 = StgDoMassageForProfiling : todo1
790 -- -----------------------------------------------------------------------------
794 allFlags = map ('-':) $
795 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
796 map ("fno-"++) flags ++
798 where ok (PrefixPred _ _) = False
800 flags = map fst fFlags
802 dynamic_flags :: [(String, OptKind DynP)]
804 ( "n" , NoArg (setDynFlag Opt_DryRun) )
805 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
806 , ( "F" , NoArg (setDynFlag Opt_Pp))
807 , ( "#include" , HasArg (addCmdlineHCInclude) )
808 , ( "v" , OptIntSuffix setVerbosity )
810 ------- Specific phases --------------------------------------------
811 , ( "pgmL" , HasArg (upd . setPgmL) )
812 , ( "pgmP" , HasArg (upd . setPgmP) )
813 , ( "pgmF" , HasArg (upd . setPgmF) )
814 , ( "pgmc" , HasArg (upd . setPgmc) )
815 , ( "pgmm" , HasArg (upd . setPgmm) )
816 , ( "pgms" , HasArg (upd . setPgms) )
817 , ( "pgma" , HasArg (upd . setPgma) )
818 , ( "pgml" , HasArg (upd . setPgml) )
819 , ( "pgmdll" , HasArg (upd . setPgmdll) )
821 , ( "optL" , HasArg (upd . addOptL) )
822 , ( "optP" , HasArg (upd . addOptP) )
823 , ( "optF" , HasArg (upd . addOptF) )
824 , ( "optc" , HasArg (upd . addOptc) )
825 , ( "optm" , HasArg (upd . addOptm) )
826 , ( "opta" , HasArg (upd . addOpta) )
827 , ( "optl" , HasArg (upd . addOptl) )
828 , ( "optdll" , HasArg (upd . addOptdll) )
829 , ( "optdep" , HasArg (upd . addOptdep) )
831 , ( "split-objs" , NoArg (if can_split
832 then setDynFlag Opt_SplitObjs
835 -------- Linking ----------------------------------------------------
836 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
837 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
838 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
840 ------- Libraries ---------------------------------------------------
841 , ( "L" , Prefix addLibraryPath )
842 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
845 ------- Frameworks --------------------------------------------------
846 -- -framework-path should really be -F ...
847 , ( "framework-path" , HasArg addFrameworkPath )
848 , ( "framework" , HasArg (upd . addCmdlineFramework) )
850 ------- Output Redirection ------------------------------------------
851 , ( "odir" , HasArg (upd . setObjectDir . Just))
852 , ( "o" , SepArg (upd . setOutputFile . Just))
853 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
854 , ( "osuf" , HasArg (upd . setObjectSuf))
855 , ( "hcsuf" , HasArg (upd . setHcSuf))
856 , ( "hisuf" , HasArg (upd . setHiSuf))
857 , ( "hidir" , HasArg (upd . setHiDir . Just))
858 , ( "tmpdir" , HasArg (upd . setTmpDir))
859 , ( "stubdir" , HasArg (upd . setStubDir . Just))
861 ------- Keeping temporary files -------------------------------------
862 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
863 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
864 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
865 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
867 ------- Miscellaneous ----------------------------------------------
868 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
869 , ( "main-is" , SepArg setMainIs )
871 ------- recompilation checker --------------------------------------
872 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
873 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
875 ------- Packages ----------------------------------------------------
876 , ( "package-conf" , HasArg extraPkgConf_ )
877 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
878 , ( "package-name" , HasArg setPackageName )
879 , ( "package" , HasArg exposePackage )
880 , ( "hide-package" , HasArg hidePackage )
881 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
882 , ( "ignore-package" , HasArg ignorePackage )
883 , ( "syslib" , HasArg exposePackage ) -- for compatibility
885 ------ HsCpp opts ---------------------------------------------------
886 , ( "D", AnySuffix (upd . addOptP) )
887 , ( "U", AnySuffix (upd . addOptP) )
889 ------- Include/Import Paths ----------------------------------------
890 , ( "I" , Prefix addIncludePath)
891 , ( "i" , OptPrefix addImportPath )
893 ------ Debugging ----------------------------------------------------
894 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
896 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
897 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
898 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
899 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
900 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
901 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
902 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
903 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
904 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
905 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
906 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
907 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
908 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
909 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
910 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
911 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
912 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
913 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
914 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
915 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
916 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
917 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
918 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
919 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
920 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
921 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
922 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
923 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
924 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
925 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
926 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
927 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
928 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
929 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
930 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
931 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
932 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
933 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
934 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
935 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
936 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
937 setVerbosity (Just 2)) )
938 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
940 ------ Machine dependant (-m<blah>) stuff ---------------------------
942 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
943 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
944 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
946 ------ Warning opts -------------------------------------------------
947 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
948 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
949 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
950 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
951 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
953 ------ Optimisation flags ------------------------------------------
954 , ( "O" , NoArg (upd (setOptLevel 1)))
955 , ( "Onot" , NoArg (upd (setOptLevel 0)))
956 , ( "O" , PrefixPred (all isDigit)
957 (\f -> upd (setOptLevel (read f))))
959 , ( "fmax-simplifier-iterations",
960 PrefixPred (all isDigit)
962 dfs{ maxSimplIterations = read n })) )
965 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
967 ------ Compiler flags -----------------------------------------------
969 , ( "fno-code", NoArg (setTarget HscNothing))
970 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
971 , ( "fvia-c", NoArg (setTarget HscC) )
972 , ( "fvia-C", NoArg (setTarget HscC) )
973 , ( "filx", NoArg (setTarget HscILX) )
975 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
976 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
978 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
979 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
981 -- the rest of the -f* and -fno-* flags
982 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
983 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
986 -- these -f<blah> flags can all be reversed with -fno-<blah>
989 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
990 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
991 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
992 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
993 ( "warn-missing-fields", Opt_WarnMissingFields ),
994 ( "warn-missing-methods", Opt_WarnMissingMethods ),
995 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
996 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
997 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
998 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
999 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1000 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1001 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1002 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1003 ( "warn-deprecations", Opt_WarnDeprecations ),
1004 ( "warn-orphans", Opt_WarnOrphans ),
1005 ( "fi", Opt_FFI ), -- support `-ffi'...
1006 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1007 ( "arrows", Opt_Arrows ), -- arrow syntax
1008 ( "parr", Opt_PArr ),
1010 ( "implicit-prelude", Opt_ImplicitPrelude ),
1011 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1012 ( "bang-patterns", Opt_BangPatterns ),
1013 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1014 ( "mono-pat-binds", Opt_MonoPatBinds ),
1015 ( "implicit-params", Opt_ImplicitParams ),
1016 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1017 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1018 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1019 ( "generics", Opt_Generics ),
1020 ( "strictness", Opt_Strictness ),
1021 ( "full-laziness", Opt_FullLaziness ),
1023 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1024 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1025 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1026 ( "ignore-asserts", Opt_IgnoreAsserts ),
1027 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1028 ( "do-eta-reduction", Opt_DoEtaReduction ),
1029 ( "case-merge", Opt_CaseMerge ),
1030 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1031 ( "dicts-cheap", Opt_DictsCheap ),
1032 ( "excess-precision", Opt_ExcessPrecision ),
1033 ( "asm-mangling", Opt_DoAsmMangling )
1036 glasgowExtsFlags = [
1040 Opt_ScopedTypeVariables,
1043 isFFlag f = f `elem` (map fst fFlags)
1044 getFFlag f = fromJust (lookup f fFlags)
1046 -- -----------------------------------------------------------------------------
1047 -- Parsing the dynamic flags.
1049 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1050 parseDynamicFlags dflags args = do
1051 let ((leftover,errs),dflags')
1052 = runCmdLine (processArgs dynamic_flags args) dflags
1053 when (not (null errs)) $ do
1054 throwDyn (UsageError (unlines errs))
1055 return (dflags', leftover)
1058 type DynP = CmdLineP DynFlags
1060 upd :: (DynFlags -> DynFlags) -> DynP ()
1062 dfs <- getCmdLineState
1063 putCmdLineState $! (f dfs)
1065 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1066 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1067 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1069 setDumpFlag :: DynFlag -> OptKind DynP
1070 setDumpFlag dump_flag
1071 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1072 -- Whenver we -ddump, switch off the recompilation checker,
1073 -- else you don't see the dump!
1075 setVerbosity :: Maybe Int -> DynP ()
1076 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1078 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1080 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1083 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1085 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1087 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1089 | Nothing <- unpackPackageId pid
1090 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1092 = upd (\s -> s{ thisPackage = pid })
1094 pid = stringToPackageId p
1096 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1097 -- (-fvia-C, -fasm, -filx respectively).
1098 setTarget l = upd (\dfs -> case hscTarget dfs of
1099 HscC -> dfs{ hscTarget = l }
1100 HscAsm -> dfs{ hscTarget = l }
1101 HscILX -> dfs{ hscTarget = l }
1104 setOptLevel :: Int -> DynFlags -> DynFlags
1105 setOptLevel n dflags
1106 | hscTarget dflags == HscInterpreted && n > 0
1108 -- not in IO any more, oh well:
1109 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1111 = updOptLevel n dflags
1114 setMainIs :: String -> DynP ()
1116 | not (null main_fn) -- The arg looked like "Foo.baz"
1117 = upd $ \d -> d{ mainFunIs = Just main_fn,
1118 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1120 | isUpper (head main_mod) -- The arg looked like "Foo"
1121 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1123 | otherwise -- The arg looked like "baz"
1124 = upd $ \d -> d{ mainFunIs = Just main_mod }
1126 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1128 -----------------------------------------------------------------------------
1129 -- Paths & Libraries
1131 -- -i on its own deletes the import paths
1132 addImportPath "" = upd (\s -> s{importPaths = []})
1133 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1137 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1140 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1142 addFrameworkPath p =
1143 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1145 split_marker = ':' -- not configurable (ToDo)
1147 splitPathList :: String -> [String]
1148 splitPathList s = filter notNull (splitUp s)
1149 -- empty paths are ignored: there might be a trailing
1150 -- ':' in the initial list, for example. Empty paths can
1151 -- cause confusion when they are translated into -I options
1152 -- for passing to gcc.
1154 #ifndef mingw32_TARGET_OS
1155 splitUp xs = split split_marker xs
1157 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1159 -- That is, if "foo:bar:baz" is used, this interpreted as
1160 -- consisting of three entries, 'foo', 'bar', 'baz'.
1161 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1162 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1164 -- Notice that no attempt is made to fully replace the 'standard'
1165 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1166 -- that this will cause too much breakage for users & ':' will
1167 -- work fine even with DOS paths, if you're not insisting on being silly.
1170 splitUp (x:':':div:xs) | div `elem` dir_markers
1171 = ((x:':':div:p): splitUp rs)
1173 (p,rs) = findNextPath xs
1174 -- we used to check for existence of the path here, but that
1175 -- required the IO monad to be threaded through the command-line
1176 -- parser which is quite inconvenient. The
1177 splitUp xs = cons p (splitUp rs)
1179 (p,rs) = findNextPath xs
1184 -- will be called either when we've consumed nought or the
1185 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1186 -- finding the next split marker.
1188 case break (`elem` split_markers) xs of
1189 (p, d:ds) -> (p, ds)
1192 split_markers :: [Char]
1193 split_markers = [':', ';']
1195 dir_markers :: [Char]
1196 dir_markers = ['/', '\\']
1199 -- -----------------------------------------------------------------------------
1200 -- tmpDir, where we store temporary files.
1202 setTmpDir :: FilePath -> DynFlags -> DynFlags
1203 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1205 #if !defined(mingw32_HOST_OS)
1206 canonicalise p = normalisePath p
1208 -- Canonicalisation of temp path under win32 is a bit more
1209 -- involved: (a) strip trailing slash,
1210 -- (b) normalise slashes
1211 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1213 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1215 -- if we're operating under cygwin, and TMP/TEMP is of
1216 -- the form "/cygdrive/drive/path", translate this to
1217 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1218 -- understand /cygdrive paths.)
1220 | "/cygdrive/" `isPrefixOf` path =
1221 case drop (length "/cygdrive/") path of
1222 drive:xs@('/':_) -> drive:':':xs
1226 -- strip the trailing backslash (awful, but we only do this once).
1227 removeTrailingSlash path =
1234 -----------------------------------------------------------------------------
1235 -- Via-C compilation stuff
1237 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1238 [String]) -- for registerised HC compilations
1239 machdepCCOpts dflags
1240 #if alpha_TARGET_ARCH
1242 #ifdef HAVE_THREADED_RTS_SUPPORT
1246 -- For now, to suppress the gcc warning "call-clobbered
1247 -- register used for global register variable", we simply
1248 -- disable all warnings altogether using the -w flag. Oh well.
1250 #elif hppa_TARGET_ARCH
1251 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1252 -- (very nice, but too bad the HP /usr/include files don't agree.)
1253 = ( ["-D_HPUX_SOURCE"], [] )
1255 #elif m68k_TARGET_ARCH
1256 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1257 -- popping of args to routines to be explicit; if we let things
1258 -- be deferred 'til after an STGJUMP, imminent death is certain!
1260 -- -fomit-frame-pointer : *don't*
1261 -- It's better to have a6 completely tied up being a frame pointer
1262 -- rather than let GCC pick random things to do with it.
1263 -- (If we want to steal a6, then we would try to do things
1264 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1265 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1267 #elif i386_TARGET_ARCH
1268 -- -fno-defer-pop : basically the same game as for m68k
1270 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1271 -- the fp (%ebp) for our register maps.
1272 = let n_regs = stolen_x86_regs dflags
1275 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1276 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1279 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1280 -- Some gccs are configured with
1281 -- -momit-leaf-frame-pointer on by default, and it
1282 -- apparently takes precedence over
1283 -- -fomit-frame-pointer, so we disable it first here.
1284 "-mno-omit-leaf-frame-pointer",
1286 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1287 "-fno-unit-at-a-time",
1288 -- unit-at-a-time doesn't do us any good, and screws
1289 -- up -split-objs by moving the split markers around.
1290 -- It's only turned on with -O2, but put it here just
1291 -- in case someone uses -optc-O2.
1293 "-fomit-frame-pointer",
1294 -- we want -fno-builtin, because when gcc inlines
1295 -- built-in functions like memcpy() it tends to
1296 -- run out of registers, requiring -monly-n-regs
1298 "-DSTOLEN_X86_REGS="++show n_regs ]
1301 #elif ia64_TARGET_ARCH
1302 = ( [], ["-fomit-frame-pointer", "-G0"] )
1304 #elif x86_64_TARGET_ARCH
1305 = ( [], ["-fomit-frame-pointer",
1306 "-fno-asynchronous-unwind-tables",
1307 -- the unwind tables are unnecessary for HC code,
1308 -- and get in the way of -split-objs. Another option
1309 -- would be to throw them away in the mangler, but this
1311 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1312 "-fno-unit-at-a-time",
1313 -- unit-at-a-time doesn't do us any good, and screws
1314 -- up -split-objs by moving the split markers around.
1315 -- It's only turned on with -O2, but put it here just
1316 -- in case someone uses -optc-O2.
1319 -- calling builtins like strlen() using the FFI can
1320 -- cause gcc to run out of regs, so use the external
1324 #elif mips_TARGET_ARCH
1325 = ( ["-static"], [] )
1327 #elif sparc_TARGET_ARCH
1329 -- For now, to suppress the gcc warning "call-clobbered
1330 -- register used for global register variable", we simply
1331 -- disable all warnings altogether using the -w flag. Oh well.
1333 #elif powerpc_apple_darwin_TARGET
1335 -- Disable Apple's precompiling preprocessor. It's a great thing
1336 -- for "normal" programs, but it doesn't support register variable
1338 = ( [], ["-no-cpp-precomp"] )
1343 picCCOpts :: DynFlags -> [String]
1345 #if darwin_TARGET_OS
1346 -- Apple prefers to do things the other way round.
1347 -- PIC is on by default.
1348 -- -mdynamic-no-pic:
1349 -- Turn off PIC code generation.
1351 -- Don't generate "common" symbols - these are unwanted
1352 -- in dynamic libraries.
1357 = ["-mdynamic-no-pic"]
1358 #elif mingw32_TARGET_OS
1359 -- no -fPIC for Windows
1368 -- -----------------------------------------------------------------------------
1373 #if defined(i386_TARGET_ARCH) \
1374 || defined(x86_64_TARGET_ARCH) \
1375 || defined(alpha_TARGET_ARCH) \
1376 || defined(hppa_TARGET_ARCH) \
1377 || defined(m68k_TARGET_ARCH) \
1378 || defined(mips_TARGET_ARCH) \
1379 || defined(powerpc_TARGET_ARCH) \
1380 || defined(rs6000_TARGET_ARCH) \
1381 || defined(sparc_TARGET_ARCH)