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