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