2 % (c) The University of Glasgow, 1996-2000
4 \section[CmdLineOpts]{Things to do with command-line options}
9 CoreToDo(..), buildCoreToDo, StgToDo(..),
11 SimplifierMode(..), FloatOutSwitches(..),
14 DynFlag(..), -- needed non-abstractly by DriverFlags
21 -- Manipulating DynFlags
22 defaultDynFlags, -- DynFlags
23 defaultHscLang, -- HscLang
24 dopt, -- DynFlag -> DynFlags -> Bool
25 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
26 dopt_CoreToDo, -- DynFlags -> [CoreToDo]
27 dopt_StgToDo, -- DynFlags -> [StgToDo]
28 dopt_HscLang, -- DynFlags -> HscLang
29 dopt_OutName, -- DynFlags -> String
30 getOpts, -- (DynFlags -> [a]) -> IO [a]
35 -- Manipulating the DynFlags state
36 getDynFlags, -- IO DynFlags
37 setDynFlags, -- DynFlags -> IO ()
38 updDynFlags, -- (DynFlags -> DynFlags) -> IO ()
39 dynFlag, -- (DynFlags -> a) -> IO a
40 setDynFlag, unSetDynFlag, -- DynFlag -> IO ()
41 saveDynFlags, -- IO ()
42 restoreDynFlags, -- IO DynFlags
44 -- sets of warning opts
49 -- Output style options
51 opt_PprStyle_RawTypes,
56 opt_AutoSccsOnAllToplevs,
57 opt_AutoSccsOnExportedToplevs,
58 opt_AutoSccsOnIndividualCafs,
66 opt_MaxContextReductionDepth,
67 opt_IrrefutableTuples,
77 opt_LiberateCaseThreshold,
80 opt_SimplNoPreInlining,
81 opt_SimplExcessPrecision,
85 opt_UF_CreationThreshold,
87 opt_UF_FunAppDiscount,
96 opt_EnsureSplittableC,
108 #include "HsVersions.h"
110 import Constants -- Default values for some flags
112 import FastString ( FastString, mkFastString )
114 import Maybes ( firstJust )
117 import DATA_IOREF ( IORef, readIORef, writeIORef )
118 import UNSAFE_IO ( unsafePerformIO )
121 %************************************************************************
123 \subsection{Command-line options}
125 %************************************************************************
127 The hsc command-line options are split into two categories:
132 Static flags are represented by top-level values of type Bool or Int,
133 for example. They therefore have the same value throughout the
136 Dynamic flags are represented by an abstract type, DynFlags, which is
137 passed into hsc by the compilation manager for every compilation.
138 Dynamic flags are those that change on a per-compilation basis,
139 perhaps because they may be present in the OPTIONS pragma at the top
142 Other flag-related blurb:
144 A list of {\em ToDo}s is things to be done in a particular part of
145 processing. A (fictitious) example for the Core-to-Core simplifier
146 might be: run the simplifier, then run the strictness analyser, then
147 run the simplifier again (three ``todos'').
149 There are three ``to-do processing centers'' at the moment. In the
150 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
151 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
152 (\tr{simplStg/SimplStg.lhs}).
154 %************************************************************************
156 \subsection{Datatypes associated with command-line options}
158 %************************************************************************
161 data CoreToDo -- These are diff core-to-core passes,
162 -- which may be invoked in any order,
163 -- as many times as you like.
165 = CoreDoSimplify -- The core-to-core simplifier.
168 -- Each run of the simplifier can take a different
169 -- set of simplifier-specific flags.
171 | CoreDoFloatOutwards FloatOutSwitches
176 | CoreDoWorkerWrapper
179 | CoreDoOldStrictness
182 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
183 -- matching this string
185 | CoreDoNothing -- useful when building up lists of these things
190 = StgDoMassageForProfiling -- should be (next to) last
191 -- There's also setStgVarInfo, but its absolute "lastness"
192 -- is so critical that it is hardwired in (no flag).
197 data SimplifierMode -- See comments in SimplMonad
201 data SimplifierSwitch
202 = MaxSimplifierIterations Int
205 data FloatOutSwitches
206 = FloatOutSw Bool -- True <=> float lambdas to top level
207 Bool -- True <=> float constants to top level,
208 -- even if they do not escape a lambda
211 %************************************************************************
213 \subsection{Dynamic command-line options}
215 %************************************************************************
228 | Opt_D_dump_inlinings
229 | Opt_D_dump_occur_anal
234 | Opt_D_dump_simpl_iterations
243 | Opt_D_dump_worker_wrapper
244 | Opt_D_dump_rn_trace
245 | Opt_D_dump_rn_stats
247 | Opt_D_dump_simpl_stats
248 | Opt_D_dump_tc_trace
253 | Opt_D_verbose_core2core
254 | Opt_D_verbose_stg2stg
256 | Opt_D_dump_hi_diffs
257 | Opt_D_dump_minimal_imports
261 | Opt_WarnIsError -- -Werror; makes warnings fatal
262 | Opt_WarnDuplicateExports
264 | Opt_WarnIncompletePatterns
265 | Opt_WarnMissingFields
266 | Opt_WarnMissingMethods
267 | Opt_WarnMissingSigs
268 | Opt_WarnNameShadowing
269 | Opt_WarnOverlappingPatterns
270 | Opt_WarnSimplePatterns
271 | Opt_WarnTypeDefaults
272 | Opt_WarnUnusedBinds
273 | Opt_WarnUnusedImports
274 | Opt_WarnUnusedMatches
275 | Opt_WarnDeprecations
279 | Opt_AllowOverlappingInstances
280 | Opt_AllowUndecidableInstances
281 | Opt_AllowIncoherentInstances
282 | Opt_NoMonomorphismRestriction
285 | Opt_PArr -- syntactic support for parallel arrays
286 | Opt_Arrows -- Arrow-notation syntax
290 | Opt_NoImplicitPrelude
295 | Opt_IgnoreInterfacePragmas
296 | Opt_OmitInterfacePragmas
297 | Opt_DoLambdaEtaExpansion
301 | Opt_UnboxStrictFields
305 data DynFlags = DynFlags {
306 coreToDo :: Maybe [CoreToDo], -- reserved for use with -Ofile
307 stgToDo :: [StgToDo],
309 hscOutName :: String, -- name of the output file
310 hscStubHOutName :: String, -- name of the .stub_h output file
311 hscStubCOutName :: String, -- name of the .stub_c output file
312 extCoreName :: String, -- name of the .core output file
313 verbosity :: Int, -- verbosity level
314 optLevel :: Int, -- optimisation level
315 maxSimplIterations :: Int, -- max simplifier iterations
316 ruleCheck :: Maybe String,
317 cppFlag :: Bool, -- preprocess with cpp?
318 ppFlag :: Bool, -- preprocess with a Haskell Pp?
319 stolen_x86_regs :: Int,
320 cmdlineHcIncludes :: [String], -- -#includes
322 -- options for particular phases
348 | cGhcWithNativeCodeGen == "YES" &&
349 (prefixMatch "i386" cTARGETPLATFORM ||
350 prefixMatch "sparc" cTARGETPLATFORM ||
351 prefixMatch "powerpc" cTARGETPLATFORM) = HscAsm
354 defaultDynFlags = DynFlags {
355 coreToDo = Nothing, stgToDo = [],
356 hscLang = defaultHscLang,
358 hscStubHOutName = "", hscStubCOutName = "",
362 maxSimplIterations = 4,
367 cmdlineHcIncludes = [],
380 -- Generating the helper-functions for
381 -- generics is now on by default
383 -- strictness is on by default, but this only
386 -- similarly for CSE.
387 Opt_DoLambdaEtaExpansion
388 -- This one is important for a tiresome reason:
389 -- we want to make sure that the bindings for data
390 -- constructors are eta-expanded. This is probably
391 -- a good thing anyway, but it seems fragile.
392 ] ++ standardWarnings,
398 0 | print errors & warnings only
399 1 | minimal verbosity: print "compiling M ... done." for each module.
400 2 | equivalent to -dshow-passes
401 3 | equivalent to existing "ghc -v"
402 4 | "ghc -v -ddump-most"
403 5 | "ghc -v -ddump-all"
406 dopt :: DynFlag -> DynFlags -> Bool
407 dopt f dflags = f `elem` (flags dflags)
409 dopt_CoreToDo :: DynFlags -> Maybe [CoreToDo]
410 dopt_CoreToDo = coreToDo
412 dopt_StgToDo :: DynFlags -> [StgToDo]
413 dopt_StgToDo = stgToDo
415 dopt_OutName :: DynFlags -> String
416 dopt_OutName = hscOutName
418 dopt_HscLang :: DynFlags -> HscLang
419 dopt_HscLang = hscLang
421 dopt_set :: DynFlags -> DynFlag -> DynFlags
422 dopt_set dfs f = dfs{ flags = f : flags dfs }
424 dopt_unset :: DynFlags -> DynFlag -> DynFlags
425 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
427 getOpts :: (DynFlags -> [a]) -> IO [a]
428 -- We add to the options from the front, so we need to reverse the list
429 getOpts opts = dynFlag opts >>= return . reverse
431 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
432 -- (-fvia-C, -fasm, -filx respectively).
433 setLang l = updDynFlags (\ dfs -> case hscLang dfs of
434 HscC -> dfs{ hscLang = l }
435 HscAsm -> dfs{ hscLang = l }
436 HscILX -> dfs{ hscLang = l }
440 verb <- dynFlag verbosity
441 if verb >= 3 then return "-v" else return ""
443 -----------------------------------------------------------------------------
444 -- Setting the optimisation level
446 setOptLevel :: Int -> IO ()
448 = do dflags <- getDynFlags
449 if hscLang dflags == HscInterpreted && n > 0
450 then putStr "warning: -O conflicts with --interactive; -O ignored.\n"
451 else updDynFlags (setOptLevel' n)
455 then dfs2{ hscLang = HscC, optLevel = n } -- turn on -fvia-C with -O
456 else dfs2{ optLevel = n }
458 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
459 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
462 | n == 0 = opt_0_dopts
463 | otherwise = opt_1_dopts
466 | n == 0 = opt_1_dopts
467 | otherwise = opt_0_dopts
470 Opt_IgnoreInterfacePragmas,
471 Opt_OmitInterfacePragmas
480 -- Core-to-core phases:
482 buildCoreToDo :: DynFlags -> [CoreToDo]
483 buildCoreToDo dflags = core_todo
485 opt_level = optLevel dflags
486 max_iter = maxSimplIterations dflags
487 strictness = dopt Opt_Strictness dflags
488 cse = dopt Opt_CSE dflags
489 rule_check = ruleCheck dflags
492 if opt_level == 0 then
494 CoreDoSimplify (SimplPhase 0) [
495 MaxSimplifierIterations max_iter
499 else {- opt_level >= 1 -} [
501 -- initial simplify: mk specialiser happy: minimum effort please
502 CoreDoSimplify SimplGently [
504 -- Don't inline anything till full laziness has bitten
505 -- In particular, inlining wrappers inhibits floating
506 -- e.g. ...(case f x of ...)...
507 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
508 -- ==> ...(case x of I# x# -> case fw x# of ...)...
509 -- and now the redex (f x) isn't floatable any more
510 -- Similarly, don't apply any rules until after full
511 -- laziness. Notably, list fusion can prevent floating.
514 -- Don't do case-of-case transformations.
515 -- This makes full laziness work better
516 MaxSimplifierIterations max_iter
519 -- Specialisation is best done before full laziness
520 -- so that overloaded functions have all their dictionary lambdas manifest
523 CoreDoFloatOutwards (FloatOutSw False False),
526 CoreDoSimplify (SimplPhase 2) [
527 -- Want to run with inline phase 2 after the specialiser to give
528 -- maximum chance for fusion to work before we inline build/augment
529 -- in phase 1. This made a difference in 'ansi' where an
530 -- overloaded function wasn't inlined till too late.
531 MaxSimplifierIterations max_iter
533 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
535 CoreDoSimplify (SimplPhase 1) [
536 -- Need inline-phase2 here so that build/augment get
537 -- inlined. I found that spectral/hartel/genfft lost some useful
538 -- strictness in the function sumcode' if augment is not inlined
539 -- before strictness analysis runs
540 MaxSimplifierIterations max_iter
542 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
544 CoreDoSimplify (SimplPhase 0) [
545 -- Phase 0: allow all Ids to be inlined now
546 -- This gets foldr inlined before strictness analysis
548 MaxSimplifierIterations 3
549 -- At least 3 iterations because otherwise we land up with
550 -- huge dead expressions because of an infelicity in the
552 -- let k = BIG in foldr k z xs
553 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
554 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
558 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
560 #ifdef OLD_STRICTNESS
563 if strictness then CoreDoStrictness else CoreDoNothing,
567 CoreDoSimplify (SimplPhase 0) [
568 MaxSimplifierIterations max_iter
571 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
572 True), -- Float constants
573 -- nofib/spectral/hartel/wang doubles in speed if you
574 -- do full laziness late in the day. It only happens
575 -- after fusion and other stuff, so the early pass doesn't
576 -- catch it. For the record, the redex is
577 -- f_el22 (f_el21 r_midblock)
580 -- We want CSE to follow the final full-laziness pass, because it may
581 -- succeed in commoning up things floated out by full laziness.
582 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
584 if cse then CoreCSE else CoreDoNothing,
588 -- Case-liberation for -O2. This should be after
589 -- strictness analysis and the simplification which follows it.
591 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
593 if opt_level >= 2 then
597 if opt_level >= 2 then
602 -- Final clean-up simplification:
603 CoreDoSimplify (SimplPhase 0) [
604 MaxSimplifierIterations max_iter
608 -- --------------------------------------------------------------------------
609 -- Mess about with the mutable variables holding the dynamic arguments
612 -- is the "baseline" dynamic flags, initialised from
613 -- the defaults and command line options, and updated by the
614 -- ':s' command in GHCi.
617 -- is the dynamic flags for the current compilation. It is reset
618 -- to the value of v_InitDynFlags before each compilation, then
619 -- updated by reading any OPTIONS pragma in the current module.
621 GLOBAL_VAR(v_InitDynFlags, defaultDynFlags, DynFlags)
622 GLOBAL_VAR(v_DynFlags, defaultDynFlags, DynFlags)
624 setDynFlags :: DynFlags -> IO ()
625 setDynFlags dfs = writeIORef v_DynFlags dfs
627 saveDynFlags :: IO ()
628 saveDynFlags = do dfs <- readIORef v_DynFlags
629 writeIORef v_InitDynFlags dfs
631 restoreDynFlags :: IO DynFlags
632 restoreDynFlags = do dfs <- readIORef v_InitDynFlags
633 writeIORef v_DynFlags dfs
636 getDynFlags :: IO DynFlags
637 getDynFlags = readIORef v_DynFlags
639 updDynFlags :: (DynFlags -> DynFlags) -> IO ()
640 updDynFlags f = do dfs <- readIORef v_DynFlags
641 writeIORef v_DynFlags (f dfs)
643 dynFlag :: (DynFlags -> a) -> IO a
644 dynFlag f = do dflags <- readIORef v_DynFlags; return (f dflags)
646 setDynFlag, unSetDynFlag :: DynFlag -> IO ()
647 setDynFlag f = updDynFlags (\dfs -> dopt_set dfs f)
648 unSetDynFlag f = updDynFlags (\dfs -> dopt_unset dfs f)
652 %************************************************************************
654 \subsection{Warnings}
656 %************************************************************************
660 = [ Opt_WarnDeprecations,
661 Opt_WarnOverlappingPatterns,
662 Opt_WarnMissingFields,
663 Opt_WarnMissingMethods,
664 Opt_WarnDuplicateExports
668 = standardWarnings ++
669 [ Opt_WarnUnusedBinds,
670 Opt_WarnUnusedMatches,
671 Opt_WarnUnusedImports,
672 Opt_WarnIncompletePatterns,
678 [ Opt_WarnTypeDefaults,
679 Opt_WarnNameShadowing,
685 %************************************************************************
687 \subsection{Classifying command-line options}
689 %************************************************************************
692 -- v_Statis_hsc_opts is here to avoid a circular dependency with
694 GLOBAL_VAR(v_Static_hsc_opts, [], [String])
696 lookUp :: FastString -> Bool
697 lookup_int :: String -> Maybe Int
698 lookup_def_int :: String -> Int -> Int
699 lookup_def_float :: String -> Float -> Float
700 lookup_str :: String -> Maybe String
702 unpacked_static_opts = unsafePerformIO (readIORef v_Static_hsc_opts)
703 packed_static_opts = map mkFastString unpacked_static_opts
705 lookUp sw = sw `elem` packed_static_opts
707 lookup_str sw = firstJust (map (startsWith sw) unpacked_static_opts)
709 lookup_int sw = case (lookup_str sw) of
711 Just xx -> Just (read xx)
713 lookup_def_int sw def = case (lookup_str sw) of
714 Nothing -> def -- Use default
717 lookup_def_float sw def = case (lookup_str sw) of
718 Nothing -> def -- Use default
723 Putting the compiler options into temporary at-files
724 may turn out to be necessary later on if we turn hsc into
725 a pure Win32 application where I think there's a command-line
726 length limit of 255. unpacked_opts understands the @ option.
728 unpacked_opts :: [String]
732 map unpackFS argv -- NOT ARGV any more: v_Static_hsc_opts
734 expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
739 %************************************************************************
741 \subsection{Static options}
743 %************************************************************************
747 opt_PprStyle_NoPrags = lookUp FSLIT("-dppr-noprags")
748 opt_PprStyle_Debug = lookUp FSLIT("-dppr-debug")
749 opt_PprStyle_RawTypes = lookUp FSLIT("-dppr-rawtypes")
750 opt_PprUserLength = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
753 opt_AutoSccsOnAllToplevs = lookUp FSLIT("-fauto-sccs-on-all-toplevs")
754 opt_AutoSccsOnExportedToplevs = lookUp FSLIT("-fauto-sccs-on-exported-toplevs")
755 opt_AutoSccsOnIndividualCafs = lookUp FSLIT("-fauto-sccs-on-individual-cafs")
756 opt_AutoSccsOnDicts = lookUp FSLIT("-fauto-sccs-on-dicts")
757 opt_SccProfilingOn = lookUp FSLIT("-fscc-profiling")
758 opt_DoTickyProfiling = lookUp FSLIT("-fticky-ticky")
761 opt_AllStrict = lookUp FSLIT("-fall-strict")
762 opt_DictsStrict = lookUp FSLIT("-fdicts-strict")
763 opt_IrrefutableTuples = lookUp FSLIT("-firrefutable-tuples")
764 opt_MaxContextReductionDepth = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
765 opt_NumbersStrict = lookUp FSLIT("-fnumbers-strict")
766 opt_Parallel = lookUp FSLIT("-fparallel")
767 opt_SMP = lookUp FSLIT("-fsmp")
768 opt_Flatten = lookUp FSLIT("-fflatten")
771 opt_NoMethodSharing = lookUp FSLIT("-fno-method-sharing")
772 opt_DoSemiTagging = lookUp FSLIT("-fsemi-tagging")
773 opt_CprOff = lookUp FSLIT("-fcpr-off")
774 opt_RulesOff = lookUp FSLIT("-frules-off")
775 -- Switch off CPR analysis in the new demand analyser
776 opt_LiberateCaseThreshold = lookup_def_int "-fliberate-case-threshold" (10::Int)
777 opt_MaxWorkerArgs = lookup_def_int "-fmax-worker-args" (10::Int)
780 The optional '-inpackage=P' flag tells what package
781 we are compiling this module for.
782 The Prelude, for example is compiled with '-inpackage std'
784 opt_InPackage = case lookup_str "-inpackage=" of
785 Just p -> mkFastString p
786 Nothing -> FSLIT("Main") -- The package name if none is specified
788 opt_EmitCExternDecls = lookUp FSLIT("-femit-extern-decls")
789 opt_EnsureSplittableC = lookUp FSLIT("-fglobalise-toplev-names")
790 opt_GranMacros = lookUp FSLIT("-fgransim")
791 opt_HiVersion = read (cProjectVersionInt ++ cProjectPatchLevel) :: Int
792 opt_HistorySize = lookup_def_int "-fhistory-size" 20
793 opt_NoHiCheck = lookUp FSLIT("-fno-hi-version-check")
794 opt_OmitBlackHoling = lookUp FSLIT("-dno-black-holing")
795 opt_RuntimeTypes = lookUp FSLIT("-fruntime-types")
797 -- Simplifier switches
798 opt_SimplNoPreInlining = lookUp FSLIT("-fno-pre-inlining")
799 -- NoPreInlining is there just to see how bad things
800 -- get if you don't do it!
801 opt_SimplExcessPrecision = lookUp FSLIT("-fexcess-precision")
804 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
805 opt_UF_UseThreshold = lookup_def_int "-funfolding-use-threshold" (8::Int) -- Discounts can be big
806 opt_UF_FunAppDiscount = lookup_def_int "-funfolding-fun-discount" (6::Int) -- It's great to inline a fn
807 opt_UF_KeenessFactor = lookup_def_float "-funfolding-keeness-factor" (1.5::Float)
808 opt_UF_UpdateInPlace = lookUp FSLIT("-funfolding-update-in-place")
810 opt_UF_CheapOp = ( 1 :: Int) -- Only one instruction; and the args are charged for
811 opt_UF_DearOp = ( 4 :: Int)
813 opt_NoPruneDecls = lookUp FSLIT("-fno-prune-decls")
814 opt_Static = lookUp FSLIT("-static")
815 opt_Unregisterised = lookUp FSLIT("-funregisterised")
816 opt_EmitExternalCore = lookUp FSLIT("-fext-core")
819 %************************************************************************
821 \subsection{List of static hsc flags}
823 %************************************************************************
828 "fauto-sccs-on-all-toplevs",
829 "fauto-sccs-on-exported-toplevs",
830 "fauto-sccs-on-individual-cafs",
831 "fauto-sccs-on-dicts",
836 "firrefutable-tuples",
843 "femit-extern-decls",
844 "fglobalise-toplev-names",
846 "fno-hi-version-check",
848 "fno-method-sharing",
852 "funfolding-update-in-place",
861 || any (flip prefixMatch f) [
863 "fliberate-case-threshold",
866 "funfolding-creation-threshold",
867 "funfolding-use-threshold",
868 "funfolding-fun-discount",
869 "funfolding-keeness-factor"
873 %************************************************************************
875 \subsection{Misc functions for command-line options}
877 %************************************************************************
882 startsWith :: String -> String -> Maybe String
883 -- startsWith pfx (pfx++rest) = Just rest
885 startsWith [] str = Just str
886 startsWith (c:cs) (s:ss)
887 = if c /= s then Nothing else startsWith cs ss
888 startsWith _ [] = Nothing
890 endsWith :: String -> String -> Maybe String
892 = case (startsWith (reverse cs) (reverse ss)) of
894 Just rs -> Just (reverse rs)