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