Remove the large ghci banner, and the flags to choose which banner to show
[ghc-hetmet.git] / compiler / main / DynFlags.hs
1
2 {-# OPTIONS -fno-warn-missing-fields #-}
3 -----------------------------------------------------------------------------
4 --
5 -- Dynamic flags
6 --
7 -- Most flags are dynamic flags, which means they can change from
8 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
9 -- multi-session GHC each session can be using different dynamic
10 -- flags.  Dynamic flags can also be set at the prompt in GHCi.
11 --
12 -- (c) The University of Glasgow 2005
13 --
14 -----------------------------------------------------------------------------
15
16 module DynFlags (
17         -- Dynamic flags
18         DynFlag(..),
19         DynFlags(..),
20         HscTarget(..), isObjectTarget, defaultObjectTarget,
21         GhcMode(..), isOneShot,
22         GhcLink(..), isNoLink,
23         PackageFlag(..),
24         Option(..),
25
26         -- Configuration of the core-to-core and stg-to-stg phases
27         CoreToDo(..),
28         StgToDo(..),
29         SimplifierSwitch(..), 
30         SimplifierMode(..), FloatOutSwitches(..),
31         getCoreToDo, getStgToDo,
32         
33         -- Manipulating DynFlags
34         defaultDynFlags,                -- DynFlags
35         initDynFlags,                   -- DynFlags -> IO DynFlags
36
37         dopt,                           -- DynFlag -> DynFlags -> Bool
38         dopt_set, dopt_unset,           -- DynFlags -> DynFlag -> DynFlags
39         getOpts,                        -- (DynFlags -> [a]) -> IO [a]
40         getVerbFlag,
41         updOptLevel,
42         setTmpDir,
43         setPackageName,
44         
45         -- parsing DynFlags
46         parseDynamicFlags,
47         allFlags,
48
49         -- misc stuff
50         machdepCCOpts, picCCOpts
51   ) where
52
53 #include "HsVersions.h"
54
55 import Module           ( Module, mkModuleName, mkModule )
56 import PackageConfig
57 import PrelNames        ( mAIN )
58 #ifdef i386_TARGET_ARCH
59 import StaticFlags      ( opt_Static )
60 #endif
61 import StaticFlags      ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
62                           v_RTS_Build_tag )
63 import {-# SOURCE #-} Packages (PackageState)
64 import DriverPhases     ( Phase(..), phaseInputExt )
65 import Config
66 import CmdLineParser
67 import Constants        ( mAX_CONTEXT_REDUCTION_DEPTH )
68 import Panic            ( panic, GhcException(..) )
69 import UniqFM           ( UniqFM )
70 import Util             ( notNull, splitLongestPrefix, normalisePath )
71 import Maybes           ( orElse, fromJust )
72 import SrcLoc           ( SrcSpan )
73 import Outputable
74 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
75
76 import Data.IORef       ( readIORef )
77 import Control.Exception ( throwDyn )
78 import Control.Monad    ( when )
79 #ifdef mingw32_TARGET_OS
80 import Data.List        ( isPrefixOf )
81 #else
82 import Util             ( split )
83 #endif
84
85 import Data.Char        ( isUpper, toLower )
86 import System.IO        ( hPutStrLn, stderr )
87
88 -- -----------------------------------------------------------------------------
89 -- DynFlags
90
91 data DynFlag
92
93    -- debugging flags
94    = Opt_D_dump_cmm
95    | Opt_D_dump_asm
96    | Opt_D_dump_cpranal
97    | Opt_D_dump_deriv
98    | Opt_D_dump_ds
99    | Opt_D_dump_flatC
100    | Opt_D_dump_foreign
101    | Opt_D_dump_inlinings
102    | Opt_D_dump_rule_firings
103    | Opt_D_dump_occur_anal
104    | Opt_D_dump_parsed
105    | Opt_D_dump_rn
106    | Opt_D_dump_simpl
107    | Opt_D_dump_simpl_iterations
108    | Opt_D_dump_spec
109    | Opt_D_dump_prep
110    | Opt_D_dump_stg
111    | Opt_D_dump_stranal
112    | Opt_D_dump_tc
113    | Opt_D_dump_types
114    | Opt_D_dump_rules
115    | Opt_D_dump_cse
116    | Opt_D_dump_worker_wrapper
117    | Opt_D_dump_rn_trace
118    | Opt_D_dump_rn_stats
119    | Opt_D_dump_opt_cmm
120    | Opt_D_dump_simpl_stats
121    | Opt_D_dump_tc_trace
122    | Opt_D_dump_if_trace
123    | Opt_D_dump_splices
124    | Opt_D_dump_BCOs
125    | Opt_D_dump_vect
126    | Opt_D_dump_hpc
127    | Opt_D_source_stats
128    | Opt_D_verbose_core2core
129    | Opt_D_verbose_stg2stg
130    | Opt_D_dump_hi
131    | Opt_D_dump_hi_diffs
132    | Opt_D_dump_minimal_imports
133    | Opt_D_dump_mod_cycles
134    | Opt_D_faststring_stats
135    | Opt_DoCoreLinting
136    | Opt_DoStgLinting
137    | Opt_DoCmmLinting
138
139    | Opt_WarnIsError            -- -Werror; makes warnings fatal
140    | Opt_WarnDuplicateExports
141    | Opt_WarnHiShadows
142    | Opt_WarnImplicitPrelude
143    | Opt_WarnIncompletePatterns
144    | Opt_WarnIncompletePatternsRecUpd
145    | Opt_WarnMissingFields
146    | Opt_WarnMissingMethods
147    | Opt_WarnMissingSigs
148    | Opt_WarnNameShadowing
149    | Opt_WarnOverlappingPatterns
150    | Opt_WarnSimplePatterns
151    | Opt_WarnTypeDefaults
152    | Opt_WarnMonomorphism
153    | Opt_WarnUnusedBinds
154    | Opt_WarnUnusedImports
155    | Opt_WarnUnusedMatches
156    | Opt_WarnDeprecations
157    | Opt_WarnDodgyImports
158    | Opt_WarnOrphans
159    | Opt_WarnTabs
160
161    -- language opts
162    | Opt_AllowOverlappingInstances
163    | Opt_AllowUndecidableInstances
164    | Opt_AllowIncoherentInstances
165    | Opt_MonomorphismRestriction
166    | Opt_MonoPatBinds
167    | Opt_ExtendedDefaultRules           -- Use GHC's extended rules for defaulting
168    | Opt_GlasgowExts
169    | Opt_FFI
170    | Opt_PArr                           -- Syntactic support for parallel arrays
171    | Opt_Arrows                         -- Arrow-notation syntax
172    | Opt_TH
173    | Opt_ImplicitParams
174    | Opt_Generics
175    | Opt_ImplicitPrelude 
176    | Opt_ScopedTypeVariables
177    | Opt_BangPatterns
178    | Opt_TypeFamilies
179    | Opt_OverloadedStrings
180    | Opt_DisambiguateRecordFields
181    | Opt_RecordWildCards
182    | Opt_RecordPuns
183    | Opt_GADTs
184    | Opt_RelaxedPolyRec                 -- -X=RelaxedPolyRec
185
186    -- optimisation opts
187    | Opt_Strictness
188    | Opt_FullLaziness
189    | Opt_CSE
190    | Opt_LiberateCase
191    | Opt_SpecConstr
192    | Opt_IgnoreInterfacePragmas
193    | Opt_OmitInterfacePragmas
194    | Opt_DoLambdaEtaExpansion
195    | Opt_IgnoreAsserts
196    | Opt_IgnoreBreakpoints
197    | Opt_DoEtaReduction
198    | Opt_CaseMerge
199    | Opt_UnboxStrictFields
200    | Opt_DictsCheap
201    | Opt_RewriteRules
202
203    -- misc opts
204    | Opt_Cpp
205    | Opt_Pp
206    | Opt_ForceRecomp
207    | Opt_DryRun
208    | Opt_DoAsmMangling
209    | Opt_ExcessPrecision
210    | Opt_ReadUserPackageConf
211    | Opt_NoHsMain
212    | Opt_SplitObjs
213    | Opt_StgStats
214    | Opt_HideAllPackages
215    | Opt_PrintBindResult
216    | Opt_Haddock
217    | Opt_Hpc_No_Auto
218    | Opt_BreakOnException
219
220    -- keeping stuff
221    | Opt_KeepHiDiffs
222    | Opt_KeepHcFiles
223    | Opt_KeepSFiles
224    | Opt_KeepRawSFiles
225    | Opt_KeepTmpFiles
226
227    deriving (Eq)
228  
229 data DynFlags = DynFlags {
230   ghcMode               :: GhcMode,
231   ghcLink               :: GhcLink,
232   coreToDo              :: Maybe [CoreToDo], -- reserved for -Ofile
233   stgToDo               :: Maybe [StgToDo],  -- similarly
234   hscTarget             :: HscTarget,
235   hscOutName            :: String,      -- name of the output file
236   extCoreName           :: String,      -- name of the .core output file
237   verbosity             :: Int,         -- verbosity level
238   optLevel              :: Int,         -- optimisation level
239   maxSimplIterations    :: Int,         -- max simplifier iterations
240   ruleCheck             :: Maybe String,
241
242   specThreshold         :: Int,         -- Threshold for function specialisation
243
244   stolen_x86_regs       :: Int,         
245   cmdlineHcIncludes     :: [String],    -- -#includes
246   importPaths           :: [FilePath],
247   mainModIs             :: Module,
248   mainFunIs             :: Maybe String,
249   ctxtStkDepth          :: Int,         -- Typechecker context stack depth
250
251   thisPackage           :: PackageId,
252
253   -- ways
254   wayNames              :: [WayName],   -- way flags from the cmd line
255   buildTag              :: String,      -- the global "way" (eg. "p" for prof)
256   rtsBuildTag           :: String,      -- the RTS "way"
257   
258   -- paths etc.
259   objectDir             :: Maybe String,
260   hiDir                 :: Maybe String,
261   stubDir               :: Maybe String,
262
263   objectSuf             :: String,
264   hcSuf                 :: String,
265   hiSuf                 :: String,
266
267   outputFile            :: Maybe String,
268   outputHi              :: Maybe String,
269
270   includePaths          :: [String],
271   libraryPaths          :: [String],
272   frameworkPaths        :: [String],    -- used on darwin only
273   cmdlineFrameworks     :: [String],    -- ditto
274   tmpDir                :: String,      -- no trailing '/'
275   
276   ghcUsagePath          :: FilePath,    -- Filled in by SysTools
277   ghciUsagePath         :: FilePath,    -- ditto
278
279   hpcDir                :: String,      -- ^ path to store the .mix files
280
281   -- options for particular phases
282   opt_L                 :: [String],
283   opt_P                 :: [String],
284   opt_F                 :: [String],
285   opt_c                 :: [String],
286   opt_m                 :: [String],
287   opt_a                 :: [String],
288   opt_l                 :: [String],
289   opt_dll               :: [String],
290   opt_dep               :: [String],
291
292   -- commands for particular phases
293   pgm_L                 :: String,
294   pgm_P                 :: (String,[Option]),
295   pgm_F                 :: String,
296   pgm_c                 :: (String,[Option]),
297   pgm_m                 :: (String,[Option]),
298   pgm_s                 :: (String,[Option]),
299   pgm_a                 :: (String,[Option]),
300   pgm_l                 :: (String,[Option]),
301   pgm_dll               :: (String,[Option]),
302   pgm_T                 :: String,
303   pgm_sysman            :: String,
304
305   --  Package flags
306   extraPkgConfs         :: [FilePath],
307   topDir                :: FilePath,    -- filled in by SysTools
308   systemPackageConfig   :: FilePath,    -- ditto
309         -- The -package-conf flags given on the command line, in the order
310         -- they appeared.
311
312   packageFlags          :: [PackageFlag],
313         -- The -package and -hide-package flags from the command-line
314
315   -- Package state
316   -- NB. do not modify this field, it is calculated by 
317   -- Packages.initPackages and Packages.updatePackages.
318   pkgDatabase           :: Maybe (UniqFM InstalledPackageInfo),
319   pkgState              :: PackageState,
320
321   -- hsc dynamic flags
322   flags                 :: [DynFlag],
323   
324   -- message output
325   log_action            :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
326  }
327
328 data HscTarget
329   = HscC
330   | HscAsm
331   | HscJava
332   | HscInterpreted
333   | HscNothing
334   deriving (Eq, Show)
335
336 -- | will this target result in an object file on the disk?
337 isObjectTarget :: HscTarget -> Bool
338 isObjectTarget HscC     = True
339 isObjectTarget HscAsm   = True
340 isObjectTarget _        = False
341
342 -- | The 'GhcMode' tells us whether we're doing multi-module
343 -- compilation (controlled via the "GHC" API) or one-shot
344 -- (single-module) compilation.  This makes a difference primarily to
345 -- the "Finder": in one-shot mode we look for interface files for
346 -- imported modules, but in multi-module mode we look for source files
347 -- in order to check whether they need to be recompiled.
348 data GhcMode
349   = CompManager         -- ^ --make, GHCi, etc.
350   | OneShot             -- ^ ghc -c Foo.hs
351   | MkDepend            -- ^ ghc -M, see Finder for why we need this
352   deriving Eq
353
354 isOneShot :: GhcMode -> Bool
355 isOneShot OneShot = True
356 isOneShot _other  = False
357
358 -- | What kind of linking to do.
359 data GhcLink    -- What to do in the link step, if there is one
360   = NoLink              -- Don't link at all
361   | LinkBinary          -- Link object code into a binary
362   | LinkInMemory        -- Use the in-memory dynamic linker
363   | LinkDynLib          -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
364   deriving Eq
365
366 isNoLink :: GhcLink -> Bool
367 isNoLink NoLink = True
368 isNoLink other  = False
369
370 data PackageFlag
371   = ExposePackage  String
372   | HidePackage    String
373   | IgnorePackage  String
374   deriving Eq
375
376 defaultHscTarget = defaultObjectTarget
377
378 -- | the 'HscTarget' value corresponding to the default way to create
379 -- object files on the current platform.
380 defaultObjectTarget
381   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
382   | otherwise                           =  HscC
383
384 initDynFlags dflags = do
385  -- someday these will be dynamic flags
386  ways <- readIORef v_Ways
387  build_tag <- readIORef v_Build_tag
388  rts_build_tag <- readIORef v_RTS_Build_tag
389  return dflags{
390         wayNames        = ways,
391         buildTag        = build_tag,
392         rtsBuildTag     = rts_build_tag
393         }
394
395 defaultDynFlags =
396      DynFlags {
397         ghcMode                 = CompManager,
398         ghcLink                 = LinkBinary,
399         coreToDo                = Nothing,
400         stgToDo                 = Nothing, 
401         hscTarget               = defaultHscTarget, 
402         hscOutName              = "", 
403         extCoreName             = "",
404         verbosity               = 0, 
405         optLevel                = 0,
406         maxSimplIterations      = 4,
407         ruleCheck               = Nothing,
408         specThreshold           = 200,
409         stolen_x86_regs         = 4,
410         cmdlineHcIncludes       = [],
411         importPaths             = ["."],
412         mainModIs               = mAIN,
413         mainFunIs               = Nothing,
414         ctxtStkDepth            = mAX_CONTEXT_REDUCTION_DEPTH,
415
416         thisPackage             = mainPackageId,
417
418         objectDir               = Nothing,
419         hiDir                   = Nothing,
420         stubDir                 = Nothing,
421
422         objectSuf               = phaseInputExt StopLn,
423         hcSuf                   = phaseInputExt HCc,
424         hiSuf                   = "hi",
425
426         outputFile              = Nothing,
427         outputHi                = Nothing,
428         includePaths            = [],
429         libraryPaths            = [],
430         frameworkPaths          = [],
431         cmdlineFrameworks       = [],
432         tmpDir                  = cDEFAULT_TMPDIR,
433         
434         hpcDir                  = ".hpc",
435
436         opt_L                   = [],
437         opt_P                   = [],
438         opt_F                   = [],
439         opt_c                   = [],
440         opt_a                   = [],
441         opt_m                   = [],
442         opt_l                   = [],
443         opt_dll                 = [],
444         opt_dep                 = [],
445         
446         extraPkgConfs           = [],
447         packageFlags            = [],
448         pkgDatabase             = Nothing,
449         pkgState                = panic "no package state yet: call GHC.setSessionDynFlags",
450         flags = [ 
451             Opt_ReadUserPackageConf,
452     
453             Opt_MonoPatBinds,   -- Experimentally, I'm making this non-standard
454                                 -- behaviour the default, to see if anyone notices
455                                 -- SLPJ July 06
456
457             Opt_ImplicitPrelude,
458             Opt_MonomorphismRestriction,
459
460             Opt_DoAsmMangling,
461     
462             -- on by default:
463             Opt_PrintBindResult ]
464             ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
465                     -- The default -O0 options
466             ++ standardWarnings,
467                
468         log_action = \severity srcSpan style msg -> 
469                         case severity of
470                           SevInfo  -> hPutStrLn stderr (show (msg style))
471                           SevFatal -> hPutStrLn stderr (show (msg style))
472                           _        -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
473       }
474
475 {- 
476     Verbosity levels:
477         
478     0   |   print errors & warnings only
479     1   |   minimal verbosity: print "compiling M ... done." for each module.
480     2   |   equivalent to -dshow-passes
481     3   |   equivalent to existing "ghc -v"
482     4   |   "ghc -v -ddump-most"
483     5   |   "ghc -v -ddump-all"
484 -}
485
486 dopt :: DynFlag -> DynFlags -> Bool
487 dopt f dflags  = f `elem` (flags dflags)
488
489 dopt_set :: DynFlags -> DynFlag -> DynFlags
490 dopt_set dfs f = dfs{ flags = f : flags dfs }
491
492 dopt_unset :: DynFlags -> DynFlag -> DynFlags
493 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
494
495 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
496 getOpts dflags opts = reverse (opts dflags)
497         -- We add to the options from the front, so we need to reverse the list
498
499 getVerbFlag :: DynFlags -> String
500 getVerbFlag dflags 
501   | verbosity dflags >= 3  = "-v" 
502   | otherwise =  ""
503
504 setObjectDir  f d = d{ objectDir  = f}
505 setHiDir      f d = d{ hiDir      = f}
506 setStubDir    f d = d{ stubDir    = f}
507
508 setObjectSuf  f d = d{ objectSuf  = f}
509 setHiSuf      f d = d{ hiSuf      = f}
510 setHcSuf      f d = d{ hcSuf      = f}
511
512 setOutputFile f d = d{ outputFile = f}
513 setOutputHi   f d = d{ outputHi   = f}
514
515 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
516 -- Config.hs should really use Option.
517 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
518
519 setPgmL   f d = d{ pgm_L   = f}
520 setPgmF   f d = d{ pgm_F   = f}
521 setPgmc   f d = d{ pgm_c   = (f,[])}
522 setPgmm   f d = d{ pgm_m   = (f,[])}
523 setPgms   f d = d{ pgm_s   = (f,[])}
524 setPgma   f d = d{ pgm_a   = (f,[])}
525 setPgml   f d = d{ pgm_l   = (f,[])}
526 setPgmdll f d = d{ pgm_dll = (f,[])}
527
528 addOptL   f d = d{ opt_L   = f : opt_L d}
529 addOptP   f d = d{ opt_P   = f : opt_P d}
530 addOptF   f d = d{ opt_F   = f : opt_F d}
531 addOptc   f d = d{ opt_c   = f : opt_c d}
532 addOptm   f d = d{ opt_m   = f : opt_m d}
533 addOpta   f d = d{ opt_a   = f : opt_a d}
534 addOptl   f d = d{ opt_l   = f : opt_l d}
535 addOptdll f d = d{ opt_dll = f : opt_dll d}
536 addOptdep f d = d{ opt_dep = f : opt_dep d}
537
538 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
539
540 -- -----------------------------------------------------------------------------
541 -- Command-line options
542
543 -- When invoking external tools as part of the compilation pipeline, we
544 -- pass these a sequence of options on the command-line. Rather than
545 -- just using a list of Strings, we use a type that allows us to distinguish
546 -- between filepaths and 'other stuff'. [The reason being, of course, that
547 -- this type gives us a handle on transforming filenames, and filenames only,
548 -- to whatever format they're expected to be on a particular platform.]
549
550 data Option
551  = FileOption -- an entry that _contains_ filename(s) / filepaths.
552               String  -- a non-filepath prefix that shouldn't be 
553                       -- transformed (e.g., "/out=")
554               String  -- the filepath/filename portion
555  | Option     String
556  
557 -----------------------------------------------------------------------------
558 -- Setting the optimisation level
559
560 updOptLevel :: Int -> DynFlags -> DynFlags
561 -- Set dynflags appropriate to the optimisation level
562 updOptLevel n dfs
563   = dfs2{ optLevel = final_n }
564   where
565    final_n = max 0 (min 2 n)    -- Clamp to 0 <= n <= 2
566    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
567    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
568
569    extra_dopts  = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
570    remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
571         
572 optLevelFlags :: [([Int], DynFlag)]
573 optLevelFlags
574   = [ ([0],     Opt_IgnoreInterfacePragmas)
575     , ([0],     Opt_OmitInterfacePragmas)
576
577     , ([1,2],   Opt_IgnoreAsserts)
578     , ([1,2],   Opt_RewriteRules)       -- Off for -O0; see Note [Scoping for Builtin rules]
579                                         --              in PrelRules
580     , ([1,2],   Opt_DoEtaReduction)
581     , ([1,2],   Opt_CaseMerge)
582     , ([1,2],   Opt_Strictness)
583     , ([1,2],   Opt_CSE)
584     , ([1,2],   Opt_FullLaziness)
585
586     , ([2],     Opt_LiberateCase)
587     , ([2],     Opt_SpecConstr)
588
589     , ([0,1,2], Opt_DoLambdaEtaExpansion)
590                 -- This one is important for a tiresome reason:
591                 -- we want to make sure that the bindings for data 
592                 -- constructors are eta-expanded.  This is probably
593                 -- a good thing anyway, but it seems fragile.
594     ]
595
596 -- -----------------------------------------------------------------------------
597 -- Standard sets of warning options
598
599 standardWarnings
600     = [ Opt_WarnDeprecations,
601         Opt_WarnOverlappingPatterns,
602         Opt_WarnMissingFields,
603         Opt_WarnMissingMethods,
604         Opt_WarnDuplicateExports
605       ]
606
607 minusWOpts
608     = standardWarnings ++ 
609       [ Opt_WarnUnusedBinds,
610         Opt_WarnUnusedMatches,
611         Opt_WarnUnusedImports,
612         Opt_WarnIncompletePatterns,
613         Opt_WarnDodgyImports
614       ]
615
616 minusWallOpts
617     = minusWOpts ++
618       [ Opt_WarnTypeDefaults,
619         Opt_WarnNameShadowing,
620         Opt_WarnMissingSigs,
621         Opt_WarnHiShadows,
622         Opt_WarnOrphans
623       ]
624
625 -- -----------------------------------------------------------------------------
626 -- CoreToDo:  abstraction of core-to-core passes to run.
627
628 data CoreToDo           -- These are diff core-to-core passes,
629                         -- which may be invoked in any order,
630                         -- as many times as you like.
631
632   = CoreDoSimplify      -- The core-to-core simplifier.
633         SimplifierMode
634         [SimplifierSwitch]
635                         -- Each run of the simplifier can take a different
636                         -- set of simplifier-specific flags.
637   | CoreDoFloatInwards
638   | CoreDoFloatOutwards FloatOutSwitches
639   | CoreLiberateCase
640   | CoreDoPrintCore
641   | CoreDoStaticArgs
642   | CoreDoStrictness
643   | CoreDoWorkerWrapper
644   | CoreDoSpecialising
645   | CoreDoSpecConstr
646   | CoreDoOldStrictness
647   | CoreDoGlomBinds
648   | CoreCSE
649   | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules 
650                                                 -- matching this string
651   | CoreDoNothing                -- Useful when building up 
652   | CoreDoPasses [CoreToDo]      -- lists of these things
653
654 data SimplifierMode             -- See comments in SimplMonad
655   = SimplGently
656   | SimplPhase Int
657
658 data SimplifierSwitch
659   = MaxSimplifierIterations Int
660   | NoCaseOfCase
661
662 data FloatOutSwitches
663   = FloatOutSw  Bool    -- True <=> float lambdas to top level
664                 Bool    -- True <=> float constants to top level,
665                         --          even if they do not escape a lambda
666
667
668 -- The core-to-core pass ordering is derived from the DynFlags:
669 runWhen :: Bool -> CoreToDo -> CoreToDo
670 runWhen True  do_this = do_this
671 runWhen False do_this = CoreDoNothing
672
673 getCoreToDo :: DynFlags -> [CoreToDo]
674 getCoreToDo dflags
675   | Just todo <- coreToDo dflags = todo -- set explicitly by user
676   | otherwise = core_todo
677   where
678     opt_level     = optLevel dflags
679     max_iter      = maxSimplIterations dflags
680     strictness    = dopt Opt_Strictness dflags
681     full_laziness = dopt Opt_FullLaziness dflags
682     cse           = dopt Opt_CSE dflags
683     spec_constr   = dopt Opt_SpecConstr dflags
684     liberate_case = dopt Opt_LiberateCase dflags
685     rule_check    = ruleCheck dflags
686
687     core_todo = 
688      if opt_level == 0 then
689       [
690         CoreDoSimplify (SimplPhase 0) [
691             MaxSimplifierIterations max_iter
692         ]
693       ]
694      else {- opt_level >= 1 -} [ 
695
696         -- initial simplify: mk specialiser happy: minimum effort please
697         CoreDoSimplify SimplGently [
698                         --      Simplify "gently"
699                         -- Don't inline anything till full laziness has bitten
700                         -- In particular, inlining wrappers inhibits floating
701                         -- e.g. ...(case f x of ...)...
702                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
703                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
704                         -- and now the redex (f x) isn't floatable any more
705                         -- Similarly, don't apply any rules until after full 
706                         -- laziness.  Notably, list fusion can prevent floating.
707
708             NoCaseOfCase,       -- Don't do case-of-case transformations.
709                                 -- This makes full laziness work better
710             MaxSimplifierIterations max_iter
711         ],
712
713         -- Specialisation is best done before full laziness
714         -- so that overloaded functions have all their dictionary lambdas manifest
715         CoreDoSpecialising,
716
717         runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
718
719         CoreDoFloatInwards,
720
721         CoreDoSimplify (SimplPhase 2) [
722                 -- Want to run with inline phase 2 after the specialiser to give
723                 -- maximum chance for fusion to work before we inline build/augment
724                 -- in phase 1.  This made a difference in 'ansi' where an 
725                 -- overloaded function wasn't inlined till too late.
726            MaxSimplifierIterations max_iter
727         ],
728         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
729
730         CoreDoSimplify (SimplPhase 1) [
731                 -- Need inline-phase2 here so that build/augment get 
732                 -- inlined.  I found that spectral/hartel/genfft lost some useful
733                 -- strictness in the function sumcode' if augment is not inlined
734                 -- before strictness analysis runs
735            MaxSimplifierIterations max_iter
736         ],
737         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
738
739         CoreDoSimplify (SimplPhase 0) [
740                 -- Phase 0: allow all Ids to be inlined now
741                 -- This gets foldr inlined before strictness analysis
742
743            MaxSimplifierIterations 3
744                 -- At least 3 iterations because otherwise we land up with
745                 -- huge dead expressions because of an infelicity in the 
746                 -- simpifier.   
747                 --      let k = BIG in foldr k z xs
748                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
749                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
750                 -- Don't stop now!
751
752         ],
753         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
754
755 #ifdef OLD_STRICTNESS
756         CoreDoOldStrictness,
757 #endif
758         runWhen strictness (CoreDoPasses [
759                 CoreDoStrictness,
760                 CoreDoWorkerWrapper,
761                 CoreDoGlomBinds,
762                 CoreDoSimplify (SimplPhase 0) [
763                    MaxSimplifierIterations max_iter
764                 ]]),
765
766         runWhen full_laziness 
767           (CoreDoFloatOutwards (FloatOutSw False    -- Not lambdas
768                                            True)),  -- Float constants
769                 -- nofib/spectral/hartel/wang doubles in speed if you
770                 -- do full laziness late in the day.  It only happens
771                 -- after fusion and other stuff, so the early pass doesn't
772                 -- catch it.  For the record, the redex is 
773                 --        f_el22 (f_el21 r_midblock)
774
775
776         runWhen cse CoreCSE,
777                 -- We want CSE to follow the final full-laziness pass, because it may
778                 -- succeed in commoning up things floated out by full laziness.
779                 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
780
781         CoreDoFloatInwards,
782
783         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
784
785                 -- Case-liberation for -O2.  This should be after
786                 -- strictness analysis and the simplification which follows it.
787         runWhen liberate_case (CoreDoPasses [
788             CoreLiberateCase,
789             CoreDoSimplify (SimplPhase 0) [
790                   MaxSimplifierIterations max_iter
791             ] ]),       -- Run the simplifier after LiberateCase to vastly 
792                         -- reduce the possiblility of shadowing
793                         -- Reason: see Note [Shadowing] in SpecConstr.lhs
794
795         runWhen spec_constr CoreDoSpecConstr,
796
797         -- Final clean-up simplification:
798         CoreDoSimplify (SimplPhase 0) [
799           MaxSimplifierIterations max_iter
800         ]
801      ]
802
803 -- -----------------------------------------------------------------------------
804 -- StgToDo:  abstraction of stg-to-stg passes to run.
805
806 data StgToDo
807   = StgDoMassageForProfiling  -- should be (next to) last
808   -- There's also setStgVarInfo, but its absolute "lastness"
809   -- is so critical that it is hardwired in (no flag).
810   | D_stg_stats
811
812 getStgToDo :: DynFlags -> [StgToDo]
813 getStgToDo dflags
814   | Just todo <- stgToDo dflags = todo -- set explicitly by user
815   | otherwise = todo2
816   where
817         stg_stats = dopt Opt_StgStats dflags
818
819         todo1 = if stg_stats then [D_stg_stats] else []
820
821         todo2 | WayProf `elem` wayNames dflags
822               = StgDoMassageForProfiling : todo1
823               | otherwise
824               = todo1
825
826 -- -----------------------------------------------------------------------------
827 -- DynFlags parser
828
829 allFlags :: [String]
830 allFlags = map ('-':) $
831            [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
832            map ("fno-"++) flags ++
833            map ("f"++) flags
834     where ok (PrefixPred _ _) = False
835           ok _ = True
836           flags = map fst fFlags
837
838 dynamic_flags :: [(String, OptKind DynP)]
839 dynamic_flags = [
840      ( "n"              , NoArg  (setDynFlag Opt_DryRun) )
841   ,  ( "cpp"            , NoArg  (setDynFlag Opt_Cpp))
842   ,  ( "F"              , NoArg  (setDynFlag Opt_Pp))
843   ,  ( "#include"       , HasArg (addCmdlineHCInclude) )
844   ,  ( "v"              , OptIntSuffix setVerbosity )
845
846         ------- Specific phases  --------------------------------------------
847   ,  ( "pgmL"           , HasArg (upd . setPgmL) )  
848   ,  ( "pgmP"           , HasArg (upd . setPgmP) )  
849   ,  ( "pgmF"           , HasArg (upd . setPgmF) )  
850   ,  ( "pgmc"           , HasArg (upd . setPgmc) )  
851   ,  ( "pgmm"           , HasArg (upd . setPgmm) )  
852   ,  ( "pgms"           , HasArg (upd . setPgms) )  
853   ,  ( "pgma"           , HasArg (upd . setPgma) )  
854   ,  ( "pgml"           , HasArg (upd . setPgml) )  
855   ,  ( "pgmdll"         , HasArg (upd . setPgmdll) )
856
857   ,  ( "optL"           , HasArg (upd . addOptL) )  
858   ,  ( "optP"           , HasArg (upd . addOptP) )  
859   ,  ( "optF"           , HasArg (upd . addOptF) )  
860   ,  ( "optc"           , HasArg (upd . addOptc) )  
861   ,  ( "optm"           , HasArg (upd . addOptm) )  
862   ,  ( "opta"           , HasArg (upd . addOpta) )  
863   ,  ( "optl"           , HasArg (upd . addOptl) )  
864   ,  ( "optdll"         , HasArg (upd . addOptdll) )  
865   ,  ( "optdep"         , HasArg (upd . addOptdep) )
866
867   ,  ( "split-objs"     , NoArg (if can_split
868                                     then setDynFlag Opt_SplitObjs
869                                     else return ()) )
870
871         -------- Linking ----------------------------------------------------
872   ,  ( "c"              , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
873   ,  ( "no-link"        , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
874   ,  ( "shared"         , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
875
876         ------- Libraries ---------------------------------------------------
877   ,  ( "L"              , Prefix addLibraryPath )
878   ,  ( "l"              , AnySuffix (\s -> do upd (addOptl s)
879                                               upd (addOptdll s)))
880
881         ------- Frameworks --------------------------------------------------
882         -- -framework-path should really be -F ...
883   ,  ( "framework-path" , HasArg addFrameworkPath )
884   ,  ( "framework"      , HasArg (upd . addCmdlineFramework) )
885
886         ------- Output Redirection ------------------------------------------
887   ,  ( "odir"           , HasArg (upd . setObjectDir  . Just))
888   ,  ( "o"              , SepArg (upd . setOutputFile . Just))
889   ,  ( "ohi"            , HasArg (upd . setOutputHi   . Just ))
890   ,  ( "osuf"           , HasArg (upd . setObjectSuf))
891   ,  ( "hcsuf"          , HasArg (upd . setHcSuf))
892   ,  ( "hisuf"          , HasArg (upd . setHiSuf))
893   ,  ( "hidir"          , HasArg (upd . setHiDir . Just))
894   ,  ( "tmpdir"         , HasArg (upd . setTmpDir))
895   ,  ( "stubdir"        , HasArg (upd . setStubDir . Just))
896
897         ------- Keeping temporary files -------------------------------------
898      -- These can be singular (think ghc -c) or plural (think ghc --make)
899   ,  ( "keep-hc-file"    , NoArg (setDynFlag Opt_KeepHcFiles))
900   ,  ( "keep-hc-files"   , NoArg (setDynFlag Opt_KeepHcFiles))
901   ,  ( "keep-s-file"     , NoArg (setDynFlag Opt_KeepSFiles))
902   ,  ( "keep-s-files"    , NoArg (setDynFlag Opt_KeepSFiles))
903   ,  ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
904   ,  ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
905      -- This only makes sense as plural
906   ,  ( "keep-tmp-files"  , NoArg (setDynFlag Opt_KeepTmpFiles))
907
908         ------- Miscellaneous ----------------------------------------------
909   ,  ( "no-hs-main"     , NoArg (setDynFlag Opt_NoHsMain))
910   ,  ( "main-is"        , SepArg setMainIs )
911   ,  ( "haddock"        , NoArg (setDynFlag Opt_Haddock) )
912   ,  ( "hpcdir"         , SepArg setOptHpcDir )
913
914         ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
915   ,  ( "recomp"         , NoArg (unSetDynFlag Opt_ForceRecomp) )
916   ,  ( "no-recomp"      , NoArg (setDynFlag   Opt_ForceRecomp) )
917
918         ------- Packages ----------------------------------------------------
919   ,  ( "package-conf"   , HasArg extraPkgConf_ )
920   ,  ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
921   ,  ( "package-name"   , HasArg (upd . setPackageName) )
922   ,  ( "package"        , HasArg exposePackage )
923   ,  ( "hide-package"   , HasArg hidePackage )
924   ,  ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
925   ,  ( "ignore-package" , HasArg ignorePackage )
926   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
927
928         ------ HsCpp opts ---------------------------------------------------
929   ,  ( "D",             AnySuffix (upd . addOptP) )
930   ,  ( "U",             AnySuffix (upd . addOptP) )
931
932         ------- Include/Import Paths ----------------------------------------
933   ,  ( "I"              , Prefix    addIncludePath)
934   ,  ( "i"              , OptPrefix addImportPath )
935
936         ------ Debugging ----------------------------------------------------
937   ,  ( "dstg-stats",    NoArg (setDynFlag Opt_StgStats))
938
939   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
940   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
941   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
942   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
943   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
944   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
945   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
946   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
947   ,  ( "ddump-rule-firings",     setDumpFlag Opt_D_dump_rule_firings)
948   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
949   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
950   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
951   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
952   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
953   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
954   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
955   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
956   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
957   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
958   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
959   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
960   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
961   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
962   ,  ( "ddump-rn-trace",         setDumpFlag Opt_D_dump_rn_trace)
963   ,  ( "ddump-if-trace",         setDumpFlag Opt_D_dump_if_trace)
964   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
965   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
966   ,  ( "ddump-rn-stats",         setDumpFlag Opt_D_dump_rn_stats)
967   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
968   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
969   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
970   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
971   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
972   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
973   ,  ( "ddump-hi-diffs",         setDumpFlag Opt_D_dump_hi_diffs)
974   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
975   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
976   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
977   ,  ( "ddump-hpc",              setDumpFlag Opt_D_dump_hpc)
978   ,  ( "ddump-mod-cycles",       setDumpFlag Opt_D_dump_mod_cycles)
979   
980   ,  ( "dcore-lint",             NoArg (setDynFlag Opt_DoCoreLinting))
981   ,  ( "dstg-lint",              NoArg (setDynFlag Opt_DoStgLinting))
982   ,  ( "dcmm-lint",              NoArg (setDynFlag Opt_DoCmmLinting))
983   ,  ( "dshow-passes",           NoArg (do setDynFlag Opt_ForceRecomp
984                                            setVerbosity (Just 2)) )
985   ,  ( "dfaststring-stats",      NoArg (setDynFlag Opt_D_faststring_stats))
986
987         ------ Machine dependant (-m<blah>) stuff ---------------------------
988
989   ,  ( "monly-2-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
990   ,  ( "monly-3-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
991   ,  ( "monly-4-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
992
993         ------ Warning opts -------------------------------------------------
994   ,  ( "W"              , NoArg (mapM_ setDynFlag   minusWOpts)    )
995   ,  ( "Werror"         , NoArg (setDynFlag         Opt_WarnIsError) )
996   ,  ( "Wall"           , NoArg (mapM_ setDynFlag   minusWallOpts) )
997   ,  ( "Wnot"           , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
998   ,  ( "w"              , NoArg (mapM_ unSetDynFlag minusWallOpts) )
999
1000         ------ Optimisation flags ------------------------------------------
1001   ,  ( "O"      , NoArg (upd (setOptLevel 1)))
1002   ,  ( "Onot"   , NoArg (upd (setOptLevel 0)))
1003   ,  ( "O"      , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1004                 -- If the number is missing, use 1
1005
1006   ,  ( "fmax-simplifier-iterations", IntSuffix (\n -> 
1007                 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1008
1009         -- liberate-case-threshold is an old flag for '-fspec-threshold'
1010   ,  ( "fspec-threshold",          IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1011   ,  ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1012
1013   ,  ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1014   ,  ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1015
1016         ------ Compiler flags -----------------------------------------------
1017
1018   ,  ( "fasm",          NoArg (setObjTarget HscAsm) )
1019   ,  ( "fvia-c",        NoArg (setObjTarget HscC) )
1020   ,  ( "fvia-C",        NoArg (setObjTarget HscC) )
1021
1022   ,  ( "fno-code",      NoArg (setTarget HscNothing))
1023   ,  ( "fbyte-code",    NoArg (setTarget HscInterpreted) )
1024   ,  ( "fobject-code",  NoArg (setTarget defaultHscTarget) )
1025
1026   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
1027   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1028
1029         -- the rest of the -f* and -fno-* flags
1030   ,  ( "f",             PrefixPred (isFlag fFlags)   (\f -> setDynFlag   (getFlag fFlags f)) )
1031   ,  ( "f",             PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1032
1033         -- For now, allow -X flags with -f; ToDo: report this as deprecated
1034   ,  ( "f",             PrefixPred (isFlag xFlags) (\f ->  setDynFlag (getFlag xFlags f)) )
1035   ,  ( "f",             PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1036
1037         -- the rest of the -X* and -Xno-* flags
1038   ,  ( "X",             PrefixPred (isFlag xFlags)   (\f -> setDynFlag   (getFlag xFlags f)) )
1039   ,  ( "X",             PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1040  ]
1041
1042 -- these -f<blah> flags can all be reversed with -fno-<blah>
1043
1044 fFlags = [
1045   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
1046   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
1047   ( "warn-implicit-prelude",            Opt_WarnImplicitPrelude ),
1048   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
1049   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
1050   ( "warn-missing-fields",              Opt_WarnMissingFields ),
1051   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
1052   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
1053   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
1054   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
1055   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
1056   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
1057   ( "warn-monomorphism-restriction",    Opt_WarnMonomorphism ),
1058   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
1059   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
1060   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
1061   ( "warn-deprecations",                Opt_WarnDeprecations ),
1062   ( "warn-orphans",                     Opt_WarnOrphans ),
1063   ( "warn-tabs",                        Opt_WarnTabs ),
1064   ( "strictness",                       Opt_Strictness ),
1065   ( "full-laziness",                    Opt_FullLaziness ),
1066   ( "liberate-case",                    Opt_LiberateCase ),
1067   ( "spec-constr",                      Opt_SpecConstr ),
1068   ( "cse",                              Opt_CSE ),
1069   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
1070   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
1071   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
1072   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
1073   ( "ignore-breakpoints",               Opt_IgnoreBreakpoints),
1074   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
1075   ( "case-merge",                       Opt_CaseMerge ),
1076   ( "unbox-strict-fields",              Opt_UnboxStrictFields ),
1077   ( "dicts-cheap",                      Opt_DictsCheap ),
1078   ( "excess-precision",                 Opt_ExcessPrecision ),
1079   ( "asm-mangling",                     Opt_DoAsmMangling ),
1080   ( "print-bind-result",                Opt_PrintBindResult ),
1081   ( "force-recomp",                     Opt_ForceRecomp ),
1082   ( "hpc-no-auto",                      Opt_Hpc_No_Auto ),
1083   ( "rewrite-rules",                    Opt_RewriteRules ),
1084   ( "break-on-exception",               Opt_BreakOnException )
1085   ]
1086
1087
1088 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1089 xFlags :: [(String, DynFlag)]
1090 xFlags = [
1091   ( "FI",                               Opt_FFI ),  -- support `-ffi'...
1092   ( "FFI",                              Opt_FFI ),  -- ...and also `-fffi'
1093   ( "ForeignFunctionInterface",         Opt_FFI ),  -- ...and also `-fffi'
1094
1095   ( "Arrows",                           Opt_Arrows ), -- arrow syntax
1096   ( "Parr",                             Opt_PArr ),
1097
1098   ( "TH",                               Opt_TH ),
1099   ( "TemplateHaskelll",                 Opt_TH ),
1100
1101   ( "Generics",                         Opt_Generics ),
1102
1103   ( "ImplicitPrelude",                  Opt_ImplicitPrelude ),  -- On by default
1104
1105   ( "RecordWildCards",                  Opt_RecordWildCards ),
1106   ( "RecordPuns",                       Opt_RecordPuns ),
1107   ( "DisambiguateRecordFields",         Opt_DisambiguateRecordFields ),
1108
1109   ( "OverloadedStrings",                Opt_OverloadedStrings ),
1110   ( "GADTs",                            Opt_GADTs ),
1111   ( "TypeFamilies",                     Opt_TypeFamilies ),
1112   ( "BangPatterns",                     Opt_BangPatterns ),
1113   ( "MonomorphismRestriction",          Opt_MonomorphismRestriction ),  -- On by default
1114   ( "MonoPatBinds",                     Opt_MonoPatBinds ),             -- On by default (which is not strictly H98)
1115   ( "RelaxedPolyRec",                   Opt_RelaxedPolyRec),
1116   ( "ExtendedDefaultRules",             Opt_ExtendedDefaultRules ),
1117   ( "ImplicitParams",                   Opt_ImplicitParams ),
1118   ( "ScopedTypeVariables",              Opt_ScopedTypeVariables ),
1119   ( "AllowOverlappingInstances",        Opt_AllowOverlappingInstances ),
1120   ( "AllowUndecidableInstances",        Opt_AllowUndecidableInstances ),
1121   ( "AllowIncoherentInstances",         Opt_AllowIncoherentInstances )
1122   ]
1123
1124 impliedFlags :: [(DynFlag, [DynFlag])]
1125 impliedFlags = [
1126   ( Opt_GADTs, [Opt_RelaxedPolyRec] )   -- We want type-sig variables to be completely rigid for GADTs
1127   ]
1128
1129 glasgowExtsFlags = [ Opt_GlasgowExts 
1130                    , Opt_FFI 
1131                    , Opt_GADTs
1132                    , Opt_ImplicitParams 
1133                    , Opt_ScopedTypeVariables
1134                    , Opt_TypeFamilies ]
1135
1136 ------------------
1137 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1138
1139 isFlag flags f = is_flag flags (normaliseFlag f)
1140
1141 isNoFlag flags no_f
1142   | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1143   | otherwise                                   = False
1144
1145 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1146         -- nf is normalised alreadly
1147
1148 ------------------
1149 getFlag, getNoFlag :: [(String,a)] -> String -> a
1150
1151 getFlag flags f = get_flag flags (normaliseFlag f)
1152
1153 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1154                         -- The flag should be a no-flag already
1155
1156 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1157                         (o:os) -> o
1158                         []     -> panic ("get_flag " ++ nf)
1159
1160 ------------------
1161 noFlag_maybe :: String -> Maybe String
1162 -- The input is normalised already
1163 noFlag_maybe ('n' : 'o' : f) = Just f
1164 noFlag_maybe other           = Nothing
1165
1166 normaliseFlag :: String -> String
1167 -- Normalise a option flag by
1168 --      * map to lower case
1169 --      * removing hyphens
1170 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1171 normaliseFlag []      = []
1172 normaliseFlag ('-':s) = normaliseFlag s
1173 normaliseFlag (c:s)   = toLower c : normaliseFlag s
1174
1175 -- -----------------------------------------------------------------------------
1176 -- Parsing the dynamic flags.
1177
1178 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1179 parseDynamicFlags dflags args = do
1180   let ((leftover,errs),dflags') 
1181           = runCmdLine (processArgs dynamic_flags args) dflags
1182   when (not (null errs)) $ do
1183     throwDyn (UsageError (unlines errs))
1184   return (dflags', leftover)
1185
1186
1187 type DynP = CmdLineP DynFlags
1188
1189 upd :: (DynFlags -> DynFlags) -> DynP ()
1190 upd f = do 
1191    dfs <- getCmdLineState
1192    putCmdLineState $! (f dfs)
1193
1194 --------------------------
1195 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1196 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1197   where
1198     deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1199         -- When you set f, set the ones it implies
1200         -- When you un-set f, however, we don't un-set the things it implies
1201         --      (except for -fno-glasgow-exts, which is treated specially)
1202
1203 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1204
1205 --------------------------
1206 setDumpFlag :: DynFlag -> OptKind DynP
1207 setDumpFlag dump_flag 
1208   = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1209         -- Whenver we -ddump, switch off the recompilation checker,
1210         -- else you don't see the dump!
1211
1212 setVerbosity :: Maybe Int -> DynP ()
1213 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1214
1215 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1216
1217 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1218
1219 exposePackage p = 
1220   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1221 hidePackage p = 
1222   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1223 ignorePackage p = 
1224   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1225
1226 setPackageName p
1227   | Nothing <- unpackPackageId pid
1228   = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1229   | otherwise
1230   = \s -> s{ thisPackage = pid }
1231   where
1232         pid = stringToPackageId p
1233
1234 -- If we're linking a binary, then only targets that produce object
1235 -- code are allowed (requests for other target types are ignored).
1236 setTarget l = upd set
1237   where 
1238    set dfs 
1239      | ghcLink dfs /= LinkBinary || isObjectTarget l  = dfs{ hscTarget = l }
1240      | otherwise = dfs
1241
1242 -- Changes the target only if we're compiling object code.  This is
1243 -- used by -fasm and -fvia-C, which switch from one to the other, but
1244 -- not from bytecode to object-code.  The idea is that -fasm/-fvia-C
1245 -- can be safely used in an OPTIONS_GHC pragma.
1246 setObjTarget l = upd set
1247   where 
1248    set dfs 
1249      | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1250      | otherwise = dfs
1251
1252 setOptLevel :: Int -> DynFlags -> DynFlags
1253 setOptLevel n dflags
1254    | hscTarget dflags == HscInterpreted && n > 0
1255         = dflags
1256             -- not in IO any more, oh well:
1257             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1258    | otherwise
1259         = updOptLevel n dflags
1260
1261
1262 setMainIs :: String -> DynP ()
1263 setMainIs arg
1264   | not (null main_fn)          -- The arg looked like "Foo.baz"
1265   = upd $ \d -> d{ mainFunIs = Just main_fn,
1266                    mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1267
1268   | isUpper (head main_mod)     -- The arg looked like "Foo"
1269   = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1270   
1271   | otherwise                   -- The arg looked like "baz"
1272   = upd $ \d -> d{ mainFunIs = Just main_mod }
1273   where
1274     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1275
1276 -----------------------------------------------------------------------------
1277 -- Paths & Libraries
1278
1279 -- -i on its own deletes the import paths
1280 addImportPath "" = upd (\s -> s{importPaths = []})
1281 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1282
1283
1284 addLibraryPath p = 
1285   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1286
1287 addIncludePath p = 
1288   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1289
1290 addFrameworkPath p = 
1291   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1292
1293 split_marker = ':'   -- not configurable (ToDo)
1294
1295 splitPathList :: String -> [String]
1296 splitPathList s = filter notNull (splitUp s)
1297                 -- empty paths are ignored: there might be a trailing
1298                 -- ':' in the initial list, for example.  Empty paths can
1299                 -- cause confusion when they are translated into -I options
1300                 -- for passing to gcc.
1301   where
1302 #ifndef mingw32_TARGET_OS
1303     splitUp xs = split split_marker xs
1304 #else 
1305      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1306      -- 
1307      -- That is, if "foo:bar:baz" is used, this interpreted as
1308      -- consisting of three entries, 'foo', 'bar', 'baz'.
1309      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1310      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1311      --
1312      -- Notice that no attempt is made to fully replace the 'standard'
1313      -- split marker ':' with the Windows / DOS one, ';'. The reason being
1314      -- that this will cause too much breakage for users & ':' will
1315      -- work fine even with DOS paths, if you're not insisting on being silly.
1316      -- So, use either.
1317     splitUp []             = []
1318     splitUp (x:':':div:xs) | div `elem` dir_markers
1319                            = ((x:':':div:p): splitUp rs)
1320                            where
1321                               (p,rs) = findNextPath xs
1322           -- we used to check for existence of the path here, but that
1323           -- required the IO monad to be threaded through the command-line
1324           -- parser which is quite inconvenient.  The 
1325     splitUp xs = cons p (splitUp rs)
1326                where
1327                  (p,rs) = findNextPath xs
1328     
1329                  cons "" xs = xs
1330                  cons x  xs = x:xs
1331
1332     -- will be called either when we've consumed nought or the
1333     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1334     -- finding the next split marker.
1335     findNextPath xs = 
1336         case break (`elem` split_markers) xs of
1337            (p, d:ds) -> (p, ds)
1338            (p, xs)   -> (p, xs)
1339
1340     split_markers :: [Char]
1341     split_markers = [':', ';']
1342
1343     dir_markers :: [Char]
1344     dir_markers = ['/', '\\']
1345 #endif
1346
1347 -- -----------------------------------------------------------------------------
1348 -- tmpDir, where we store temporary files.
1349
1350 setTmpDir :: FilePath -> DynFlags -> DynFlags
1351 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1352   where
1353 #if !defined(mingw32_HOST_OS)
1354      canonicalise p = normalisePath p
1355 #else
1356         -- Canonicalisation of temp path under win32 is a bit more
1357         -- involved: (a) strip trailing slash, 
1358         --           (b) normalise slashes
1359         --           (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1360         -- 
1361      canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1362
1363         -- if we're operating under cygwin, and TMP/TEMP is of
1364         -- the form "/cygdrive/drive/path", translate this to
1365         -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1366         -- understand /cygdrive paths.)
1367      xltCygdrive path
1368       | "/cygdrive/" `isPrefixOf` path = 
1369           case drop (length "/cygdrive/") path of
1370             drive:xs@('/':_) -> drive:':':xs
1371             _ -> path
1372       | otherwise = path
1373
1374         -- strip the trailing backslash (awful, but we only do this once).
1375      removeTrailingSlash path = 
1376        case last path of
1377          '/'  -> init path
1378          '\\' -> init path
1379          _    -> path
1380 #endif
1381
1382 -----------------------------------------------------------------------------
1383 -- Hpc stuff
1384
1385 setOptHpcDir :: String -> DynP ()
1386 setOptHpcDir arg  = upd $ \ d -> d{hpcDir = arg}
1387
1388 -----------------------------------------------------------------------------
1389 -- Via-C compilation stuff
1390
1391 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1392                               [String]) -- for registerised HC compilations
1393 machdepCCOpts dflags
1394 #if alpha_TARGET_ARCH
1395         =       ( ["-w", "-mieee"
1396 #ifdef HAVE_THREADED_RTS_SUPPORT
1397                     , "-D_REENTRANT"
1398 #endif
1399                    ], [] )
1400         -- For now, to suppress the gcc warning "call-clobbered
1401         -- register used for global register variable", we simply
1402         -- disable all warnings altogether using the -w flag. Oh well.
1403
1404 #elif hppa_TARGET_ARCH
1405         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1406         -- (very nice, but too bad the HP /usr/include files don't agree.)
1407         = ( ["-D_HPUX_SOURCE"], [] )
1408
1409 #elif m68k_TARGET_ARCH
1410       -- -fno-defer-pop : for the .hc files, we want all the pushing/
1411       --    popping of args to routines to be explicit; if we let things
1412       --    be deferred 'til after an STGJUMP, imminent death is certain!
1413       --
1414       -- -fomit-frame-pointer : *don't*
1415       --     It's better to have a6 completely tied up being a frame pointer
1416       --     rather than let GCC pick random things to do with it.
1417       --     (If we want to steal a6, then we would try to do things
1418       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
1419         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1420
1421 #elif i386_TARGET_ARCH
1422       -- -fno-defer-pop : basically the same game as for m68k
1423       --
1424       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1425       --   the fp (%ebp) for our register maps.
1426         =  let n_regs = stolen_x86_regs dflags
1427                sta = opt_Static
1428            in
1429                     ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1430 --                    , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else "" 
1431                       ],
1432                       [ "-fno-defer-pop",
1433 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1434                         -- Some gccs are configured with
1435                         -- -momit-leaf-frame-pointer on by default, and it
1436                         -- apparently takes precedence over 
1437                         -- -fomit-frame-pointer, so we disable it first here.
1438                         "-mno-omit-leaf-frame-pointer",
1439 #endif
1440 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1441                         "-fno-unit-at-a-time",
1442                         -- unit-at-a-time doesn't do us any good, and screws
1443                         -- up -split-objs by moving the split markers around.
1444                         -- It's only turned on with -O2, but put it here just
1445                         -- in case someone uses -optc-O2.
1446 #endif
1447                         "-fomit-frame-pointer",
1448                         -- we want -fno-builtin, because when gcc inlines
1449                         -- built-in functions like memcpy() it tends to
1450                         -- run out of registers, requiring -monly-n-regs
1451                         "-fno-builtin",
1452                         "-DSTOLEN_X86_REGS="++show n_regs ]
1453                     )
1454
1455 #elif ia64_TARGET_ARCH
1456         = ( [], ["-fomit-frame-pointer", "-G0"] )
1457
1458 #elif x86_64_TARGET_ARCH
1459         = ( [], ["-fomit-frame-pointer",
1460                  "-fno-asynchronous-unwind-tables",
1461                         -- the unwind tables are unnecessary for HC code,
1462                         -- and get in the way of -split-objs.  Another option
1463                         -- would be to throw them away in the mangler, but this
1464                         -- is easier.
1465 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1466                  "-fno-unit-at-a-time",
1467                         -- unit-at-a-time doesn't do us any good, and screws
1468                         -- up -split-objs by moving the split markers around.
1469                         -- It's only turned on with -O2, but put it here just
1470                         -- in case someone uses -optc-O2.
1471 #endif
1472                  "-fno-builtin"
1473                         -- calling builtins like strlen() using the FFI can
1474                         -- cause gcc to run out of regs, so use the external
1475                         -- version.
1476                 ] )
1477
1478 #elif sparc_TARGET_ARCH
1479         = ( [], ["-w"] )
1480         -- For now, to suppress the gcc warning "call-clobbered
1481         -- register used for global register variable", we simply
1482         -- disable all warnings altogether using the -w flag. Oh well.
1483
1484 #elif powerpc_apple_darwin_TARGET
1485       -- -no-cpp-precomp:
1486       --     Disable Apple's precompiling preprocessor. It's a great thing
1487       --     for "normal" programs, but it doesn't support register variable
1488       --     declarations.
1489         = ( [], ["-no-cpp-precomp"] )
1490 #else
1491         = ( [], [] )
1492 #endif
1493
1494 picCCOpts :: DynFlags -> [String]
1495 picCCOpts dflags
1496 #if darwin_TARGET_OS
1497       -- Apple prefers to do things the other way round.
1498       -- PIC is on by default.
1499       -- -mdynamic-no-pic:
1500       --     Turn off PIC code generation.
1501       -- -fno-common:
1502       --     Don't generate "common" symbols - these are unwanted
1503       --     in dynamic libraries.
1504
1505     | opt_PIC
1506         = ["-fno-common"]
1507     | otherwise
1508         = ["-mdynamic-no-pic"]
1509 #elif mingw32_TARGET_OS
1510       -- no -fPIC for Windows
1511         = []
1512 #else
1513     | opt_PIC
1514         = ["-fPIC"]
1515     | otherwise
1516         = []
1517 #endif
1518
1519 -- -----------------------------------------------------------------------------
1520 -- Splitting
1521
1522 can_split :: Bool
1523 can_split =  
1524 #if    defined(i386_TARGET_ARCH)     \
1525     || defined(x86_64_TARGET_ARCH)   \
1526     || defined(alpha_TARGET_ARCH)    \
1527     || defined(hppa_TARGET_ARCH)     \
1528     || defined(m68k_TARGET_ARCH)     \
1529     || defined(mips_TARGET_ARCH)     \
1530     || defined(powerpc_TARGET_ARCH)  \
1531     || defined(rs6000_TARGET_ARCH)   \
1532     || defined(sparc_TARGET_ARCH) 
1533    True
1534 #else
1535    False
1536 #endif
1537