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