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