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