[project @ 1997-12-02 18:08:54 by quintela]
[ghc-hetmet.git] / ghc / compiler / main / CmdLineOpts.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1996
3 %
4 \section[CmdLineOpts]{Things to do with command-line options}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module CmdLineOpts (
10         CoreToDo(..),
11         SimplifierSwitch(..),
12         StgToDo(..),
13         SwitchResult(..),
14         classifyOpts,
15
16         intSwitchSet,
17         switchIsOn,
18
19         maybe_CompilingGhcInternals,
20         opt_AllStrict,
21         opt_AutoSccsOnAllToplevs,
22         opt_AutoSccsOnExportedToplevs,
23         opt_AutoSccsOnIndividualCafs,
24         opt_CompilingGhcInternals,
25         opt_D_dump_absC,
26         opt_D_dump_asm,
27         opt_D_dump_deriv,
28         opt_D_dump_ds,
29         opt_D_dump_flatC,
30         opt_D_dump_occur_anal,
31         opt_D_dump_rdr,
32         opt_D_dump_realC,
33         opt_D_dump_rn,
34         opt_D_dump_simpl,
35         opt_D_dump_simpl_iterations,
36         opt_D_dump_spec,
37         opt_D_dump_stg,
38         opt_D_dump_stranal,
39         opt_D_dump_tc,
40         opt_D_show_passes,
41         opt_D_show_rn_trace,
42         opt_D_simplifier_stats,
43         opt_D_source_stats,
44         opt_D_verbose_core2core,
45         opt_D_verbose_stg2stg,
46         opt_DoCoreLinting,
47         opt_DoStgLinting,
48         opt_DoSemiTagging,
49         opt_DoEtaReduction,
50         opt_DoTickyProfiling,
51         opt_EnsureSplittableC,
52         opt_FoldrBuildOn,
53         opt_ForConcurrent,
54         opt_GlasgowExts,
55         opt_GranMacros,
56         opt_HiMap,
57         opt_IgnoreIfacePragmas,
58         opt_IrrefutableTuples,
59         opt_LiberateCaseThreshold,
60         opt_NoImplicitPrelude,
61         opt_NumbersStrict,
62         opt_OmitBlackHoling,
63         opt_OmitInterfacePragmas,
64         opt_PprStyle_All,
65         opt_PprStyle_Debug,
66         opt_PprStyle_User,              -- ToDo: rm
67         opt_PprUserLength,
68         opt_ProduceC,
69         opt_ProduceHi,
70         opt_ProduceS,
71         opt_ReportWhyUnfoldingsDisallowed,
72         opt_ReturnInRegsThreshold,
73         opt_SccGroup,
74         opt_SccProfilingOn,
75         opt_ShowImportSpecs,
76         opt_SigsRequired,
77         opt_SourceUnchanged,
78         opt_SpecialiseAll,
79         opt_SpecialiseImports,
80         opt_SpecialiseOverloaded,
81         opt_SpecialiseTrace,
82         opt_SpecialiseUnboxed,
83         opt_StgDoLetNoEscapes,
84
85         opt_InterfaceUnfoldThreshold,
86         opt_UnfoldingCreationThreshold,
87         opt_UnfoldingConDiscount,
88         opt_UnfoldingUseThreshold,
89         opt_UnfoldingKeenessFactor,
90
91         opt_Verbose,
92         opt_WarnNameShadowing,
93         opt_WarnUnusedNames,
94         opt_WarnIncompletePatterns, opt_WarnOverlappedPatterns, opt_WarnSimplePatterns,
95         opt_WarnMissingMethods,
96         opt_WarnDuplicateExports,
97         opt_PruneTyDecls, opt_PruneInstDecls,
98         opt_D_show_unused_imports,
99         opt_D_show_rn_stats,
100         
101         all_toplev_ids_visible
102     ) where
103
104 IMPORT_1_3(Array(array, (//)))
105 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
106 import PreludeGlaST     -- bad bad bad boy, Will (_Array internals)
107 #else
108 import GlaExts
109 import ArrBase
110 #if __GLASGOW_HASKELL__ >= 209
111 import Addr
112 #endif
113 -- 2.04 and later exports Lift from GlaExts
114 #if __GLASGOW_HASKELL__ < 204
115 import PrelBase (Lift(..))
116 #endif
117 #endif
118
119 CHK_Ubiq() -- debugging consistency check
120
121 import Argv
122 import Constants        -- Default values for some flags
123 import Maybes           ( assocMaybe, firstJust, maybeToBool )
124 import Util             ( startsWith, panic, panic#, assertPanic )
125 \end{code}
126
127 A command-line {\em switch} is (generally) either on or off; e.g., the
128 ``verbose'' (-v) switch is either on or off.  (The \tr{-G<group>}
129 switch is an exception; it's set to a string, or nothing.)
130
131 A list of {\em ToDo}s is things to be done in a particular part of
132 processing.  A (fictitious) example for the Core-to-Core simplifier
133 might be: run the simplifier, then run the strictness analyser, then
134 run the simplifier again (three ``todos'').
135
136 There are three ``to-do processing centers'' at the moment.  In the
137 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
138 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
139 (\tr{simplStg/SimplStg.lhs}).
140
141 %************************************************************************
142 %*                                                                      *
143 \subsection{Datatypes associated with command-line options}
144 %*                                                                      *
145 %************************************************************************
146
147 \begin{code}
148 data SwitchResult
149   = SwBool      Bool            -- on/off
150   | SwString    FAST_STRING     -- nothing or a String
151   | SwInt       Int             -- nothing or an Int
152 \end{code}
153
154 \begin{code}
155 data CoreToDo           -- These are diff core-to-core passes,
156                         -- which may be invoked in any order,
157                         -- as many times as you like.
158
159   = CoreDoSimplify      -- The core-to-core simplifier.
160         (SimplifierSwitch -> SwitchResult)
161                         -- Each run of the simplifier can take a different
162                         -- set of simplifier-specific flags.
163   | CoreDoCalcInlinings1
164   | CoreDoCalcInlinings2
165   | CoreDoFloatInwards
166   | CoreDoFullLaziness
167   | CoreLiberateCase
168   | CoreDoPrintCore
169   | CoreDoStaticArgs
170   | CoreDoStrictness
171   | CoreDoSpecialising
172   | CoreDoFoldrBuildWorkerWrapper
173   | CoreDoFoldrBuildWWAnal
174 \end{code}
175
176 \begin{code}
177 data StgToDo
178   = StgDoStaticArgs
179   | StgDoUpdateAnalysis
180   | StgDoLambdaLift
181   | StgDoMassageForProfiling  -- should be (next to) last
182   -- There's also setStgVarInfo, but its absolute "lastness"
183   -- is so critical that it is hardwired in (no flag).
184   | D_stg_stats
185 \end{code}
186
187 \begin{code}
188 data SimplifierSwitch
189   = SimplOkToDupCode
190   | SimplFloatLetsExposingWHNF
191   | SimplOkToFloatPrimOps
192   | SimplAlwaysFloatLetsFromLets
193   | SimplDoCaseElim
194   | SimplReuseCon
195   | SimplCaseOfCase
196   | SimplLetToCase
197   | SimplMayDeleteConjurableIds
198   | SimplPedanticBottoms -- see Simplifier for an explanation
199   | SimplDoArityExpand   -- expand arity of bindings
200   | SimplDoFoldrBuild    -- This is the per-simplification flag;
201                          -- see also FoldrBuildOn, used elsewhere
202                          -- in the compiler.
203   | SimplDoInlineFoldrBuild
204                          -- inline foldr/build (*after* f/b rule is used)
205
206   | IgnoreINLINEPragma
207   | SimplDoLambdaEtaExpansion
208
209   | EssentialUnfoldingsOnly -- never mind the thresholds, only
210                             -- do unfoldings that *must* be done
211                             -- (to saturate constructors and primitives)
212
213   | ShowSimplifierProgress  -- report counts on every interation
214
215   | MaxSimplifierIterations Int
216
217   | KeepSpecPragmaIds       -- We normally *toss* Ids we can do without
218   | KeepUnusedBindings
219
220   | SimplNoLetFromCase      -- used when turning off floating entirely
221   | SimplNoLetFromApp       -- (for experimentation only) WDP 95/10
222   | SimplNoLetFromStrictLet
223
224   | SimplDontFoldBackAppend
225                         -- we fold `foldr (:)' back into flip (++),
226                         -- but we *don't* want to do it when compiling
227                         -- List.hs, otherwise
228                         -- xs ++ ys = foldr (:) ys xs
229                         -- {- via our loopback -}
230                         -- xs ++ ys = xs ++ ys
231                         -- Oops!
232                         -- So only use this flag inside List.hs
233                         -- (Sigh, what a HACK, Andy.  WDP 96/01)
234
235   | SimplCaseMerge
236   | SimplCaseScrutinee  -- This flag tells that the expression being simplified is
237                         -- the scrutinee of a case expression, so we should
238                         -- apply the scrutinee discount when considering inlinings.
239                         -- See SimplVar.lhs
240 \end{code}
241
242 %************************************************************************
243 %*                                                                      *
244 \subsection{Classifying command-line options}
245 %*                                                                      *
246 %************************************************************************
247
248 \begin{code}
249 lookUp           :: FAST_STRING -> Bool
250 lookup_int       :: String -> Maybe Int
251 lookup_def_int   :: String -> Int -> Int
252 lookup_def_float :: String -> Float -> Float
253 lookup_str       :: String -> Maybe String
254
255 lookUp     sw = maybeToBool (assoc_opts sw)
256         
257 lookup_str sw = firstJust (map (startsWith sw) unpacked_opts)
258
259 lookup_int sw = case (lookup_str sw) of
260                   Nothing -> Nothing
261                   Just xx -> Just (read xx)
262
263 lookup_def_int sw def = case (lookup_str sw) of
264                             Nothing -> def              -- Use default
265                             Just xx -> read xx
266
267 lookup_def_float sw def = case (lookup_str sw) of
268                             Nothing -> def              -- Use default
269                             Just xx -> read xx
270
271 assoc_opts    = assocMaybe [ (a, True) | a <- argv ]
272 unpacked_opts = map _UNPK_ argv
273 \end{code}
274
275 \begin{code}
276 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
277 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
278 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
279 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
280 opt_CompilingGhcInternals       = maybeToBool maybe_CompilingGhcInternals
281 maybe_CompilingGhcInternals     = lookup_str "-fcompiling-ghc-internals="
282 opt_D_dump_absC                 = lookUp  SLIT("-ddump-absC")
283 opt_D_dump_asm                  = lookUp  SLIT("-ddump-asm")
284 opt_D_dump_deriv                = lookUp  SLIT("-ddump-deriv")
285 opt_D_dump_ds                   = lookUp  SLIT("-ddump-ds")
286 opt_D_dump_flatC                = lookUp  SLIT("-ddump-flatC")
287 opt_D_dump_occur_anal           = lookUp  SLIT("-ddump-occur-anal")
288 opt_D_dump_rdr                  = lookUp  SLIT("-ddump-rdr")
289 opt_D_dump_realC                = lookUp  SLIT("-ddump-realC")
290 opt_D_dump_rn                   = lookUp  SLIT("-ddump-rn")
291 opt_D_dump_simpl                = lookUp  SLIT("-ddump-simpl")
292 opt_D_dump_simpl_iterations     = lookUp  SLIT("-ddump-simpl-iterations")
293 opt_D_dump_spec                 = lookUp  SLIT("-ddump-spec")
294 opt_D_dump_stg                  = lookUp  SLIT("-ddump-stg")
295 opt_D_dump_stranal              = lookUp  SLIT("-ddump-stranal")
296 opt_D_dump_tc                   = lookUp  SLIT("-ddump-tc")
297 opt_D_show_passes               = lookUp  SLIT("-dshow-passes")
298 opt_D_show_rn_trace             = lookUp  SLIT("-dshow-rn-trace")
299 opt_D_simplifier_stats          = lookUp  SLIT("-dsimplifier-stats")
300 opt_D_source_stats              = lookUp  SLIT("-dsource-stats")
301 opt_D_verbose_core2core         = lookUp  SLIT("-dverbose-simpl")
302 opt_D_verbose_stg2stg           = lookUp  SLIT("-dverbose-stg")
303 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
304 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
305 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
306 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
307 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
308 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
309 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
310 opt_ForConcurrent               = lookUp  SLIT("-fconcurrent")
311 opt_GranMacros                  = lookUp  SLIT("-fgransim")
312 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
313 --UNUSED:opt_Haskell_1_3        = lookUp  SLIT("-fhaskell-1.3")
314 opt_HiMap                       = lookup_str "-himap="  -- file saying where to look for .hi files
315 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
316 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
317 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
318 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
319 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
320 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
321 opt_PprStyle_All                = lookUp  SLIT("-dppr-all")
322 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
323 opt_PprStyle_User               = lookUp  SLIT("-dppr-user")
324 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
325 opt_ProduceC                    = lookup_str "-C="
326 opt_ProduceS                    = lookup_str "-S="
327 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
328 opt_ReportWhyUnfoldingsDisallowed= lookUp SLIT("-freport-disallowed-unfoldings")
329 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
330 opt_ShowImportSpecs             = lookUp  SLIT("-fshow-import-specs")
331 opt_SigsRequired                = lookUp  SLIT("-fsignatures-required")
332 opt_SourceUnchanged             = lookUp  SLIT("-fsource-unchanged")
333 opt_SpecialiseAll               = lookUp  SLIT("-fspecialise-all")
334 opt_SpecialiseImports           = lookUp  SLIT("-fspecialise-imports")
335 opt_SpecialiseOverloaded        = lookUp  SLIT("-fspecialise-overloaded")
336 opt_SpecialiseTrace             = lookUp  SLIT("-ftrace-specialisation")
337 opt_SpecialiseUnboxed           = lookUp  SLIT("-fspecialise-unboxed")
338 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
339 opt_ReturnInRegsThreshold       = lookup_int "-freturn-in-regs-threshold"
340 opt_SccGroup                    = lookup_str "-G="
341 opt_Verbose                     = lookUp  SLIT("-v")
342
343 opt_InterfaceUnfoldThreshold    = lookup_def_int "-funfolding-interface-threshold" iNTERFACE_UNFOLD_THRESHOLD
344 opt_UnfoldingCreationThreshold  = lookup_def_int "-funfolding-creation-threshold"  uNFOLDING_CREATION_THRESHOLD
345 opt_UnfoldingUseThreshold       = lookup_def_int "-funfolding-use-threshold"       uNFOLDING_USE_THRESHOLD
346 opt_UnfoldingConDiscount        = lookup_def_int "-funfolding-con-discount"        uNFOLDING_CON_DISCOUNT_WEIGHT
347                         
348 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold"       lIBERATE_CASE_THRESHOLD
349 opt_UnfoldingKeenessFactor      = lookup_def_float "-funfolding-keeness-factor"    uNFOLDING_KEENESS_FACTOR
350 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
351 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
352 opt_WarnOverlappedPatterns      = lookUp  SLIT("-fwarn-overlapped-patterns")
353 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
354 opt_WarnUnusedNames             = lookUp  SLIT("-fwarn-unused-names")
355 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
356 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
357 opt_PruneTyDecls                = not (lookUp SLIT("-fno-prune-tydecls"))
358 opt_PruneInstDecls              = not (lookUp SLIT("-fno-prune-instdecls"))
359 opt_D_show_unused_imports       = lookUp SLIT("-dshow-unused-imports")
360 opt_D_show_rn_stats             = lookUp SLIT("-dshow-rn-stats")
361
362 -- opt_UnfoldingOverrideThreshold       = lookup_int "-funfolding-override-threshold"
363 \end{code}
364
365
366 \begin{code}
367 all_toplev_ids_visible :: Bool
368 all_toplev_ids_visible = 
369   not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
370   opt_EnsureSplittableC        ||  -- Splitting requires visiblilty
371   opt_AutoSccsOnAllToplevs         -- ditto for profiling 
372                                    -- (ToDo: fix up the auto-annotation
373                                    -- pass in the desugarer to avoid having
374                                    -- to do this)
375
376 \end{code}
377
378
379
380 \begin{code}
381 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
382                  [StgToDo])     -- STG-to-STG   processing spec
383
384 classifyOpts = sep argv [] [] -- accumulators...
385   where
386     sep :: [FAST_STRING]                         -- cmd-line opts (input)
387         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
388         -> ([CoreToDo], [StgToDo])       -- result
389
390     sep [] core_td stg_td -- all done!
391       = (reverse core_td, reverse stg_td)
392
393 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
394 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
395 #       define IGNORE_ARG()   sep opts core_td stg_td
396
397     sep (opt1:opts) core_td stg_td
398       =
399         case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
400
401           ',' : _       -> IGNORE_ARG() -- it is for the parser
402
403           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
404                            simpl_sep opts defaultSimplSwitches core_td stg_td
405
406           "-fcalc-inlinings1"-> CORE_TD(CoreDoCalcInlinings1)
407           "-fcalc-inlinings2"-> CORE_TD(CoreDoCalcInlinings2)
408           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
409           "-ffull-laziness"  -> CORE_TD(CoreDoFullLaziness)
410           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
411           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
412           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
413           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
414           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
415           "-ffoldr-build-worker-wrapper"  -> CORE_TD(CoreDoFoldrBuildWorkerWrapper)
416           "-ffoldr-build-ww-anal"  -> CORE_TD(CoreDoFoldrBuildWWAnal)
417
418           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
419           "-fupdate-analysis" -> STG_TD(StgDoUpdateAnalysis)
420           "-dstg-stats"       -> STG_TD(D_stg_stats)
421           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
422           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
423
424           _ -> -- NB: the driver is really supposed to handle bad options
425                IGNORE_ARG()
426
427     ----------------
428
429     simpl_sep :: [FAST_STRING]      -- cmd-line opts (input)
430         -> [SimplifierSwitch]       -- simplifier-switch accumulator
431         -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
432         -> ([CoreToDo], [StgToDo])  -- result
433
434         -- "simpl_sep" tailcalls "sep" once it's seen one set
435         -- of SimplifierSwitches for a CoreDoSimplify.
436
437 #ifdef DEBUG
438     simpl_sep input@[] simpl_sw core_td stg_td
439       = panic "simpl_sep []"
440 #endif
441
442         -- The SimplifierSwitches should be delimited by "[" and "]".
443
444     simpl_sep (opt1:opts) simpl_sw core_td stg_td
445       = case (_UNPK_ opt1) of
446           "[" -> simpl_sep opts simpl_sw core_td stg_td
447           "]" -> let
448                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
449                  in
450                  sep opts (this_simpl : core_td) stg_td
451
452 #         define SIMPL_SW(sw) simpl_sep opts (sw:simpl_sw) core_td stg_td
453
454           -- the non-"just match a string" options are at the end...
455           "-fshow-simplifier-progress"      -> SIMPL_SW(ShowSimplifierProgress)
456           "-fcode-duplication-ok"           -> SIMPL_SW(SimplOkToDupCode)
457           "-ffloat-lets-exposing-whnf"      -> SIMPL_SW(SimplFloatLetsExposingWHNF)
458           "-ffloat-primops-ok"              -> SIMPL_SW(SimplOkToFloatPrimOps)
459           "-falways-float-lets-from-lets"   -> SIMPL_SW(SimplAlwaysFloatLetsFromLets)
460           "-fdo-case-elim"                  -> SIMPL_SW(SimplDoCaseElim)
461           "-fdo-lambda-eta-expansion"       -> SIMPL_SW(SimplDoLambdaEtaExpansion)
462           "-fdo-foldr-build"                -> SIMPL_SW(SimplDoFoldrBuild)
463           "-fdo-not-fold-back-append"       -> SIMPL_SW(SimplDontFoldBackAppend)
464           "-fdo-arity-expand"               -> SIMPL_SW(SimplDoArityExpand)
465           "-fdo-inline-foldr-build"         -> SIMPL_SW(SimplDoInlineFoldrBuild)
466           "-freuse-con"                     -> SIMPL_SW(SimplReuseCon)
467           "-fcase-of-case"                  -> SIMPL_SW(SimplCaseOfCase)
468           "-fcase-merge"                    -> SIMPL_SW(SimplCaseMerge)
469           "-flet-to-case"                   -> SIMPL_SW(SimplLetToCase)
470           "-fpedantic-bottoms"              -> SIMPL_SW(SimplPedanticBottoms)
471           "-fkeep-spec-pragma-ids"          -> SIMPL_SW(KeepSpecPragmaIds)
472           "-fkeep-unused-bindings"          -> SIMPL_SW(KeepUnusedBindings)
473           "-fmay-delete-conjurable-ids"     -> SIMPL_SW(SimplMayDeleteConjurableIds)
474           "-fessential-unfoldings-only"     -> SIMPL_SW(EssentialUnfoldingsOnly)
475           "-fignore-inline-pragma"          -> SIMPL_SW(IgnoreINLINEPragma)
476           "-fno-let-from-case"              -> SIMPL_SW(SimplNoLetFromCase)
477           "-fno-let-from-app"               -> SIMPL_SW(SimplNoLetFromApp)
478           "-fno-let-from-strict-let"        -> SIMPL_SW(SimplNoLetFromStrictLet)
479
480           o | starts_with_msi  -> SIMPL_SW(MaxSimplifierIterations (read after_msi))
481            where
482             maybe_msi           = startsWith "-fmax-simplifier-iterations"   o
483             starts_with_msi     = maybeToBool maybe_msi
484             (Just after_msi)    = maybe_msi
485
486           _ -> -- NB: the driver is really supposed to handle bad options
487                simpl_sep opts simpl_sw core_td stg_td
488 \end{code}
489
490 %************************************************************************
491 %*                                                                      *
492 \subsection{Switch ordering}
493 %*                                                                      *
494 %************************************************************************
495
496 In spite of the @Produce*@ and @SccGroup@ constructors, these things
497 behave just like enumeration types.
498
499 \begin{code}
500 instance Eq SimplifierSwitch where
501     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
502
503 instance Ord SimplifierSwitch where
504     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
505     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
506
507 tagOf_SimplSwitch SimplOkToDupCode              =(ILIT(0) :: FAST_INT)
508 tagOf_SimplSwitch SimplFloatLetsExposingWHNF    = ILIT(1)
509 tagOf_SimplSwitch SimplOkToFloatPrimOps         = ILIT(2)
510 tagOf_SimplSwitch SimplAlwaysFloatLetsFromLets  = ILIT(3)
511 tagOf_SimplSwitch SimplDoCaseElim               = ILIT(4)
512 tagOf_SimplSwitch SimplReuseCon                 = ILIT(5)
513 tagOf_SimplSwitch SimplCaseOfCase               = ILIT(6)
514 tagOf_SimplSwitch SimplLetToCase                = ILIT(7)
515 tagOf_SimplSwitch SimplMayDeleteConjurableIds   = ILIT(9)
516 tagOf_SimplSwitch SimplPedanticBottoms          = ILIT(10)
517 tagOf_SimplSwitch SimplDoArityExpand            = ILIT(11)
518 tagOf_SimplSwitch SimplDoFoldrBuild             = ILIT(12)
519 tagOf_SimplSwitch SimplDoInlineFoldrBuild       = ILIT(14)
520 tagOf_SimplSwitch IgnoreINLINEPragma            = ILIT(15)
521 tagOf_SimplSwitch SimplDoLambdaEtaExpansion     = ILIT(16)
522 tagOf_SimplSwitch EssentialUnfoldingsOnly       = ILIT(19)
523 tagOf_SimplSwitch ShowSimplifierProgress        = ILIT(20)
524 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(21)
525 tagOf_SimplSwitch KeepSpecPragmaIds             = ILIT(25)
526 tagOf_SimplSwitch KeepUnusedBindings            = ILIT(26)
527 tagOf_SimplSwitch SimplNoLetFromCase            = ILIT(27)
528 tagOf_SimplSwitch SimplNoLetFromApp             = ILIT(28)
529 tagOf_SimplSwitch SimplNoLetFromStrictLet       = ILIT(29)
530 tagOf_SimplSwitch SimplDontFoldBackAppend       = ILIT(30)
531 tagOf_SimplSwitch SimplCaseMerge                = ILIT(31)
532 tagOf_SimplSwitch SimplCaseScrutinee            = ILIT(32)
533
534 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
535
536 tagOf_SimplSwitch _ = panic# "tagOf_SimplSwitch"
537
538 lAST_SIMPL_SWITCH_TAG = IBOX(tagOf_SimplSwitch SimplCaseScrutinee)
539 \end{code}
540
541 %************************************************************************
542 %*                                                                      *
543 \subsection{Switch lookup}
544 %*                                                                      *
545 %************************************************************************
546
547 \begin{code}
548 #if __GLASGOW_HASKELL__ == 201
549 # define ARRAY      Array
550 # define LIFT       GHCbase.Lift
551 # define SET_TO     =:
552 (=:) a b = (a,b)
553 #elif __GLASGOW_HASKELL__ >= 202
554 # define ARRAY      Array
555 # define LIFT       Lift
556 # define SET_TO     =:
557 (=:) a b = (a,b)
558 #else
559 # define ARRAY      _Array
560 # define LIFT       _Lift
561 # define SET_TO     :=
562 #endif
563
564 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
565
566 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
567                                         -- in the list; defaults right at the end.
568   = let
569         tidied_on_switches = foldl rm_dups [] on_switches
570                 -- The fold*l* ensures that we keep the latest switches;
571                 -- ie the ones that occur earliest in the list.
572
573         sw_tbl :: Array Int SwitchResult
574
575         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
576                         all_undefined)
577                  // defined_elems
578
579         all_undefined = [ i SET_TO SwBool False | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
580
581         defined_elems = map mk_assoc_elem tidied_on_switches
582     in
583     -- (avoid some unboxing, bounds checking, and other horrible things:)
584     case sw_tbl of { ARRAY bounds_who_needs_'em stuff ->
585     \ switch ->
586         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
587           LIFT v -> v
588     }
589   where
590     mk_assoc_elem k@(MaxSimplifierIterations lvl)       = IBOX(tagOf_SimplSwitch k) SET_TO SwInt lvl
591
592     mk_assoc_elem k = IBOX(tagOf_SimplSwitch k) SET_TO SwBool   True -- I'm here, Mom!
593
594     -- cannot have duplicates if we are going to use the array thing
595     rm_dups switches_so_far switch
596       = if switch `is_elem` switches_so_far
597         then switches_so_far
598         else switch : switches_so_far
599       where
600         sw `is_elem` []     = False
601         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
602                             || sw `is_elem` ss
603 \end{code}
604
605 Default settings for simplifier switches
606
607 \begin{code}
608 defaultSimplSwitches = [MaxSimplifierIterations         1
609                        ]
610 \end{code}
611
612 %************************************************************************
613 %*                                                                      *
614 \subsection{Misc functions for command-line options}
615 %*                                                                      *
616 %************************************************************************
617
618
619 \begin{code}
620 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
621
622 switchIsOn lookup_fn switch
623   = case (lookup_fn switch) of
624       SwBool False -> False
625       _            -> True
626
627 stringSwitchSet :: (switch -> SwitchResult)
628                 -> (FAST_STRING -> switch)
629                 -> Maybe FAST_STRING
630
631 stringSwitchSet lookup_fn switch
632   = case (lookup_fn (switch (panic "stringSwitchSet"))) of
633       SwString str -> Just str
634       _            -> Nothing
635
636 intSwitchSet :: (switch -> SwitchResult)
637              -> (Int -> switch)
638              -> Maybe Int
639
640 intSwitchSet lookup_fn switch
641   = case (lookup_fn (switch (panic "intSwitchSet"))) of
642       SwInt int -> Just int
643       _         -> Nothing
644 \end{code}