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