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