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