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