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