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