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]
46 machdepCCOpts, picCCOpts,
49 #include "HsVersions.h"
51 import Module ( Module, mkModule )
52 import PrelNames ( mAIN )
53 import StaticFlags ( opt_Static, opt_PIC,
54 WayName(..), v_Ways, v_Build_tag, v_RTS_Build_tag )
55 import {-# SOURCE #-} Packages (PackageState)
56 import DriverPhases ( Phase(..), phaseInputExt )
59 import Panic ( panic, GhcException(..) )
60 import Util ( notNull, splitLongestPrefix, split, normalisePath )
61 import SrcLoc ( SrcSpan )
63 import DATA_IOREF ( readIORef )
64 import EXCEPTION ( throwDyn )
66 #ifdef mingw32_TARGET_OS
67 import Data.List ( isPrefixOf )
69 import Maybe ( fromJust )
70 import Char ( isDigit, isUpper )
72 import System.IO ( hPutStrLn, stderr )
73 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
75 -- -----------------------------------------------------------------------------
88 | Opt_D_dump_inlinings
89 | Opt_D_dump_occur_anal
93 | Opt_D_dump_simpl_iterations
102 | Opt_D_dump_worker_wrapper
103 | Opt_D_dump_rn_trace
104 | Opt_D_dump_rn_stats
106 | Opt_D_dump_simpl_stats
107 | Opt_D_dump_tc_trace
108 | Opt_D_dump_if_trace
113 | Opt_D_verbose_core2core
114 | Opt_D_verbose_stg2stg
116 | Opt_D_dump_hi_diffs
117 | Opt_D_dump_minimal_imports
122 | Opt_WarnIsError -- -Werror; makes warnings fatal
123 | Opt_WarnDuplicateExports
125 | Opt_WarnIncompletePatterns
126 | Opt_WarnIncompletePatternsRecUpd
127 | Opt_WarnMissingFields
128 | Opt_WarnMissingMethods
129 | Opt_WarnMissingSigs
130 | Opt_WarnNameShadowing
131 | Opt_WarnOverlappingPatterns
132 | Opt_WarnSimplePatterns
133 | Opt_WarnTypeDefaults
134 | Opt_WarnUnusedBinds
135 | Opt_WarnUnusedImports
136 | Opt_WarnUnusedMatches
137 | Opt_WarnDeprecations
138 | Opt_WarnDodgyImports
142 | Opt_AllowOverlappingInstances
143 | Opt_AllowUndecidableInstances
144 | Opt_AllowIncoherentInstances
145 | Opt_MonomorphismRestriction
148 | Opt_PArr -- syntactic support for parallel arrays
149 | Opt_Arrows -- Arrow-notation syntax
153 | Opt_ImplicitPrelude
154 | Opt_ScopedTypeVariables
160 | Opt_IgnoreInterfacePragmas
161 | Opt_OmitInterfacePragmas
162 | Opt_DoLambdaEtaExpansion
166 | Opt_UnboxStrictFields
174 | Opt_ExcessPrecision
175 | Opt_ReadUserPackageConf
179 | Opt_HideAllPackages
190 data DynFlags = DynFlags {
193 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
194 stgToDo :: Maybe [StgToDo], -- similarly
195 hscTarget :: HscTarget,
196 hscOutName :: String, -- name of the output file
197 hscStubHOutName :: String, -- name of the .stub_h output file
198 hscStubCOutName :: String, -- name of the .stub_c output file
199 extCoreName :: String, -- name of the .core output file
200 verbosity :: Int, -- verbosity level
201 optLevel :: Int, -- optimisation level
202 maxSimplIterations :: Int, -- max simplifier iterations
203 ruleCheck :: Maybe String,
204 stolen_x86_regs :: Int,
205 cmdlineHcIncludes :: [String], -- -#includes
206 importPaths :: [FilePath],
208 mainFunIs :: Maybe String,
211 wayNames :: [WayName], -- way flags from the cmd line
212 buildTag :: String, -- the global "way" (eg. "p" for prof)
213 rtsBuildTag :: String, -- the RTS "way"
216 outputDir :: Maybe String,
217 outputFile :: Maybe String,
218 outputHi :: Maybe String,
221 hiDir :: Maybe String,
223 includePaths :: [String],
224 libraryPaths :: [String],
225 frameworkPaths :: [String], -- used on darwin only
226 cmdlineFrameworks :: [String], -- ditto
227 tmpDir :: String, -- no trailing '/'
229 -- options for particular phases
240 -- commands for particular phases
242 pgm_P :: (String,[Option]),
244 pgm_c :: (String,[Option]),
245 pgm_m :: (String,[Option]),
246 pgm_s :: (String,[Option]),
247 pgm_a :: (String,[Option]),
248 pgm_l :: (String,[Option]),
249 pgm_dll :: (String,[Option]),
252 extraPkgConfs :: [FilePath],
253 -- The -package-conf flags given on the command line, in the order
256 packageFlags :: [PackageFlag],
257 -- The -package and -hide-package flags from the command-line
260 pkgState :: PackageState,
266 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
279 = BatchCompile -- | @ghc --make Main@
280 | Interactive -- | @ghc --interactive@
281 | OneShot -- | @ghc -c Foo.hs@
282 | JustTypecheck -- | Development environemnts, refactorer, etc.
286 isOneShot :: GhcMode -> Bool
287 isOneShot OneShot = True
288 isOneShot _other = False
290 data GhcLink -- What to do in the link step, if there is one
291 = -- Only relevant for modes
292 -- DoMake and StopBefore StopLn
293 NoLink -- Don't link at all
294 | StaticLink -- Ordinary linker [the default]
295 | MkDLL -- Make a DLL
297 isNoLink :: GhcLink -> Bool
298 isNoLink NoLink = True
299 isNoLink other = False
302 = ExposePackage String
304 | IgnorePackage String
307 | cGhcWithNativeCodeGen == "YES" = HscAsm
310 initDynFlags dflags = do
311 -- someday these will be dynamic flags
312 ways <- readIORef v_Ways
313 build_tag <- readIORef v_Build_tag
314 rts_build_tag <- readIORef v_RTS_Build_tag
317 buildTag = build_tag,
318 rtsBuildTag = rts_build_tag
324 ghcLink = StaticLink,
327 hscTarget = defaultHscTarget,
329 hscStubHOutName = "",
330 hscStubCOutName = "",
334 maxSimplIterations = 4,
337 cmdlineHcIncludes = [],
342 wayNames = panic "ways",
343 buildTag = panic "buildTag",
344 rtsBuildTag = panic "rtsBuildTag",
347 outputFile = Nothing,
349 objectSuf = phaseInputExt StopLn,
350 hcSuf = phaseInputExt HCc,
356 cmdlineFrameworks = [],
357 tmpDir = cDEFAULT_TMPDIR,
369 pgm_L = panic "pgm_L",
370 pgm_P = panic "pgm_P",
371 pgm_F = panic "pgm_F",
372 pgm_c = panic "pgm_c",
373 pgm_m = panic "pgm_m",
374 pgm_s = panic "pgm_s",
375 pgm_a = panic "pgm_a",
376 pgm_l = panic "pgm_l",
377 pgm_dll = panic "pgm_mkdll",
381 pkgState = panic "pkgState",
385 Opt_ReadUserPackageConf,
388 Opt_MonomorphismRestriction,
390 -- strictness is on by default, but this only
392 Opt_CSE, -- similarly for CSE.
393 Opt_FullLaziness, -- ...and for full laziness
395 Opt_DoLambdaEtaExpansion,
396 -- This one is important for a tiresome reason:
397 -- we want to make sure that the bindings for data
398 -- constructors are eta-expanded. This is probably
399 -- a good thing anyway, but it seems fragile.
403 -- and the default no-optimisation options:
404 Opt_IgnoreInterfacePragmas,
405 Opt_OmitInterfacePragmas
407 ] ++ standardWarnings,
409 log_action = \severity srcSpan style msg ->
411 SevInfo -> hPutStrLn stderr (show (msg style))
412 SevFatal -> hPutStrLn stderr (show (msg style))
413 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
419 0 | print errors & warnings only
420 1 | minimal verbosity: print "compiling M ... done." for each module.
421 2 | equivalent to -dshow-passes
422 3 | equivalent to existing "ghc -v"
423 4 | "ghc -v -ddump-most"
424 5 | "ghc -v -ddump-all"
427 dopt :: DynFlag -> DynFlags -> Bool
428 dopt f dflags = f `elem` (flags dflags)
430 dopt_set :: DynFlags -> DynFlag -> DynFlags
431 dopt_set dfs f = dfs{ flags = f : flags dfs }
433 dopt_unset :: DynFlags -> DynFlag -> DynFlags
434 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
436 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
437 getOpts dflags opts = reverse (opts dflags)
438 -- We add to the options from the front, so we need to reverse the list
440 getVerbFlag :: DynFlags -> String
442 | verbosity dflags >= 3 = "-v"
445 setOutputDir f d = d{ outputDir = f}
446 setOutputFile f d = d{ outputFile = f}
447 setOutputHi f d = d{ outputHi = f}
448 setObjectSuf f d = d{ objectSuf = f}
449 setHcSuf f d = d{ hcSuf = f}
450 setHiSuf f d = d{ hiSuf = f}
451 setHiDir f d = d{ hiDir = f}
453 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
454 -- Config.hs should really use Option.
455 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
457 setPgmL f d = d{ pgm_L = f}
458 setPgmF f d = d{ pgm_F = f}
459 setPgmc f d = d{ pgm_c = (f,[])}
460 setPgmm f d = d{ pgm_m = (f,[])}
461 setPgms f d = d{ pgm_s = (f,[])}
462 setPgma f d = d{ pgm_a = (f,[])}
463 setPgml f d = d{ pgm_l = (f,[])}
464 setPgmdll f d = d{ pgm_dll = (f,[])}
466 addOptL f d = d{ opt_L = f : opt_L d}
467 addOptP f d = d{ opt_P = f : opt_P d}
468 addOptF f d = d{ opt_F = f : opt_F d}
469 addOptc f d = d{ opt_c = f : opt_c d}
470 addOptm f d = d{ opt_m = f : opt_m d}
471 addOpta f d = d{ opt_a = f : opt_a d}
472 addOptl f d = d{ opt_l = f : opt_l d}
473 addOptdll f d = d{ opt_dll = f : opt_dll d}
474 addOptdep f d = d{ opt_dep = f : opt_dep d}
476 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
478 -- -----------------------------------------------------------------------------
479 -- Command-line options
481 -- When invoking external tools as part of the compilation pipeline, we
482 -- pass these a sequence of options on the command-line. Rather than
483 -- just using a list of Strings, we use a type that allows us to distinguish
484 -- between filepaths and 'other stuff'. [The reason being, of course, that
485 -- this type gives us a handle on transforming filenames, and filenames only,
486 -- to whatever format they're expected to be on a particular platform.]
489 = FileOption -- an entry that _contains_ filename(s) / filepaths.
490 String -- a non-filepath prefix that shouldn't be
491 -- transformed (e.g., "/out=")
492 String -- the filepath/filename portion
495 -----------------------------------------------------------------------------
496 -- Setting the optimisation level
498 updOptLevel :: Int -> DynFlags -> DynFlags
499 -- Set dynflags appropriate to the optimisation level
502 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
503 else dfs2{ optLevel = n }
505 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
506 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
509 | n == 0 = opt_0_dopts
510 | otherwise = opt_1_dopts
513 | n == 0 = opt_1_dopts
514 | otherwise = opt_0_dopts
517 Opt_IgnoreInterfacePragmas,
518 Opt_OmitInterfacePragmas
527 -- -----------------------------------------------------------------------------
528 -- Standard sets of warning options
531 = [ Opt_WarnDeprecations,
532 Opt_WarnOverlappingPatterns,
533 Opt_WarnMissingFields,
534 Opt_WarnMissingMethods,
535 Opt_WarnDuplicateExports
539 = standardWarnings ++
540 [ Opt_WarnUnusedBinds,
541 Opt_WarnUnusedMatches,
542 Opt_WarnUnusedImports,
543 Opt_WarnIncompletePatterns,
549 [ Opt_WarnTypeDefaults,
550 Opt_WarnNameShadowing,
556 -- -----------------------------------------------------------------------------
557 -- CoreToDo: abstraction of core-to-core passes to run.
559 data CoreToDo -- These are diff core-to-core passes,
560 -- which may be invoked in any order,
561 -- as many times as you like.
563 = CoreDoSimplify -- The core-to-core simplifier.
566 -- Each run of the simplifier can take a different
567 -- set of simplifier-specific flags.
569 | CoreDoFloatOutwards FloatOutSwitches
574 | CoreDoWorkerWrapper
577 | CoreDoOldStrictness
580 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
581 -- matching this string
583 | CoreDoNothing -- useful when building up lists of these things
585 data SimplifierMode -- See comments in SimplMonad
589 data SimplifierSwitch
590 = MaxSimplifierIterations Int
593 data FloatOutSwitches
594 = FloatOutSw Bool -- True <=> float lambdas to top level
595 Bool -- True <=> float constants to top level,
596 -- even if they do not escape a lambda
599 -- The core-to-core pass ordering is derived from the DynFlags:
601 getCoreToDo :: DynFlags -> [CoreToDo]
603 | Just todo <- coreToDo dflags = todo -- set explicitly by user
604 | otherwise = core_todo
606 opt_level = optLevel dflags
607 max_iter = maxSimplIterations dflags
608 strictness = dopt Opt_Strictness dflags
609 full_laziness = dopt Opt_FullLaziness dflags
610 cse = dopt Opt_CSE dflags
611 rule_check = ruleCheck dflags
614 if opt_level == 0 then
616 CoreDoSimplify (SimplPhase 0) [
617 MaxSimplifierIterations max_iter
620 else {- opt_level >= 1 -} [
622 -- initial simplify: mk specialiser happy: minimum effort please
623 CoreDoSimplify SimplGently [
625 -- Don't inline anything till full laziness has bitten
626 -- In particular, inlining wrappers inhibits floating
627 -- e.g. ...(case f x of ...)...
628 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
629 -- ==> ...(case x of I# x# -> case fw x# of ...)...
630 -- and now the redex (f x) isn't floatable any more
631 -- Similarly, don't apply any rules until after full
632 -- laziness. Notably, list fusion can prevent floating.
635 -- Don't do case-of-case transformations.
636 -- This makes full laziness work better
637 MaxSimplifierIterations max_iter
640 -- Specialisation is best done before full laziness
641 -- so that overloaded functions have all their dictionary lambdas manifest
644 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
649 CoreDoSimplify (SimplPhase 2) [
650 -- Want to run with inline phase 2 after the specialiser to give
651 -- maximum chance for fusion to work before we inline build/augment
652 -- in phase 1. This made a difference in 'ansi' where an
653 -- overloaded function wasn't inlined till too late.
654 MaxSimplifierIterations max_iter
656 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
658 CoreDoSimplify (SimplPhase 1) [
659 -- Need inline-phase2 here so that build/augment get
660 -- inlined. I found that spectral/hartel/genfft lost some useful
661 -- strictness in the function sumcode' if augment is not inlined
662 -- before strictness analysis runs
663 MaxSimplifierIterations max_iter
665 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
667 CoreDoSimplify (SimplPhase 0) [
668 -- Phase 0: allow all Ids to be inlined now
669 -- This gets foldr inlined before strictness analysis
671 MaxSimplifierIterations 3
672 -- At least 3 iterations because otherwise we land up with
673 -- huge dead expressions because of an infelicity in the
675 -- let k = BIG in foldr k z xs
676 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
677 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
681 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
683 #ifdef OLD_STRICTNESS
686 if strictness then CoreDoStrictness else CoreDoNothing,
690 CoreDoSimplify (SimplPhase 0) [
691 MaxSimplifierIterations max_iter
694 if full_laziness then
695 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
696 True) -- Float constants
698 -- nofib/spectral/hartel/wang doubles in speed if you
699 -- do full laziness late in the day. It only happens
700 -- after fusion and other stuff, so the early pass doesn't
701 -- catch it. For the record, the redex is
702 -- f_el22 (f_el21 r_midblock)
705 -- We want CSE to follow the final full-laziness pass, because it may
706 -- succeed in commoning up things floated out by full laziness.
707 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
709 if cse then CoreCSE else CoreDoNothing,
713 -- Case-liberation for -O2. This should be after
714 -- strictness analysis and the simplification which follows it.
716 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
718 if opt_level >= 2 then
722 if opt_level >= 2 then
727 -- Final clean-up simplification:
728 CoreDoSimplify (SimplPhase 0) [
729 MaxSimplifierIterations max_iter
733 -- -----------------------------------------------------------------------------
734 -- StgToDo: abstraction of stg-to-stg passes to run.
737 = StgDoMassageForProfiling -- should be (next to) last
738 -- There's also setStgVarInfo, but its absolute "lastness"
739 -- is so critical that it is hardwired in (no flag).
742 getStgToDo :: DynFlags -> [StgToDo]
744 | Just todo <- stgToDo dflags = todo -- set explicitly by user
747 stg_stats = dopt Opt_StgStats dflags
749 todo1 = if stg_stats then [D_stg_stats] else []
751 todo2 | WayProf `elem` wayNames dflags
752 = StgDoMassageForProfiling : todo1
756 -- -----------------------------------------------------------------------------
759 dynamic_flags :: [(String, OptKind DynP)]
761 ( "n" , NoArg (setDynFlag Opt_DryRun) )
762 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
763 , ( "F" , NoArg (setDynFlag Opt_Pp))
764 , ( "#include" , HasArg (addCmdlineHCInclude) )
765 , ( "v" , OptPrefix (setVerbosity) )
767 ------- Specific phases --------------------------------------------
768 , ( "pgmL" , HasArg (upd . setPgmL) )
769 , ( "pgmP" , HasArg (upd . setPgmP) )
770 , ( "pgmF" , HasArg (upd . setPgmF) )
771 , ( "pgmc" , HasArg (upd . setPgmc) )
772 , ( "pgmm" , HasArg (upd . setPgmm) )
773 , ( "pgms" , HasArg (upd . setPgms) )
774 , ( "pgma" , HasArg (upd . setPgma) )
775 , ( "pgml" , HasArg (upd . setPgml) )
776 , ( "pgmdll" , HasArg (upd . setPgmdll) )
778 , ( "optL" , HasArg (upd . addOptL) )
779 , ( "optP" , HasArg (upd . addOptP) )
780 , ( "optF" , HasArg (upd . addOptF) )
781 , ( "optc" , HasArg (upd . addOptc) )
782 , ( "optm" , HasArg (upd . addOptm) )
783 , ( "opta" , HasArg (upd . addOpta) )
784 , ( "optl" , HasArg (upd . addOptl) )
785 , ( "optdll" , HasArg (upd . addOptdll) )
786 , ( "optdep" , HasArg (upd . addOptdep) )
788 , ( "split-objs" , NoArg (if can_split
789 then setDynFlag Opt_SplitObjs
792 -------- Linking ----------------------------------------------------
793 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
794 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
795 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
797 ------- Libraries ---------------------------------------------------
798 , ( "L" , Prefix addLibraryPath )
799 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
802 ------- Frameworks --------------------------------------------------
803 -- -framework-path should really be -F ...
804 , ( "framework-path" , HasArg addFrameworkPath )
805 , ( "framework" , HasArg (upd . addCmdlineFramework) )
807 ------- Output Redirection ------------------------------------------
808 , ( "odir" , HasArg (upd . setOutputDir . Just))
809 , ( "o" , SepArg (upd . setOutputFile . Just))
810 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
811 , ( "osuf" , HasArg (upd . setObjectSuf))
812 , ( "hcsuf" , HasArg (upd . setHcSuf))
813 , ( "hisuf" , HasArg (upd . setHiSuf))
814 , ( "hidir" , HasArg (upd . setHiDir . Just))
815 , ( "tmpdir" , HasArg (upd . setTmpDir))
817 ------- Keeping temporary files -------------------------------------
818 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
819 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
820 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
821 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
823 ------- Miscellaneous ----------------------------------------------
824 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
825 , ( "main-is" , SepArg setMainIs )
827 ------- recompilation checker --------------------------------------
828 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
829 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
831 ------- Packages ----------------------------------------------------
832 , ( "package-conf" , HasArg extraPkgConf_ )
833 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
834 , ( "package-name" , HasArg ignorePackage ) -- for compatibility
835 , ( "package" , HasArg exposePackage )
836 , ( "hide-package" , HasArg hidePackage )
837 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
838 , ( "ignore-package" , HasArg ignorePackage )
839 , ( "syslib" , HasArg exposePackage ) -- for compatibility
841 ------ HsCpp opts ---------------------------------------------------
842 , ( "D", AnySuffix (upd . addOptP) )
843 , ( "U", AnySuffix (upd . addOptP) )
845 ------- Include/Import Paths ----------------------------------------
846 , ( "I" , Prefix addIncludePath)
847 , ( "i" , OptPrefix addImportPath )
849 ------ Debugging ----------------------------------------------------
850 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
852 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
853 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
854 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
855 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
856 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
857 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
858 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
859 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
860 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
861 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
862 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
863 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
864 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
865 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
866 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
867 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
868 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
869 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
870 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
871 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
872 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
873 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
874 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
875 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
876 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
877 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
878 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
879 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
880 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
881 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
882 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
883 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
884 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
885 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
886 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
887 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
888 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
889 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
890 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
891 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
892 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
895 ------ Machine dependant (-m<blah>) stuff ---------------------------
897 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
898 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
899 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
901 ------ Warning opts -------------------------------------------------
902 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
903 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
904 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
905 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
906 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
908 ------ Optimisation flags ------------------------------------------
909 , ( "O" , NoArg (upd (setOptLevel 1)))
910 , ( "Onot" , NoArg (upd (setOptLevel 0)))
911 , ( "O" , PrefixPred (all isDigit)
912 (\f -> upd (setOptLevel (read f))))
914 , ( "fmax-simplifier-iterations",
915 PrefixPred (all isDigit)
917 dfs{ maxSimplIterations = read n })) )
920 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
922 ------ Compiler flags -----------------------------------------------
924 , ( "fno-code", NoArg (setTarget HscNothing))
925 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
926 , ( "fvia-c", NoArg (setTarget HscC) )
927 , ( "fvia-C", NoArg (setTarget HscC) )
928 , ( "filx", NoArg (setTarget HscILX) )
930 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
931 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
933 -- the rest of the -f* and -fno-* flags
934 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
935 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
938 -- these -f<blah> flags can all be reversed with -fno-<blah>
941 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
942 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
943 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
944 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
945 ( "warn-missing-fields", Opt_WarnMissingFields ),
946 ( "warn-missing-methods", Opt_WarnMissingMethods ),
947 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
948 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
949 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
950 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
951 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
952 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
953 ( "warn-unused-imports", Opt_WarnUnusedImports ),
954 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
955 ( "warn-deprecations", Opt_WarnDeprecations ),
956 ( "warn-orphans", Opt_WarnOrphans ),
957 ( "fi", Opt_FFI ), -- support `-ffi'...
958 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
959 ( "arrows", Opt_Arrows ), -- arrow syntax
960 ( "parr", Opt_PArr ),
962 ( "implicit-prelude", Opt_ImplicitPrelude ),
963 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
964 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
965 ( "implicit-params", Opt_ImplicitParams ),
966 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
967 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
968 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
969 ( "generics", Opt_Generics ),
970 ( "strictness", Opt_Strictness ),
971 ( "full-laziness", Opt_FullLaziness ),
973 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
974 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
975 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
976 ( "ignore-asserts", Opt_IgnoreAsserts ),
977 ( "do-eta-reduction", Opt_DoEtaReduction ),
978 ( "case-merge", Opt_CaseMerge ),
979 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
980 ( "excess-precision", Opt_ExcessPrecision ),
981 ( "asm-mangling", Opt_DoAsmMangling )
989 Opt_ScopedTypeVariables ]
991 isFFlag f = f `elem` (map fst fFlags)
992 getFFlag f = fromJust (lookup f fFlags)
994 -- -----------------------------------------------------------------------------
995 -- Parsing the dynamic flags.
997 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
998 parseDynamicFlags dflags args = do
999 let ((leftover,errs),dflags')
1000 = runCmdLine (processArgs dynamic_flags args) dflags
1001 when (not (null errs)) $ do
1002 throwDyn (UsageError (unlines errs))
1003 return (dflags', leftover)
1006 type DynP = CmdLineP DynFlags
1008 upd :: (DynFlags -> DynFlags) -> DynP ()
1010 dfs <- getCmdLineState
1011 putCmdLineState $! (f dfs)
1013 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1014 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1015 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1017 setDumpFlag :: DynFlag -> OptKind DynP
1018 setDumpFlag dump_flag
1019 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1020 -- Whenver we -ddump, switch off the recompilation checker,
1021 -- else you don't see the dump!
1023 setVerbosity "" = upd (\dfs -> dfs{ verbosity = 3 })
1025 | all isDigit n = upd (\dfs -> dfs{ verbosity = read n })
1026 | otherwise = throwDyn (UsageError "can't parse verbosity flag (-v<n>)")
1028 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1030 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1033 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1035 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1037 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1039 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1040 -- (-fvia-C, -fasm, -filx respectively).
1041 setTarget l = upd (\dfs -> case hscTarget dfs of
1042 HscC -> dfs{ hscTarget = l }
1043 HscAsm -> dfs{ hscTarget = l }
1044 HscILX -> dfs{ hscTarget = l }
1047 setOptLevel :: Int -> DynFlags -> DynFlags
1048 setOptLevel n dflags
1049 | hscTarget dflags == HscInterpreted && n > 0
1051 -- not in IO any more, oh well:
1052 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1054 = updOptLevel n dflags
1057 setMainIs :: String -> DynP ()
1059 | not (null main_fn) -- The arg looked like "Foo.baz"
1060 = upd $ \d -> d{ mainFunIs = Just main_fn,
1061 mainModIs = mkModule main_mod }
1063 | isUpper (head main_mod) -- The arg looked like "Foo"
1064 = upd $ \d -> d{ mainModIs = mkModule main_mod }
1066 | otherwise -- The arg looked like "baz"
1067 = upd $ \d -> d{ mainFunIs = Just main_mod }
1069 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1071 -----------------------------------------------------------------------------
1072 -- Paths & Libraries
1074 -- -i on its own deletes the import paths
1075 addImportPath "" = upd (\s -> s{importPaths = []})
1076 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1080 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1083 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1085 addFrameworkPath p =
1086 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1088 split_marker = ':' -- not configurable (ToDo)
1090 splitPathList :: String -> [String]
1091 splitPathList s = filter notNull (splitUp s)
1092 -- empty paths are ignored: there might be a trailing
1093 -- ':' in the initial list, for example. Empty paths can
1094 -- cause confusion when they are translated into -I options
1095 -- for passing to gcc.
1097 #ifndef mingw32_TARGET_OS
1098 splitUp xs = split split_marker xs
1100 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1102 -- That is, if "foo:bar:baz" is used, this interpreted as
1103 -- consisting of three entries, 'foo', 'bar', 'baz'.
1104 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1105 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1107 -- Notice that no attempt is made to fully replace the 'standard'
1108 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1109 -- that this will cause too much breakage for users & ':' will
1110 -- work fine even with DOS paths, if you're not insisting on being silly.
1113 splitUp (x:':':div:xs) | div `elem` dir_markers
1114 = ((x:':':div:p): splitUp rs)
1116 (p,rs) = findNextPath xs
1117 -- we used to check for existence of the path here, but that
1118 -- required the IO monad to be threaded through the command-line
1119 -- parser which is quite inconvenient. The
1120 splitUp xs = cons p (splitUp rs)
1122 (p,rs) = findNextPath xs
1127 -- will be called either when we've consumed nought or the
1128 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1129 -- finding the next split marker.
1131 case break (`elem` split_markers) xs of
1132 (p, d:ds) -> (p, ds)
1135 split_markers :: [Char]
1136 split_markers = [':', ';']
1138 dir_markers :: [Char]
1139 dir_markers = ['/', '\\']
1142 -- -----------------------------------------------------------------------------
1143 -- tmpDir, where we store temporary files.
1145 setTmpDir :: FilePath -> DynFlags -> DynFlags
1146 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1148 #if !defined(mingw32_HOST_OS)
1149 canonicalise p = normalisePath p
1151 -- Canonicalisation of temp path under win32 is a bit more
1152 -- involved: (a) strip trailing slash,
1153 -- (b) normalise slashes
1154 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1156 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1158 -- if we're operating under cygwin, and TMP/TEMP is of
1159 -- the form "/cygdrive/drive/path", translate this to
1160 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1161 -- understand /cygdrive paths.)
1163 | "/cygdrive/" `isPrefixOf` path =
1164 case drop (length "/cygdrive/") path of
1165 drive:xs@('/':_) -> drive:':':xs
1169 -- strip the trailing backslash (awful, but we only do this once).
1170 removeTrailingSlash path =
1177 -----------------------------------------------------------------------------
1178 -- Via-C compilation stuff
1180 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1181 [String]) -- for registerised HC compilations
1182 machdepCCOpts dflags
1183 #if alpha_TARGET_ARCH
1185 #ifdef HAVE_THREADED_RTS_SUPPORT
1189 -- For now, to suppress the gcc warning "call-clobbered
1190 -- register used for global register variable", we simply
1191 -- disable all warnings altogether using the -w flag. Oh well.
1193 #elif hppa_TARGET_ARCH
1194 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1195 -- (very nice, but too bad the HP /usr/include files don't agree.)
1196 = ( ["-D_HPUX_SOURCE"], [] )
1198 #elif m68k_TARGET_ARCH
1199 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1200 -- popping of args to routines to be explicit; if we let things
1201 -- be deferred 'til after an STGJUMP, imminent death is certain!
1203 -- -fomit-frame-pointer : *don't*
1204 -- It's better to have a6 completely tied up being a frame pointer
1205 -- rather than let GCC pick random things to do with it.
1206 -- (If we want to steal a6, then we would try to do things
1207 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1208 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1210 #elif i386_TARGET_ARCH
1211 -- -fno-defer-pop : basically the same game as for m68k
1213 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1214 -- the fp (%ebp) for our register maps.
1215 = let n_regs = stolen_x86_regs dflags
1218 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1219 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1222 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1223 -- Some gccs are configured with
1224 -- -momit-leaf-frame-pointer on by default, and it
1225 -- apparently takes precedence over
1226 -- -fomit-frame-pointer, so we disable it first here.
1227 "-mno-omit-leaf-frame-pointer",
1229 "-fomit-frame-pointer",
1230 -- we want -fno-builtin, because when gcc inlines
1231 -- built-in functions like memcpy() it tends to
1232 -- run out of registers, requiring -monly-n-regs
1234 "-DSTOLEN_X86_REGS="++show n_regs ]
1237 #elif ia64_TARGET_ARCH
1238 = ( [], ["-fomit-frame-pointer", "-G0"] )
1240 #elif x86_64_TARGET_ARCH
1241 = ( [], ["-fomit-frame-pointer",
1242 "-fno-asynchronous-unwind-tables"
1243 -- the unwind tables are unnecessary for HC code,
1244 -- and get in the way of -split-objs. Another option
1245 -- would be to throw them away in the mangler, but this
1249 #elif mips_TARGET_ARCH
1250 = ( ["-static"], [] )
1252 #elif sparc_TARGET_ARCH
1254 -- For now, to suppress the gcc warning "call-clobbered
1255 -- register used for global register variable", we simply
1256 -- disable all warnings altogether using the -w flag. Oh well.
1258 #elif powerpc_apple_darwin_TARGET
1260 -- Disable Apple's precompiling preprocessor. It's a great thing
1261 -- for "normal" programs, but it doesn't support register variable
1263 = ( [], ["-no-cpp-precomp"] )
1268 picCCOpts :: DynFlags -> [String]
1270 #if darwin_TARGET_OS
1271 -- Apple prefers to do things the other way round.
1272 -- PIC is on by default.
1273 -- -mdynamic-no-pic:
1274 -- Turn off PIC code generation.
1276 -- Don't generate "common" symbols - these are unwanted
1277 -- in dynamic libraries.
1282 = ["-mdynamic-no-pic"]
1283 #elif mingw32_TARGET_OS
1284 -- no -fPIC for Windows
1293 -- -----------------------------------------------------------------------------
1298 #if defined(i386_TARGET_ARCH) \
1299 || defined(x86_64_TARGET_ARCH) \
1300 || defined(alpha_TARGET_ARCH) \
1301 || defined(hppa_TARGET_ARCH) \
1302 || defined(m68k_TARGET_ARCH) \
1303 || defined(mips_TARGET_ARCH) \
1304 || defined(powerpc_TARGET_ARCH) \
1305 || defined(rs6000_TARGET_ARCH) \
1306 || defined(sparc_TARGET_ARCH)