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