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