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