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