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