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