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