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