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