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