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