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