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