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