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