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