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
22 -- Manipulating DynFlags
23 defaultDynFlags, -- DynFlags
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_HscTarget, -- DynFlags -> HscTarget
29 dopt_OutName, -- DynFlags -> String
30 getOpts, -- (DynFlags -> [a]) -> IO [a]
34 -- sets of warning opts
38 -- Output style options
43 opt_AutoSccsOnAllToplevs,
44 opt_AutoSccsOnExportedToplevs,
45 opt_AutoSccsOnIndividualCafs,
51 opt_MaxContextReductionDepth,
52 opt_IrrefutableTuples,
61 opt_LiberateCaseThreshold,
64 opt_SimplNoPreInlining,
65 opt_SimplExcessPrecision,
69 opt_UF_CreationThreshold,
71 opt_UF_FunAppDiscount,
79 opt_EnsureSplittableC,
90 #include "HsVersions.h"
92 import {-# SOURCE #-} Packages (PackageState)
93 import DriverPhases ( HscTarget(..) )
94 import Constants -- Default values for some flags
96 import FastString ( FastString, mkFastString )
98 import Maybes ( firstJust )
100 import Panic ( ghcError, GhcException(UsageError) )
102 import DATA_IOREF ( IORef, readIORef )
103 import UNSAFE_IO ( unsafePerformIO )
106 %************************************************************************
108 \subsection{Command-line options}
110 %************************************************************************
112 The hsc command-line options are split into two categories:
117 Static flags are represented by top-level values of type Bool or Int,
118 for example. They therefore have the same value throughout the
121 Dynamic flags are represented by an abstract type, DynFlags, which is
122 passed into hsc by the compilation manager for every compilation.
123 Dynamic flags are those that change on a per-compilation basis,
124 perhaps because they may be present in the OPTIONS pragma at the top
127 Other flag-related blurb:
129 A list of {\em ToDo}s is things to be done in a particular part of
130 processing. A (fictitious) example for the Core-to-Core simplifier
131 might be: run the simplifier, then run the strictness analyser, then
132 run the simplifier again (three ``todos'').
134 There are three ``to-do processing centers'' at the moment. In the
135 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
136 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
137 (\tr{simplStg/SimplStg.lhs}).
139 %************************************************************************
141 \subsection{Datatypes associated with command-line options}
143 %************************************************************************
146 data CoreToDo -- These are diff core-to-core passes,
147 -- which may be invoked in any order,
148 -- as many times as you like.
150 = CoreDoSimplify -- The core-to-core simplifier.
153 -- Each run of the simplifier can take a different
154 -- set of simplifier-specific flags.
156 | CoreDoFloatOutwards FloatOutSwitches
161 | CoreDoWorkerWrapper
164 | CoreDoOldStrictness
167 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
168 -- matching this string
170 | CoreDoNothing -- useful when building up lists of these things
175 = StgDoMassageForProfiling -- should be (next to) last
176 -- There's also setStgVarInfo, but its absolute "lastness"
177 -- is so critical that it is hardwired in (no flag).
182 data SimplifierMode -- See comments in SimplMonad
186 data SimplifierSwitch
187 = MaxSimplifierIterations Int
190 data FloatOutSwitches
191 = FloatOutSw Bool -- True <=> float lambdas to top level
192 Bool -- True <=> float constants to top level,
193 -- even if they do not escape a lambda
196 %************************************************************************
198 \subsection{Dynamic command-line options}
200 %************************************************************************
213 | Opt_D_dump_inlinings
214 | Opt_D_dump_occur_anal
218 | Opt_D_dump_simpl_iterations
227 | Opt_D_dump_worker_wrapper
228 | Opt_D_dump_rn_trace
229 | Opt_D_dump_rn_stats
231 | Opt_D_dump_simpl_stats
232 | Opt_D_dump_tc_trace
233 | Opt_D_dump_if_trace
238 | Opt_D_verbose_core2core
239 | Opt_D_verbose_stg2stg
241 | Opt_D_dump_hi_diffs
242 | Opt_D_dump_minimal_imports
247 | Opt_WarnIsError -- -Werror; makes warnings fatal
248 | Opt_WarnDuplicateExports
250 | Opt_WarnIncompletePatterns
251 | Opt_WarnIncompletePatternsRecUpd
252 | Opt_WarnMissingFields
253 | Opt_WarnMissingMethods
254 | Opt_WarnMissingSigs
255 | Opt_WarnNameShadowing
256 | Opt_WarnOverlappingPatterns
257 | Opt_WarnSimplePatterns
258 | Opt_WarnTypeDefaults
259 | Opt_WarnUnusedBinds
260 | Opt_WarnUnusedImports
261 | Opt_WarnUnusedMatches
262 | Opt_WarnDeprecations
263 | Opt_WarnDodgyImports
267 | Opt_AllowOverlappingInstances
268 | Opt_AllowUndecidableInstances
269 | Opt_AllowIncoherentInstances
270 | Opt_MonomorphismRestriction
273 | Opt_PArr -- syntactic support for parallel arrays
274 | Opt_Arrows -- Arrow-notation syntax
278 | Opt_ImplicitPrelude
279 | Opt_ScopedTypeVariables
285 | Opt_IgnoreInterfacePragmas
286 | Opt_OmitInterfacePragmas
287 | Opt_DoLambdaEtaExpansion
291 | Opt_UnboxStrictFields
295 data DynFlags = DynFlags {
296 coreToDo :: Maybe [CoreToDo], -- reserved for use with -Ofile
297 stgToDo :: [StgToDo],
298 hscTarget :: HscTarget,
299 hscOutName :: String, -- name of the output file
300 hscStubHOutName :: String, -- name of the .stub_h output file
301 hscStubCOutName :: String, -- name of the .stub_c output file
302 extCoreName :: String, -- name of the .core output file
303 verbosity :: Int, -- verbosity level
304 optLevel :: Int, -- optimisation level
305 maxSimplIterations :: Int, -- max simplifier iterations
306 ruleCheck :: Maybe String,
307 cppFlag :: Bool, -- preprocess with cpp?
308 ppFlag :: Bool, -- preprocess with a Haskell Pp?
309 recompFlag :: Bool, -- True <=> recompilation checker is on
310 stolen_x86_regs :: Int,
311 cmdlineHcIncludes :: [String], -- -#includes
312 importPaths :: [FilePath],
314 -- options for particular phases
327 extraPkgConfs :: [FilePath],
328 -- The -package-conf flags given on the command line, in the order
331 readUserPkgConf :: Bool,
332 -- Whether or not to read the user package database
333 -- (-no-user-package-conf).
335 packageFlags :: [PackageFlag],
336 -- The -package and -hide-package flags from the command-line
339 pkgState :: PackageState,
346 = ExposePackage String
348 | IgnorePackage String
351 | cGhcWithNativeCodeGen == "YES" &&
352 (prefixMatch "i386" cTARGETPLATFORM ||
353 prefixMatch "sparc" cTARGETPLATFORM ||
354 prefixMatch "powerpc" cTARGETPLATFORM) = HscAsm
357 defaultDynFlags = DynFlags {
358 coreToDo = Nothing, stgToDo = [],
359 hscTarget = defaultHscTarget,
361 hscStubHOutName = "", hscStubCOutName = "",
365 maxSimplIterations = 4,
371 cmdlineHcIncludes = [],
385 readUserPkgConf = True,
387 pkgState = error "pkgState",
391 Opt_MonomorphismRestriction,
393 -- Generating the helper-functions for
394 -- generics is now on by default
396 -- strictness is on by default, but this only
398 Opt_CSE, -- similarly for CSE.
399 Opt_FullLaziness, -- ...and for full laziness
401 Opt_DoLambdaEtaExpansion,
402 -- This one is important for a tiresome reason:
403 -- we want to make sure that the bindings for data
404 -- constructors are eta-expanded. This is probably
405 -- a good thing anyway, but it seems fragile.
407 -- and the default no-optimisation options:
408 Opt_IgnoreInterfacePragmas,
409 Opt_OmitInterfacePragmas
411 ] ++ standardWarnings
417 0 | print errors & warnings only
418 1 | minimal verbosity: print "compiling M ... done." for each module.
419 2 | equivalent to -dshow-passes
420 3 | equivalent to existing "ghc -v"
421 4 | "ghc -v -ddump-most"
422 5 | "ghc -v -ddump-all"
425 dopt :: DynFlag -> DynFlags -> Bool
426 dopt f dflags = f `elem` (flags dflags)
428 dopt_CoreToDo :: DynFlags -> Maybe [CoreToDo]
429 dopt_CoreToDo = coreToDo
431 dopt_StgToDo :: DynFlags -> [StgToDo]
432 dopt_StgToDo = stgToDo
434 dopt_OutName :: DynFlags -> String
435 dopt_OutName = hscOutName
437 dopt_HscTarget :: DynFlags -> HscTarget
438 dopt_HscTarget = hscTarget
440 dopt_set :: DynFlags -> DynFlag -> DynFlags
441 dopt_set dfs f = dfs{ flags = f : flags dfs }
443 dopt_unset :: DynFlags -> DynFlag -> DynFlags
444 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
446 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
447 -- We add to the options from the front, so we need to reverse the list
448 getOpts dflags opts = reverse (opts dflags)
451 | verbosity dflags >= 3 = "-v"
454 -----------------------------------------------------------------------------
455 -- Setting the optimisation level
459 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
460 else dfs2{ optLevel = n }
462 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
463 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
466 | n == 0 = opt_0_dopts
467 | otherwise = opt_1_dopts
470 | n == 0 = opt_1_dopts
471 | otherwise = opt_0_dopts
474 Opt_IgnoreInterfacePragmas,
475 Opt_OmitInterfacePragmas
484 -- Core-to-core phases:
486 buildCoreToDo :: DynFlags -> [CoreToDo]
487 buildCoreToDo dflags = core_todo
489 opt_level = optLevel dflags
490 max_iter = maxSimplIterations dflags
491 strictness = dopt Opt_Strictness dflags
492 full_laziness = dopt Opt_FullLaziness dflags
493 cse = dopt Opt_CSE dflags
494 rule_check = ruleCheck dflags
497 if opt_level == 0 then
499 CoreDoSimplify (SimplPhase 0) [
500 MaxSimplifierIterations max_iter
504 else {- opt_level >= 1 -} [
506 -- initial simplify: mk specialiser happy: minimum effort please
507 CoreDoSimplify SimplGently [
509 -- Don't inline anything till full laziness has bitten
510 -- In particular, inlining wrappers inhibits floating
511 -- e.g. ...(case f x of ...)...
512 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
513 -- ==> ...(case x of I# x# -> case fw x# of ...)...
514 -- and now the redex (f x) isn't floatable any more
515 -- Similarly, don't apply any rules until after full
516 -- laziness. Notably, list fusion can prevent floating.
519 -- Don't do case-of-case transformations.
520 -- This makes full laziness work better
521 MaxSimplifierIterations max_iter
524 -- Specialisation is best done before full laziness
525 -- so that overloaded functions have all their dictionary lambdas manifest
528 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
533 CoreDoSimplify (SimplPhase 2) [
534 -- Want to run with inline phase 2 after the specialiser to give
535 -- maximum chance for fusion to work before we inline build/augment
536 -- in phase 1. This made a difference in 'ansi' where an
537 -- overloaded function wasn't inlined till too late.
538 MaxSimplifierIterations max_iter
540 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
542 CoreDoSimplify (SimplPhase 1) [
543 -- Need inline-phase2 here so that build/augment get
544 -- inlined. I found that spectral/hartel/genfft lost some useful
545 -- strictness in the function sumcode' if augment is not inlined
546 -- before strictness analysis runs
547 MaxSimplifierIterations max_iter
549 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
551 CoreDoSimplify (SimplPhase 0) [
552 -- Phase 0: allow all Ids to be inlined now
553 -- This gets foldr inlined before strictness analysis
555 MaxSimplifierIterations 3
556 -- At least 3 iterations because otherwise we land up with
557 -- huge dead expressions because of an infelicity in the
559 -- let k = BIG in foldr k z xs
560 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
561 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
565 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
567 #ifdef OLD_STRICTNESS
570 if strictness then CoreDoStrictness else CoreDoNothing,
574 CoreDoSimplify (SimplPhase 0) [
575 MaxSimplifierIterations max_iter
578 if full_laziness then
579 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
580 True) -- Float constants
582 -- nofib/spectral/hartel/wang doubles in speed if you
583 -- do full laziness late in the day. It only happens
584 -- after fusion and other stuff, so the early pass doesn't
585 -- catch it. For the record, the redex is
586 -- f_el22 (f_el21 r_midblock)
589 -- We want CSE to follow the final full-laziness pass, because it may
590 -- succeed in commoning up things floated out by full laziness.
591 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
593 if cse then CoreCSE else CoreDoNothing,
597 -- Case-liberation for -O2. This should be after
598 -- strictness analysis and the simplification which follows it.
600 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
602 if opt_level >= 2 then
606 if opt_level >= 2 then
611 -- Final clean-up simplification:
612 CoreDoSimplify (SimplPhase 0) [
613 MaxSimplifierIterations max_iter
618 %************************************************************************
620 \subsection{Warnings}
622 %************************************************************************
626 = [ Opt_WarnDeprecations,
627 Opt_WarnOverlappingPatterns,
628 Opt_WarnMissingFields,
629 Opt_WarnMissingMethods,
630 Opt_WarnDuplicateExports
634 = standardWarnings ++
635 [ Opt_WarnUnusedBinds,
636 Opt_WarnUnusedMatches,
637 Opt_WarnUnusedImports,
638 Opt_WarnIncompletePatterns,
644 [ Opt_WarnTypeDefaults,
645 Opt_WarnNameShadowing,
652 %************************************************************************
654 \subsection{Classifying command-line options}
656 %************************************************************************
659 -- v_Statis_hsc_opts is here to avoid a circular dependency with
661 GLOBAL_VAR(v_Static_hsc_opts, [], [String])
663 lookUp :: FastString -> Bool
664 lookup_def_int :: String -> Int -> Int
665 lookup_def_float :: String -> Float -> Float
666 lookup_str :: String -> Maybe String
668 unpacked_static_opts = unsafePerformIO (readIORef v_Static_hsc_opts)
669 packed_static_opts = map mkFastString unpacked_static_opts
671 lookUp sw = sw `elem` packed_static_opts
673 -- (lookup_str "foo") looks for the flag -foo=X or -fooX,
674 -- and returns the string X
676 = case firstJust (map (startsWith sw) unpacked_static_opts) of
677 Just ('=' : str) -> Just str
681 lookup_def_int sw def = case (lookup_str sw) of
682 Nothing -> def -- Use default
683 Just xx -> try_read sw xx
685 lookup_def_float sw def = case (lookup_str sw) of
686 Nothing -> def -- Use default
687 Just xx -> try_read sw xx
690 try_read :: Read a => String -> String -> a
691 -- (try_read sw str) tries to read s; if it fails, it
692 -- bleats about flag sw
695 ((x,_):_) -> x -- Be forgiving: ignore trailing goop, and alternative parses
696 [] -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
697 -- ToDo: hack alert. We should really parse the arugments
698 -- and announce errors in a more civilised way.
702 Putting the compiler options into temporary at-files
703 may turn out to be necessary later on if we turn hsc into
704 a pure Win32 application where I think there's a command-line
705 length limit of 255. unpacked_opts understands the @ option.
707 unpacked_opts :: [String]
711 map unpackFS argv -- NOT ARGV any more: v_Static_hsc_opts
713 expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
718 %************************************************************************
720 \subsection{Static options}
722 %************************************************************************
726 opt_PprStyle_Debug = lookUp FSLIT("-dppr-debug")
727 opt_PprUserLength = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
730 opt_AutoSccsOnAllToplevs = lookUp FSLIT("-fauto-sccs-on-all-toplevs")
731 opt_AutoSccsOnExportedToplevs = lookUp FSLIT("-fauto-sccs-on-exported-toplevs")
732 opt_AutoSccsOnIndividualCafs = lookUp FSLIT("-fauto-sccs-on-individual-cafs")
733 opt_SccProfilingOn = lookUp FSLIT("-fscc-profiling")
734 opt_DoTickyProfiling = lookUp FSLIT("-fticky-ticky")
737 opt_DictsStrict = lookUp FSLIT("-fdicts-strict")
738 opt_IrrefutableTuples = lookUp FSLIT("-firrefutable-tuples")
739 opt_MaxContextReductionDepth = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
740 opt_Parallel = lookUp FSLIT("-fparallel")
741 opt_SMP = lookUp FSLIT("-fsmp")
742 opt_Flatten = lookUp FSLIT("-fflatten")
745 opt_NoStateHack = lookUp FSLIT("-fno-state-hack")
746 opt_NoMethodSharing = lookUp FSLIT("-fno-method-sharing")
747 opt_CprOff = lookUp FSLIT("-fcpr-off")
748 opt_RulesOff = lookUp FSLIT("-frules-off")
749 -- Switch off CPR analysis in the new demand analyser
750 opt_LiberateCaseThreshold = lookup_def_int "-fliberate-case-threshold" (10::Int)
751 opt_MaxWorkerArgs = lookup_def_int "-fmax-worker-args" (10::Int)
753 opt_EmitCExternDecls = lookUp FSLIT("-femit-extern-decls")
754 opt_EnsureSplittableC = lookUp FSLIT("-fglobalise-toplev-names")
755 opt_GranMacros = lookUp FSLIT("-fgransim")
756 opt_HiVersion = read (cProjectVersionInt ++ cProjectPatchLevel) :: Int
757 opt_HistorySize = lookup_def_int "-fhistory-size" 20
758 opt_OmitBlackHoling = lookUp FSLIT("-dno-black-holing")
759 opt_RuntimeTypes = lookUp FSLIT("-fruntime-types")
761 -- Simplifier switches
762 opt_SimplNoPreInlining = lookUp FSLIT("-fno-pre-inlining")
763 -- NoPreInlining is there just to see how bad things
764 -- get if you don't do it!
765 opt_SimplExcessPrecision = lookUp FSLIT("-fexcess-precision")
768 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
769 opt_UF_UseThreshold = lookup_def_int "-funfolding-use-threshold" (8::Int) -- Discounts can be big
770 opt_UF_FunAppDiscount = lookup_def_int "-funfolding-fun-discount" (6::Int) -- It's great to inline a fn
771 opt_UF_KeenessFactor = lookup_def_float "-funfolding-keeness-factor" (1.5::Float)
772 opt_UF_UpdateInPlace = lookUp FSLIT("-funfolding-update-in-place")
774 opt_UF_DearOp = ( 4 :: Int)
776 opt_Static = lookUp FSLIT("-static")
777 opt_Unregisterised = lookUp FSLIT("-funregisterised")
778 opt_EmitExternalCore = lookUp FSLIT("-fext-core")
780 -- Include full span info in error messages, instead of just the start position.
781 opt_ErrorSpans = lookUp FSLIT("-ferror-spans")
783 opt_PIC = lookUp FSLIT("-fPIC")
786 %************************************************************************
788 \subsection{List of static hsc flags}
790 %************************************************************************
795 "fauto-sccs-on-all-toplevs",
796 "fauto-sccs-on-exported-toplevs",
797 "fauto-sccs-on-individual-cafs",
798 "fauto-sccs-on-dicts",
803 "firrefutable-tuples",
809 "femit-extern-decls",
810 "fglobalise-toplev-names",
812 "fno-hi-version-check",
814 "fno-method-sharing",
819 "funfolding-update-in-place",
829 || any (flip prefixMatch f) [
831 "fliberate-case-threshold",
834 "funfolding-creation-threshold",
835 "funfolding-use-threshold",
836 "funfolding-fun-discount",
837 "funfolding-keeness-factor"
841 %************************************************************************
843 \subsection{Misc functions for command-line options}
845 %************************************************************************
850 startsWith :: String -> String -> Maybe String
851 -- startsWith pfx (pfx++rest) = Just rest
853 startsWith [] str = Just str
854 startsWith (c:cs) (s:ss)
855 = if c /= s then Nothing else startsWith cs ss
856 startsWith _ [] = Nothing