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