-fglasgow-exts implies -X=GADTs
[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_RecordDotDot
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_ShortGhciBanner
205    | Opt_Cpp
206    | Opt_Pp
207    | Opt_ForceRecomp
208    | Opt_DryRun
209    | Opt_DoAsmMangling
210    | Opt_ExcessPrecision
211    | Opt_ReadUserPackageConf
212    | Opt_NoHsMain
213    | Opt_SplitObjs
214    | Opt_StgStats
215    | Opt_HideAllPackages
216    | Opt_PrintBindResult
217    | Opt_Haddock
218    | Opt_Hpc_No_Auto
219    | Opt_BreakOnException
220
221    -- keeping stuff
222    | Opt_KeepHiDiffs
223    | Opt_KeepHcFiles
224    | Opt_KeepSFiles
225    | Opt_KeepRawSFiles
226    | Opt_KeepTmpFiles
227
228    deriving (Eq)
229  
230 data DynFlags = DynFlags {
231   ghcMode               :: GhcMode,
232   ghcLink               :: GhcLink,
233   coreToDo              :: Maybe [CoreToDo], -- reserved for -Ofile
234   stgToDo               :: Maybe [StgToDo],  -- similarly
235   hscTarget             :: HscTarget,
236   hscOutName            :: String,      -- name of the output file
237   extCoreName           :: String,      -- name of the .core output file
238   verbosity             :: Int,         -- verbosity level
239   optLevel              :: Int,         -- optimisation level
240   maxSimplIterations    :: Int,         -- max simplifier iterations
241   ruleCheck             :: Maybe String,
242
243   specThreshold         :: Int,         -- Threshold for function specialisation
244
245   stolen_x86_regs       :: Int,         
246   cmdlineHcIncludes     :: [String],    -- -#includes
247   importPaths           :: [FilePath],
248   mainModIs             :: Module,
249   mainFunIs             :: Maybe String,
250   ctxtStkDepth          :: Int,         -- Typechecker context stack depth
251
252   thisPackage           :: PackageId,
253
254   -- ways
255   wayNames              :: [WayName],   -- way flags from the cmd line
256   buildTag              :: String,      -- the global "way" (eg. "p" for prof)
257   rtsBuildTag           :: String,      -- the RTS "way"
258   
259   -- paths etc.
260   objectDir             :: Maybe String,
261   hiDir                 :: Maybe String,
262   stubDir               :: Maybe String,
263
264   objectSuf             :: String,
265   hcSuf                 :: String,
266   hiSuf                 :: String,
267
268   outputFile            :: Maybe String,
269   outputHi              :: Maybe String,
270
271   includePaths          :: [String],
272   libraryPaths          :: [String],
273   frameworkPaths        :: [String],    -- used on darwin only
274   cmdlineFrameworks     :: [String],    -- ditto
275   tmpDir                :: String,      -- no trailing '/'
276   
277   ghcUsagePath          :: FilePath,    -- Filled in by SysTools
278   ghciUsagePath         :: FilePath,    -- ditto
279
280   hpcDir                :: String,      -- ^ path to store the .mix files
281
282   -- options for particular phases
283   opt_L                 :: [String],
284   opt_P                 :: [String],
285   opt_F                 :: [String],
286   opt_c                 :: [String],
287   opt_m                 :: [String],
288   opt_a                 :: [String],
289   opt_l                 :: [String],
290   opt_dll               :: [String],
291   opt_dep               :: [String],
292
293   -- commands for particular phases
294   pgm_L                 :: String,
295   pgm_P                 :: (String,[Option]),
296   pgm_F                 :: String,
297   pgm_c                 :: (String,[Option]),
298   pgm_m                 :: (String,[Option]),
299   pgm_s                 :: (String,[Option]),
300   pgm_a                 :: (String,[Option]),
301   pgm_l                 :: (String,[Option]),
302   pgm_dll               :: (String,[Option]),
303   pgm_T                 :: String,
304   pgm_sysman            :: String,
305
306   --  Package flags
307   extraPkgConfs         :: [FilePath],
308   topDir                :: FilePath,    -- filled in by SysTools
309   systemPackageConfig   :: FilePath,    -- ditto
310         -- The -package-conf flags given on the command line, in the order
311         -- they appeared.
312
313   packageFlags          :: [PackageFlag],
314         -- The -package and -hide-package flags from the command-line
315
316   -- Package state
317   -- NB. do not modify this field, it is calculated by 
318   -- Packages.initPackages and Packages.updatePackages.
319   pkgDatabase           :: Maybe (UniqFM InstalledPackageInfo),
320   pkgState              :: PackageState,
321
322   -- hsc dynamic flags
323   flags                 :: [DynFlag],
324   
325   -- message output
326   log_action            :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
327  }
328
329 data HscTarget
330   = HscC
331   | HscAsm
332   | HscJava
333   | HscInterpreted
334   | HscNothing
335   deriving (Eq, Show)
336
337 -- | will this target result in an object file on the disk?
338 isObjectTarget :: HscTarget -> Bool
339 isObjectTarget HscC     = True
340 isObjectTarget HscAsm   = True
341 isObjectTarget _        = False
342
343 -- | The 'GhcMode' tells us whether we're doing multi-module
344 -- compilation (controlled via the "GHC" API) or one-shot
345 -- (single-module) compilation.  This makes a difference primarily to
346 -- the "Finder": in one-shot mode we look for interface files for
347 -- imported modules, but in multi-module mode we look for source files
348 -- in order to check whether they need to be recompiled.
349 data GhcMode
350   = CompManager         -- ^ --make, GHCi, etc.
351   | OneShot             -- ^ ghc -c Foo.hs
352   | MkDepend            -- ^ ghc -M, see Finder for why we need this
353   deriving Eq
354
355 isOneShot :: GhcMode -> Bool
356 isOneShot OneShot = True
357 isOneShot _other  = False
358
359 -- | What kind of linking to do.
360 data GhcLink    -- What to do in the link step, if there is one
361   = NoLink              -- Don't link at all
362   | LinkBinary          -- Link object code into a binary
363   | LinkInMemory        -- Use the in-memory dynamic linker
364   | MkDLL               -- Make a DLL
365   deriving Eq
366
367 isNoLink :: GhcLink -> Bool
368 isNoLink NoLink = True
369 isNoLink other  = False
370
371 data PackageFlag
372   = ExposePackage  String
373   | HidePackage    String
374   | IgnorePackage  String
375   deriving Eq
376
377 defaultHscTarget = defaultObjectTarget
378
379 -- | the 'HscTarget' value corresponding to the default way to create
380 -- object files on the current platform.
381 defaultObjectTarget
382   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
383   | otherwise                           =  HscC
384
385 initDynFlags dflags = do
386  -- someday these will be dynamic flags
387  ways <- readIORef v_Ways
388  build_tag <- readIORef v_Build_tag
389  rts_build_tag <- readIORef v_RTS_Build_tag
390  return dflags{
391         wayNames        = ways,
392         buildTag        = build_tag,
393         rtsBuildTag     = rts_build_tag
394         }
395
396 defaultDynFlags =
397      DynFlags {
398         ghcMode                 = CompManager,
399         ghcLink                 = LinkBinary,
400         coreToDo                = Nothing,
401         stgToDo                 = Nothing, 
402         hscTarget               = defaultHscTarget, 
403         hscOutName              = "", 
404         extCoreName             = "",
405         verbosity               = 0, 
406         optLevel                = 0,
407         maxSimplIterations      = 4,
408         ruleCheck               = Nothing,
409         specThreshold           = 200,
410         stolen_x86_regs         = 4,
411         cmdlineHcIncludes       = [],
412         importPaths             = ["."],
413         mainModIs               = mAIN,
414         mainFunIs               = Nothing,
415         ctxtStkDepth            = mAX_CONTEXT_REDUCTION_DEPTH,
416
417         thisPackage             = mainPackageId,
418
419         objectDir               = Nothing,
420         hiDir                   = Nothing,
421         stubDir                 = Nothing,
422
423         objectSuf               = phaseInputExt StopLn,
424         hcSuf                   = phaseInputExt HCc,
425         hiSuf                   = "hi",
426
427         outputFile              = Nothing,
428         outputHi                = Nothing,
429         includePaths            = [],
430         libraryPaths            = [],
431         frameworkPaths          = [],
432         cmdlineFrameworks       = [],
433         tmpDir                  = cDEFAULT_TMPDIR,
434         
435         hpcDir                  = ".hpc",
436
437         opt_L                   = [],
438         opt_P                   = [],
439         opt_F                   = [],
440         opt_c                   = [],
441         opt_a                   = [],
442         opt_m                   = [],
443         opt_l                   = [],
444         opt_dll                 = [],
445         opt_dep                 = [],
446         
447         extraPkgConfs           = [],
448         packageFlags            = [],
449         pkgDatabase             = Nothing,
450         pkgState                = panic "no package state yet: call GHC.setSessionDynFlags",
451         flags = [ 
452             Opt_ReadUserPackageConf,
453     
454             Opt_MonoPatBinds,   -- Experimentally, I'm making this non-standard
455                                 -- behaviour the default, to see if anyone notices
456                                 -- SLPJ July 06
457
458             Opt_ImplicitPrelude,
459             Opt_MonomorphismRestriction,
460
461             Opt_DoAsmMangling,
462     
463             -- on by default:
464             Opt_PrintBindResult ]
465             ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
466                     -- The default -O0 options
467             ++ standardWarnings,
468                
469         log_action = \severity srcSpan style msg -> 
470                         case severity of
471                           SevInfo  -> hPutStrLn stderr (show (msg style))
472                           SevFatal -> hPutStrLn stderr (show (msg style))
473                           _        -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
474       }
475
476 {- 
477     Verbosity levels:
478         
479     0   |   print errors & warnings only
480     1   |   minimal verbosity: print "compiling M ... done." for each module.
481     2   |   equivalent to -dshow-passes
482     3   |   equivalent to existing "ghc -v"
483     4   |   "ghc -v -ddump-most"
484     5   |   "ghc -v -ddump-all"
485 -}
486
487 dopt :: DynFlag -> DynFlags -> Bool
488 dopt f dflags  = f `elem` (flags dflags)
489
490 dopt_set :: DynFlags -> DynFlag -> DynFlags
491 dopt_set dfs f = dfs{ flags = f : flags dfs }
492
493 dopt_unset :: DynFlags -> DynFlag -> DynFlags
494 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
495
496 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
497 getOpts dflags opts = reverse (opts dflags)
498         -- We add to the options from the front, so we need to reverse the list
499
500 getVerbFlag :: DynFlags -> String
501 getVerbFlag dflags 
502   | verbosity dflags >= 3  = "-v" 
503   | otherwise =  ""
504
505 setObjectDir  f d = d{ objectDir  = f}
506 setHiDir      f d = d{ hiDir      = f}
507 setStubDir    f d = d{ stubDir    = f}
508
509 setObjectSuf  f d = d{ objectSuf  = f}
510 setHiSuf      f d = d{ hiSuf      = f}
511 setHcSuf      f d = d{ hcSuf      = f}
512
513 setOutputFile f d = d{ outputFile = f}
514 setOutputHi   f d = d{ outputHi   = f}
515
516 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
517 -- Config.hs should really use Option.
518 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
519
520 setPgmL   f d = d{ pgm_L   = f}
521 setPgmF   f d = d{ pgm_F   = f}
522 setPgmc   f d = d{ pgm_c   = (f,[])}
523 setPgmm   f d = d{ pgm_m   = (f,[])}
524 setPgms   f d = d{ pgm_s   = (f,[])}
525 setPgma   f d = d{ pgm_a   = (f,[])}
526 setPgml   f d = d{ pgm_l   = (f,[])}
527 setPgmdll f d = d{ pgm_dll = (f,[])}
528
529 addOptL   f d = d{ opt_L   = f : opt_L d}
530 addOptP   f d = d{ opt_P   = f : opt_P d}
531 addOptF   f d = d{ opt_F   = f : opt_F d}
532 addOptc   f d = d{ opt_c   = f : opt_c d}
533 addOptm   f d = d{ opt_m   = f : opt_m d}
534 addOpta   f d = d{ opt_a   = f : opt_a d}
535 addOptl   f d = d{ opt_l   = f : opt_l d}
536 addOptdll f d = d{ opt_dll = f : opt_dll d}
537 addOptdep f d = d{ opt_dep = f : opt_dep d}
538
539 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
540
541 -- -----------------------------------------------------------------------------
542 -- Command-line options
543
544 -- When invoking external tools as part of the compilation pipeline, we
545 -- pass these a sequence of options on the command-line. Rather than
546 -- just using a list of Strings, we use a type that allows us to distinguish
547 -- between filepaths and 'other stuff'. [The reason being, of course, that
548 -- this type gives us a handle on transforming filenames, and filenames only,
549 -- to whatever format they're expected to be on a particular platform.]
550
551 data Option
552  = FileOption -- an entry that _contains_ filename(s) / filepaths.
553               String  -- a non-filepath prefix that shouldn't be 
554                       -- transformed (e.g., "/out=")
555               String  -- the filepath/filename portion
556  | Option     String
557  
558 -----------------------------------------------------------------------------
559 -- Setting the optimisation level
560
561 updOptLevel :: Int -> DynFlags -> DynFlags
562 -- Set dynflags appropriate to the optimisation level
563 updOptLevel n dfs
564   = dfs2{ optLevel = n }
565   where
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, n `elem` ns ]
570    remove_dopts = [ f | (ns,f) <- optLevelFlags, 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   ,  ( "short-ghci-banner", NoArg (setDynFlag Opt_ShortGhciBanner) )
846   ,  ( "long-ghci-banner" , NoArg (unSetDynFlag Opt_ShortGhciBanner) )
847
848         ------- Specific phases  --------------------------------------------
849   ,  ( "pgmL"           , HasArg (upd . setPgmL) )  
850   ,  ( "pgmP"           , HasArg (upd . setPgmP) )  
851   ,  ( "pgmF"           , HasArg (upd . setPgmF) )  
852   ,  ( "pgmc"           , HasArg (upd . setPgmc) )  
853   ,  ( "pgmm"           , HasArg (upd . setPgmm) )  
854   ,  ( "pgms"           , HasArg (upd . setPgms) )  
855   ,  ( "pgma"           , HasArg (upd . setPgma) )  
856   ,  ( "pgml"           , HasArg (upd . setPgml) )  
857   ,  ( "pgmdll"         , HasArg (upd . setPgmdll) )
858
859   ,  ( "optL"           , HasArg (upd . addOptL) )  
860   ,  ( "optP"           , HasArg (upd . addOptP) )  
861   ,  ( "optF"           , HasArg (upd . addOptF) )  
862   ,  ( "optc"           , HasArg (upd . addOptc) )  
863   ,  ( "optm"           , HasArg (upd . addOptm) )  
864   ,  ( "opta"           , HasArg (upd . addOpta) )  
865   ,  ( "optl"           , HasArg (upd . addOptl) )  
866   ,  ( "optdll"         , HasArg (upd . addOptdll) )  
867   ,  ( "optdep"         , HasArg (upd . addOptdep) )
868
869   ,  ( "split-objs"     , NoArg (if can_split
870                                     then setDynFlag Opt_SplitObjs
871                                     else return ()) )
872
873         -------- Linking ----------------------------------------------------
874   ,  ( "c"              , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
875   ,  ( "no-link"        , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
876   ,  ( "-mk-dll"        , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
877
878         ------- Libraries ---------------------------------------------------
879   ,  ( "L"              , Prefix addLibraryPath )
880   ,  ( "l"              , AnySuffix (\s -> do upd (addOptl s)
881                                               upd (addOptdll s)))
882
883         ------- Frameworks --------------------------------------------------
884         -- -framework-path should really be -F ...
885   ,  ( "framework-path" , HasArg addFrameworkPath )
886   ,  ( "framework"      , HasArg (upd . addCmdlineFramework) )
887
888         ------- Output Redirection ------------------------------------------
889   ,  ( "odir"           , HasArg (upd . setObjectDir  . Just))
890   ,  ( "o"              , SepArg (upd . setOutputFile . Just))
891   ,  ( "ohi"            , HasArg (upd . setOutputHi   . Just ))
892   ,  ( "osuf"           , HasArg (upd . setObjectSuf))
893   ,  ( "hcsuf"          , HasArg (upd . setHcSuf))
894   ,  ( "hisuf"          , HasArg (upd . setHiSuf))
895   ,  ( "hidir"          , HasArg (upd . setHiDir . Just))
896   ,  ( "tmpdir"         , HasArg (upd . setTmpDir))
897   ,  ( "stubdir"        , HasArg (upd . setStubDir . Just))
898
899         ------- Keeping temporary files -------------------------------------
900   ,  ( "keep-hc-file"   , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
901   ,  ( "keep-s-file"    , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
902   ,  ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
903   ,  ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
904
905         ------- Miscellaneous ----------------------------------------------
906   ,  ( "no-hs-main"     , NoArg (setDynFlag Opt_NoHsMain))
907   ,  ( "main-is"        , SepArg setMainIs )
908   ,  ( "haddock"        , NoArg (setDynFlag Opt_Haddock) )
909   ,  ( "hpcdir"         , SepArg setOptHpcDir )
910
911         ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
912   ,  ( "recomp"         , NoArg (unSetDynFlag Opt_ForceRecomp) )
913   ,  ( "no-recomp"      , NoArg (setDynFlag   Opt_ForceRecomp) )
914
915         ------- Packages ----------------------------------------------------
916   ,  ( "package-conf"   , HasArg extraPkgConf_ )
917   ,  ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
918   ,  ( "package-name"   , HasArg (upd . setPackageName) )
919   ,  ( "package"        , HasArg exposePackage )
920   ,  ( "hide-package"   , HasArg hidePackage )
921   ,  ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
922   ,  ( "ignore-package" , HasArg ignorePackage )
923   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
924
925         ------ HsCpp opts ---------------------------------------------------
926   ,  ( "D",             AnySuffix (upd . addOptP) )
927   ,  ( "U",             AnySuffix (upd . addOptP) )
928
929         ------- Include/Import Paths ----------------------------------------
930   ,  ( "I"              , Prefix    addIncludePath)
931   ,  ( "i"              , OptPrefix addImportPath )
932
933         ------ Debugging ----------------------------------------------------
934   ,  ( "dstg-stats",    NoArg (setDynFlag Opt_StgStats))
935
936   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
937   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
938   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
939   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
940   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
941   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
942   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
943   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
944   ,  ( "ddump-rule-firings",     setDumpFlag Opt_D_dump_rule_firings)
945   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
946   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
947   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
948   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
949   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
950   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
951   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
952   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
953   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
954   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
955   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
956   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
957   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
958   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
959   ,  ( "ddump-rn-trace",         setDumpFlag Opt_D_dump_rn_trace)
960   ,  ( "ddump-if-trace",         setDumpFlag Opt_D_dump_if_trace)
961   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
962   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
963   ,  ( "ddump-rn-stats",         setDumpFlag Opt_D_dump_rn_stats)
964   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
965   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
966   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
967   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
968   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
969   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
970   ,  ( "ddump-hi-diffs",         setDumpFlag Opt_D_dump_hi_diffs)
971   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
972   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
973   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
974   ,  ( "ddump-hpc",              setDumpFlag Opt_D_dump_hpc)
975   ,  ( "ddump-mod-cycles",       setDumpFlag Opt_D_dump_mod_cycles)
976   
977   ,  ( "dcore-lint",             NoArg (setDynFlag Opt_DoCoreLinting))
978   ,  ( "dstg-lint",              NoArg (setDynFlag Opt_DoStgLinting))
979   ,  ( "dcmm-lint",              NoArg (setDynFlag Opt_DoCmmLinting))
980   ,  ( "dshow-passes",           NoArg (do setDynFlag Opt_ForceRecomp
981                                            setVerbosity (Just 2)) )
982   ,  ( "dfaststring-stats",      NoArg (setDynFlag Opt_D_faststring_stats))
983
984         ------ Machine dependant (-m<blah>) stuff ---------------------------
985
986   ,  ( "monly-2-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
987   ,  ( "monly-3-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
988   ,  ( "monly-4-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
989
990         ------ Warning opts -------------------------------------------------
991   ,  ( "W"              , NoArg (mapM_ setDynFlag   minusWOpts)    )
992   ,  ( "Werror"         , NoArg (setDynFlag         Opt_WarnIsError) )
993   ,  ( "Wall"           , NoArg (mapM_ setDynFlag   minusWallOpts) )
994   ,  ( "Wnot"           , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
995   ,  ( "w"              , NoArg (mapM_ unSetDynFlag minusWallOpts) )
996
997         ------ Optimisation flags ------------------------------------------
998   ,  ( "O"      , NoArg (upd (setOptLevel 1)))
999   ,  ( "Onot"   , NoArg (upd (setOptLevel 0)))
1000   ,  ( "O"      , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1001                 -- If the number is missing, use 1
1002
1003   ,  ( "fmax-simplifier-iterations", IntSuffix (\n -> 
1004                 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1005
1006         -- liberate-case-threshold is an old flag for '-fspec-threshold'
1007   ,  ( "fspec-threshold",          IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1008   ,  ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1009
1010   ,  ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1011   ,  ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1012
1013         ------ Compiler flags -----------------------------------------------
1014
1015   ,  ( "fasm",          AnySuffix (\_ -> setObjTarget HscAsm) )
1016   ,  ( "fvia-c",        NoArg (setObjTarget HscC) )
1017   ,  ( "fvia-C",        NoArg (setObjTarget HscC) )
1018
1019   ,  ( "fno-code",      NoArg (setTarget HscNothing))
1020   ,  ( "fbyte-code",    NoArg (setTarget HscInterpreted) )
1021   ,  ( "fobject-code",  NoArg (setTarget defaultHscTarget) )
1022
1023   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
1024   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1025
1026         -- the rest of the -f* and -fno-* flags
1027   ,  ( "f",             PrefixPred (isFlag fFlags)   (\f -> setDynFlag   (getFlag fFlags f)) )
1028   ,  ( "f",             PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1029
1030         -- For now, allow -X flags with -f; ToDo: report this as deprecated
1031   ,  ( "f",             PrefixPred (isFlag xFlags) (\f ->  setDynFlag (getFlag xFlags f)) )
1032   ,  ( "f",             PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1033
1034         -- the rest of the -X* and -Xno-* flags
1035   ,  ( "X",             PrefixPred (isFlag xFlags)   (\f -> setDynFlag   (getFlag xFlags f)) )
1036   ,  ( "X",             PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1037  ]
1038
1039 -- these -f<blah> flags can all be reversed with -fno-<blah>
1040
1041 fFlags = [
1042   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
1043   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
1044   ( "warn-implicit-prelude",            Opt_WarnImplicitPrelude ),
1045   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
1046   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
1047   ( "warn-missing-fields",              Opt_WarnMissingFields ),
1048   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
1049   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
1050   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
1051   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
1052   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
1053   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
1054   ( "warn-monomorphism-restriction",    Opt_WarnMonomorphism ),
1055   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
1056   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
1057   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
1058   ( "warn-deprecations",                Opt_WarnDeprecations ),
1059   ( "warn-orphans",                     Opt_WarnOrphans ),
1060   ( "warn-tabs",                        Opt_WarnTabs ),
1061   ( "strictness",                       Opt_Strictness ),
1062   ( "full-laziness",                    Opt_FullLaziness ),
1063   ( "liberate-case",                    Opt_LiberateCase ),
1064   ( "spec-constr",                      Opt_SpecConstr ),
1065   ( "cse",                              Opt_CSE ),
1066   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
1067   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
1068   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
1069   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
1070   ( "ignore-breakpoints",               Opt_IgnoreBreakpoints),
1071   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
1072   ( "case-merge",                       Opt_CaseMerge ),
1073   ( "unbox-strict-fields",              Opt_UnboxStrictFields ),
1074   ( "dicts-cheap",                      Opt_DictsCheap ),
1075   ( "excess-precision",                 Opt_ExcessPrecision ),
1076   ( "asm-mangling",                     Opt_DoAsmMangling ),
1077   ( "print-bind-result",                Opt_PrintBindResult ),
1078   ( "force-recomp",                     Opt_ForceRecomp ),
1079   ( "hpc-no-auto",                      Opt_Hpc_No_Auto ),
1080   ( "rewrite-rules",                    Opt_RewriteRules ),
1081   ( "break-on-exception",               Opt_BreakOnException )
1082   ]
1083
1084
1085 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1086 xFlags :: [(String, DynFlag)]
1087 xFlags = [
1088   ( "FI",                               Opt_FFI ),  -- support `-ffi'...
1089   ( "FFI",                              Opt_FFI ),  -- ...and also `-fffi'
1090   ( "ForeignFunctionInterface",         Opt_FFI ),  -- ...and also `-fffi'
1091
1092   ( "Arrows",                           Opt_Arrows ), -- arrow syntax
1093   ( "Parr",                             Opt_PArr ),
1094
1095   ( "TH",                               Opt_TH ),
1096   ( "TemplateHaskelll",                 Opt_TH ),
1097
1098   ( "Generics",                         Opt_Generics ),
1099
1100   ( "ImplicitPrelude",                  Opt_ImplicitPrelude ),  -- On by default
1101
1102   ( "OverloadedStrings",                Opt_OverloadedStrings ),
1103   ( "GADTs",                            Opt_GADTs ),
1104   ( "TypeFamilies",                     Opt_TypeFamilies ),
1105   ( "BangPatterns",                     Opt_BangPatterns ),
1106   ( "MonomorphismRestriction",          Opt_MonomorphismRestriction ),  -- On by default
1107   ( "MonoPatBinds",                     Opt_MonoPatBinds ),             -- On by default (which is not strictly H98)
1108   ( "RelaxedPolyRec",                   Opt_RelaxedPolyRec),
1109   ( "ExtendedDefaultRules",             Opt_ExtendedDefaultRules ),
1110   ( "ImplicitParams",                   Opt_ImplicitParams ),
1111   ( "ScopedTypeVariables",              Opt_ScopedTypeVariables ),
1112   ( "AllowOverlappingInstances",        Opt_AllowOverlappingInstances ),
1113   ( "AllowUndecidableInstances",        Opt_AllowUndecidableInstances ),
1114   ( "AllowIncoherentInstances",         Opt_AllowIncoherentInstances )
1115   ]
1116
1117 impliedFlags :: [(DynFlag, [DynFlag])]
1118 impliedFlags = [
1119   ( Opt_GADTs, [Opt_RelaxedPolyRec] )   -- We want type-sig variables to be completely rigid for GADTs
1120   ]
1121
1122 glasgowExtsFlags = [ Opt_GlasgowExts 
1123                    , Opt_FFI 
1124                    , Opt_GADTs
1125                    , Opt_ImplicitParams 
1126                    , Opt_ScopedTypeVariables
1127                    , Opt_TypeFamilies ]
1128
1129 ------------------
1130 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1131
1132 isFlag flags f = is_flag flags (normaliseFlag f)
1133
1134 isNoFlag flags no_f
1135   | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1136   | otherwise                                   = False
1137
1138 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1139         -- nf is normalised alreadly
1140
1141 ------------------
1142 getFlag, getNoFlag :: [(String,a)] -> String -> a
1143
1144 getFlag flags f = get_flag flags (normaliseFlag f)
1145
1146 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1147                         -- The flag should be a no-flag already
1148
1149 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1150                         (o:os) -> o
1151                         []     -> panic ("get_flag " ++ nf)
1152
1153 ------------------
1154 noFlag_maybe :: String -> Maybe String
1155 -- The input is normalised already
1156 noFlag_maybe ('n' : 'o' : f) = Just f
1157 noFlag_maybe other           = Nothing
1158
1159 normaliseFlag :: String -> String
1160 -- Normalise a option flag by
1161 --      * map to lower case
1162 --      * removing hyphens
1163 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1164 normaliseFlag []      = []
1165 normaliseFlag ('-':s) = normaliseFlag s
1166 normaliseFlag (c:s)   = toLower c : normaliseFlag s
1167
1168 -- -----------------------------------------------------------------------------
1169 -- Parsing the dynamic flags.
1170
1171 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1172 parseDynamicFlags dflags args = do
1173   let ((leftover,errs),dflags') 
1174           = runCmdLine (processArgs dynamic_flags args) dflags
1175   when (not (null errs)) $ do
1176     throwDyn (UsageError (unlines errs))
1177   return (dflags', leftover)
1178
1179
1180 type DynP = CmdLineP DynFlags
1181
1182 upd :: (DynFlags -> DynFlags) -> DynP ()
1183 upd f = do 
1184    dfs <- getCmdLineState
1185    putCmdLineState $! (f dfs)
1186
1187 --------------------------
1188 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1189 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1190   where
1191     deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1192         -- When you set f, set the ones it implies
1193         -- When you un-set f, however, we don't un-set the things it implies
1194         --      (except for -fno-glasgow-exts, which is treated specially)
1195
1196 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1197
1198 --------------------------
1199 setDumpFlag :: DynFlag -> OptKind DynP
1200 setDumpFlag dump_flag 
1201   = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1202         -- Whenver we -ddump, switch off the recompilation checker,
1203         -- else you don't see the dump!
1204
1205 setVerbosity :: Maybe Int -> DynP ()
1206 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1207
1208 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1209
1210 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1211
1212 exposePackage p = 
1213   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1214 hidePackage p = 
1215   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1216 ignorePackage p = 
1217   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1218
1219 setPackageName p
1220   | Nothing <- unpackPackageId pid
1221   = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1222   | otherwise
1223   = \s -> s{ thisPackage = pid }
1224   where
1225         pid = stringToPackageId p
1226
1227 -- If we're linking a binary, then only targets that produce object
1228 -- code are allowed (requests for other target types are ignored).
1229 setTarget l = upd set
1230   where 
1231    set dfs 
1232      | ghcLink dfs /= LinkBinary || isObjectTarget l  = dfs{ hscTarget = l }
1233      | otherwise = dfs
1234
1235 -- Changes the target only if we're compiling object code.  This is
1236 -- used by -fasm and -fvia-C, which switch from one to the other, but
1237 -- not from bytecode to object-code.  The idea is that -fasm/-fvia-C
1238 -- can be safely used in an OPTIONS_GHC pragma.
1239 setObjTarget l = upd set
1240   where 
1241    set dfs 
1242      | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1243      | otherwise = dfs
1244
1245 setOptLevel :: Int -> DynFlags -> DynFlags
1246 setOptLevel n dflags
1247    | hscTarget dflags == HscInterpreted && n > 0
1248         = dflags
1249             -- not in IO any more, oh well:
1250             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1251    | otherwise
1252         = updOptLevel n dflags
1253
1254
1255 setMainIs :: String -> DynP ()
1256 setMainIs arg
1257   | not (null main_fn)          -- The arg looked like "Foo.baz"
1258   = upd $ \d -> d{ mainFunIs = Just main_fn,
1259                    mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1260
1261   | isUpper (head main_mod)     -- The arg looked like "Foo"
1262   = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1263   
1264   | otherwise                   -- The arg looked like "baz"
1265   = upd $ \d -> d{ mainFunIs = Just main_mod }
1266   where
1267     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1268
1269 -----------------------------------------------------------------------------
1270 -- Paths & Libraries
1271
1272 -- -i on its own deletes the import paths
1273 addImportPath "" = upd (\s -> s{importPaths = []})
1274 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1275
1276
1277 addLibraryPath p = 
1278   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1279
1280 addIncludePath p = 
1281   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1282
1283 addFrameworkPath p = 
1284   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1285
1286 split_marker = ':'   -- not configurable (ToDo)
1287
1288 splitPathList :: String -> [String]
1289 splitPathList s = filter notNull (splitUp s)
1290                 -- empty paths are ignored: there might be a trailing
1291                 -- ':' in the initial list, for example.  Empty paths can
1292                 -- cause confusion when they are translated into -I options
1293                 -- for passing to gcc.
1294   where
1295 #ifndef mingw32_TARGET_OS
1296     splitUp xs = split split_marker xs
1297 #else 
1298      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1299      -- 
1300      -- That is, if "foo:bar:baz" is used, this interpreted as
1301      -- consisting of three entries, 'foo', 'bar', 'baz'.
1302      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1303      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1304      --
1305      -- Notice that no attempt is made to fully replace the 'standard'
1306      -- split marker ':' with the Windows / DOS one, ';'. The reason being
1307      -- that this will cause too much breakage for users & ':' will
1308      -- work fine even with DOS paths, if you're not insisting on being silly.
1309      -- So, use either.
1310     splitUp []             = []
1311     splitUp (x:':':div:xs) | div `elem` dir_markers
1312                            = ((x:':':div:p): splitUp rs)
1313                            where
1314                               (p,rs) = findNextPath xs
1315           -- we used to check for existence of the path here, but that
1316           -- required the IO monad to be threaded through the command-line
1317           -- parser which is quite inconvenient.  The 
1318     splitUp xs = cons p (splitUp rs)
1319                where
1320                  (p,rs) = findNextPath xs
1321     
1322                  cons "" xs = xs
1323                  cons x  xs = x:xs
1324
1325     -- will be called either when we've consumed nought or the
1326     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1327     -- finding the next split marker.
1328     findNextPath xs = 
1329         case break (`elem` split_markers) xs of
1330            (p, d:ds) -> (p, ds)
1331            (p, xs)   -> (p, xs)
1332
1333     split_markers :: [Char]
1334     split_markers = [':', ';']
1335
1336     dir_markers :: [Char]
1337     dir_markers = ['/', '\\']
1338 #endif
1339
1340 -- -----------------------------------------------------------------------------
1341 -- tmpDir, where we store temporary files.
1342
1343 setTmpDir :: FilePath -> DynFlags -> DynFlags
1344 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1345   where
1346 #if !defined(mingw32_HOST_OS)
1347      canonicalise p = normalisePath p
1348 #else
1349         -- Canonicalisation of temp path under win32 is a bit more
1350         -- involved: (a) strip trailing slash, 
1351         --           (b) normalise slashes
1352         --           (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1353         -- 
1354      canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1355
1356         -- if we're operating under cygwin, and TMP/TEMP is of
1357         -- the form "/cygdrive/drive/path", translate this to
1358         -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1359         -- understand /cygdrive paths.)
1360      xltCygdrive path
1361       | "/cygdrive/" `isPrefixOf` path = 
1362           case drop (length "/cygdrive/") path of
1363             drive:xs@('/':_) -> drive:':':xs
1364             _ -> path
1365       | otherwise = path
1366
1367         -- strip the trailing backslash (awful, but we only do this once).
1368      removeTrailingSlash path = 
1369        case last path of
1370          '/'  -> init path
1371          '\\' -> init path
1372          _    -> path
1373 #endif
1374
1375 -----------------------------------------------------------------------------
1376 -- Hpc stuff
1377
1378 setOptHpcDir :: String -> DynP ()
1379 setOptHpcDir arg  = upd $ \ d -> d{hpcDir = arg}
1380
1381 -----------------------------------------------------------------------------
1382 -- Via-C compilation stuff
1383
1384 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1385                               [String]) -- for registerised HC compilations
1386 machdepCCOpts dflags
1387 #if alpha_TARGET_ARCH
1388         =       ( ["-w", "-mieee"
1389 #ifdef HAVE_THREADED_RTS_SUPPORT
1390                     , "-D_REENTRANT"
1391 #endif
1392                    ], [] )
1393         -- For now, to suppress the gcc warning "call-clobbered
1394         -- register used for global register variable", we simply
1395         -- disable all warnings altogether using the -w flag. Oh well.
1396
1397 #elif hppa_TARGET_ARCH
1398         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1399         -- (very nice, but too bad the HP /usr/include files don't agree.)
1400         = ( ["-D_HPUX_SOURCE"], [] )
1401
1402 #elif m68k_TARGET_ARCH
1403       -- -fno-defer-pop : for the .hc files, we want all the pushing/
1404       --    popping of args to routines to be explicit; if we let things
1405       --    be deferred 'til after an STGJUMP, imminent death is certain!
1406       --
1407       -- -fomit-frame-pointer : *don't*
1408       --     It's better to have a6 completely tied up being a frame pointer
1409       --     rather than let GCC pick random things to do with it.
1410       --     (If we want to steal a6, then we would try to do things
1411       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
1412         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1413
1414 #elif i386_TARGET_ARCH
1415       -- -fno-defer-pop : basically the same game as for m68k
1416       --
1417       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1418       --   the fp (%ebp) for our register maps.
1419         =  let n_regs = stolen_x86_regs dflags
1420                sta = opt_Static
1421            in
1422                     ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1423 --                    , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else "" 
1424                       ],
1425                       [ "-fno-defer-pop",
1426 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1427                         -- Some gccs are configured with
1428                         -- -momit-leaf-frame-pointer on by default, and it
1429                         -- apparently takes precedence over 
1430                         -- -fomit-frame-pointer, so we disable it first here.
1431                         "-mno-omit-leaf-frame-pointer",
1432 #endif
1433 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1434                         "-fno-unit-at-a-time",
1435                         -- unit-at-a-time doesn't do us any good, and screws
1436                         -- up -split-objs by moving the split markers around.
1437                         -- It's only turned on with -O2, but put it here just
1438                         -- in case someone uses -optc-O2.
1439 #endif
1440                         "-fomit-frame-pointer",
1441                         -- we want -fno-builtin, because when gcc inlines
1442                         -- built-in functions like memcpy() it tends to
1443                         -- run out of registers, requiring -monly-n-regs
1444                         "-fno-builtin",
1445                         "-DSTOLEN_X86_REGS="++show n_regs ]
1446                     )
1447
1448 #elif ia64_TARGET_ARCH
1449         = ( [], ["-fomit-frame-pointer", "-G0"] )
1450
1451 #elif x86_64_TARGET_ARCH
1452         = ( [], ["-fomit-frame-pointer",
1453                  "-fno-asynchronous-unwind-tables",
1454                         -- the unwind tables are unnecessary for HC code,
1455                         -- and get in the way of -split-objs.  Another option
1456                         -- would be to throw them away in the mangler, but this
1457                         -- is easier.
1458 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1459                  "-fno-unit-at-a-time",
1460                         -- unit-at-a-time doesn't do us any good, and screws
1461                         -- up -split-objs by moving the split markers around.
1462                         -- It's only turned on with -O2, but put it here just
1463                         -- in case someone uses -optc-O2.
1464 #endif
1465                  "-fno-builtin"
1466                         -- calling builtins like strlen() using the FFI can
1467                         -- cause gcc to run out of regs, so use the external
1468                         -- version.
1469                 ] )
1470
1471 #elif sparc_TARGET_ARCH
1472         = ( [], ["-w"] )
1473         -- For now, to suppress the gcc warning "call-clobbered
1474         -- register used for global register variable", we simply
1475         -- disable all warnings altogether using the -w flag. Oh well.
1476
1477 #elif powerpc_apple_darwin_TARGET
1478       -- -no-cpp-precomp:
1479       --     Disable Apple's precompiling preprocessor. It's a great thing
1480       --     for "normal" programs, but it doesn't support register variable
1481       --     declarations.
1482         = ( [], ["-no-cpp-precomp"] )
1483 #else
1484         = ( [], [] )
1485 #endif
1486
1487 picCCOpts :: DynFlags -> [String]
1488 picCCOpts dflags
1489 #if darwin_TARGET_OS
1490       -- Apple prefers to do things the other way round.
1491       -- PIC is on by default.
1492       -- -mdynamic-no-pic:
1493       --     Turn off PIC code generation.
1494       -- -fno-common:
1495       --     Don't generate "common" symbols - these are unwanted
1496       --     in dynamic libraries.
1497
1498     | opt_PIC
1499         = ["-fno-common"]
1500     | otherwise
1501         = ["-mdynamic-no-pic"]
1502 #elif mingw32_TARGET_OS
1503       -- no -fPIC for Windows
1504         = []
1505 #else
1506     | opt_PIC
1507         = ["-fPIC"]
1508     | otherwise
1509         = []
1510 #endif
1511
1512 -- -----------------------------------------------------------------------------
1513 -- Splitting
1514
1515 can_split :: Bool
1516 can_split =  
1517 #if    defined(i386_TARGET_ARCH)     \
1518     || defined(x86_64_TARGET_ARCH)   \
1519     || defined(alpha_TARGET_ARCH)    \
1520     || defined(hppa_TARGET_ARCH)     \
1521     || defined(m68k_TARGET_ARCH)     \
1522     || defined(mips_TARGET_ARCH)     \
1523     || defined(powerpc_TARGET_ARCH)  \
1524     || defined(rs6000_TARGET_ARCH)   \
1525     || defined(sparc_TARGET_ARCH) 
1526    True
1527 #else
1528    False
1529 #endif
1530