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