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