Merge branch 'master' into ghc-generics
[ghc-hetmet.git] / compiler / main / StaticFlags.hs
1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
3
4 -----------------------------------------------------------------------------
5 --
6 -- Static flags
7 --
8 -- Static flags can only be set once, on the command-line.  Inside GHC,
9 -- each static flag corresponds to a top-level value, usually of type Bool.
10 --
11 -- (c) The University of Glasgow 2005
12 --
13 -----------------------------------------------------------------------------
14
15 module StaticFlags (
16         staticFlags,
17         initStaticOpts,
18
19         -- Ways
20         WayName(..), Way(..), v_Ways, isRTSWay, mkBuildTag,
21
22         -- Output style options
23         opt_PprUserLength,
24         opt_PprCols,
25         opt_PprCaseAsLet,
26         opt_PprStyle_Debug, opt_TraceLevel,
27         opt_NoDebugOutput, 
28
29         -- Suppressing boring aspects of core dumps
30         opt_SuppressAll,
31         opt_SuppressUniques,
32         opt_SuppressCoercions,
33         opt_SuppressModulePrefixes,
34         opt_SuppressTypeApplications,
35         opt_SuppressIdInfo,
36         opt_SuppressTypeSignatures,
37
38         -- profiling opts
39         opt_SccProfilingOn,
40
41         -- Hpc opts
42         opt_Hpc,
43
44         -- language opts
45         opt_DictsStrict,
46         opt_IrrefutableTuples,
47         opt_Parallel,
48
49         -- optimisation opts
50         opt_NoStateHack,
51         opt_SimpleListLiterals,
52         opt_CprOff,
53         opt_SimplNoPreInlining,
54         opt_SimplExcessPrecision,
55         opt_NoOptCoercion,
56         opt_MaxWorkerArgs,
57
58         -- Unfolding control
59         opt_UF_CreationThreshold,
60         opt_UF_UseThreshold,
61         opt_UF_FunAppDiscount,
62         opt_UF_DictDiscount,
63         opt_UF_KeenessFactor,
64         opt_UF_DearOp,
65
66         -- Optimization fuel controls
67         opt_Fuel,
68
69         -- Related to linking
70         opt_PIC,
71         opt_Static,
72
73         -- misc opts
74         opt_IgnoreDotGhci,
75         opt_ErrorSpans,
76         opt_GranMacros,
77         opt_HiVersion,
78         opt_HistorySize,
79         opt_OmitBlackHoling,
80         opt_Unregisterised,
81         v_Ld_inputs,
82         tablesNextToCode,
83         opt_StubDeadValues,
84         opt_Ticky,
85
86     -- For the parser
87     addOpt, removeOpt, addWay, getWayFlags, v_opt_C_ready
88   ) where
89
90 #include "HsVersions.h"
91
92 import Config
93 import FastString
94 import Util
95 import Maybes           ( firstJusts )
96 import Panic
97
98 import Data.Maybe       ( listToMaybe )
99 import Data.IORef
100 import System.IO.Unsafe ( unsafePerformIO )
101 import Data.List
102
103 -----------------------------------------------------------------------------
104 -- Static flags
105
106 initStaticOpts :: IO ()
107 initStaticOpts = writeIORef v_opt_C_ready True
108
109 addOpt :: String -> IO ()
110 addOpt = consIORef v_opt_C
111
112 addWay :: WayName -> IO ()
113 addWay = consIORef v_Ways . lkupWay
114
115 removeOpt :: String -> IO ()
116 removeOpt f = do
117   fs <- readIORef v_opt_C
118   writeIORef v_opt_C $! filter (/= f) fs    
119
120 lookUp           :: FastString -> Bool
121 lookup_def_int   :: String -> Int -> Int
122 lookup_def_float :: String -> Float -> Float
123 lookup_str       :: String -> Maybe String
124
125 -- holds the static opts while they're being collected, before
126 -- being unsafely read by unpacked_static_opts below.
127 GLOBAL_VAR(v_opt_C, defaultStaticOpts, [String])
128 GLOBAL_VAR(v_opt_C_ready, False, Bool)
129
130 staticFlags :: [String]
131 staticFlags = unsafePerformIO $ do
132   ready <- readIORef v_opt_C_ready
133   if (not ready)
134         then panic "Static flags have not been initialised!\n        Please call GHC.newSession or GHC.parseStaticFlags early enough."
135         else readIORef v_opt_C
136
137 -- -static is the default
138 defaultStaticOpts :: [String]
139 defaultStaticOpts = ["-static"]
140
141 packed_static_opts :: [FastString]
142 packed_static_opts   = map mkFastString staticFlags
143
144 lookUp     sw = sw `elem` packed_static_opts
145         
146 -- (lookup_str "foo") looks for the flag -foo=X or -fooX, 
147 -- and returns the string X
148 lookup_str sw 
149    = case firstJusts (map (stripPrefix sw) staticFlags) of
150         Just ('=' : str) -> Just str
151         Just str         -> Just str
152         Nothing          -> Nothing     
153
154 lookup_def_int sw def = case (lookup_str sw) of
155                             Nothing -> def              -- Use default
156                             Just xx -> try_read sw xx
157
158 lookup_def_float sw def = case (lookup_str sw) of
159                             Nothing -> def              -- Use default
160                             Just xx -> try_read sw xx
161
162
163 try_read :: Read a => String -> String -> a
164 -- (try_read sw str) tries to read s; if it fails, it
165 -- bleats about flag sw
166 try_read sw str
167   = case reads str of
168         ((x,_):_) -> x  -- Be forgiving: ignore trailing goop, and alternative parses
169         []        -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
170                         -- ToDo: hack alert. We should really parse the arugments
171                         --       and announce errors in a more civilised way.
172
173
174 {-
175  Putting the compiler options into temporary at-files
176  may turn out to be necessary later on if we turn hsc into
177  a pure Win32 application where I think there's a command-line
178  length limit of 255. unpacked_opts understands the @ option.
179
180 unpacked_opts :: [String]
181 unpacked_opts =
182   concat $
183   map (expandAts) $
184   map unpackFS argv  -- NOT ARGV any more: v_Static_hsc_opts
185   where
186    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
187    expandAts l = [l]
188 -}
189
190 opt_IgnoreDotGhci :: Bool
191 opt_IgnoreDotGhci               = lookUp (fsLit "-ignore-dot-ghci")
192
193 -- debugging options
194 -- | Suppress all that is suppressable in core dumps.
195 opt_SuppressAll :: Bool
196 opt_SuppressAll 
197         = lookUp  (fsLit "-dsuppress-all")
198
199 -- | Suppress unique ids on variables.
200 opt_SuppressUniques :: Bool
201 opt_SuppressUniques
202         =  lookUp  (fsLit "-dsuppress-all")
203         || lookUp  (fsLit "-dsuppress-uniques")
204
205 -- | Suppress all coercions, them replacing with '...'
206 opt_SuppressCoercions :: Bool
207 opt_SuppressCoercions
208         =  lookUp  (fsLit "-dsuppress-all") 
209         || lookUp  (fsLit "-dsuppress-coercions")
210
211 -- | Suppress module id prefixes on variables.
212 opt_SuppressModulePrefixes :: Bool
213 opt_SuppressModulePrefixes
214         =  lookUp  (fsLit "-dsuppress-all")
215         || lookUp  (fsLit "-dsuppress-module-prefixes")
216
217 -- | Suppress type applications.
218 opt_SuppressTypeApplications :: Bool
219 opt_SuppressTypeApplications
220         =  lookUp  (fsLit "-dsuppress-all")
221         || lookUp  (fsLit "-dsuppress-type-applications")
222
223 -- | Suppress info such as arity and unfoldings on identifiers.
224 opt_SuppressIdInfo :: Bool
225 opt_SuppressIdInfo 
226         =  lookUp  (fsLit "-dsuppress-all")
227         || lookUp  (fsLit "-dsuppress-idinfo")
228
229 -- | Suppress seprate type signatures in core, but leave types on lambda bound vars
230 opt_SuppressTypeSignatures :: Bool
231 opt_SuppressTypeSignatures
232         =  lookUp  (fsLit "-dsuppress-all")
233         || lookUp  (fsLit "-dsuppress-type-signatures")
234
235
236 -- | Display case expressions with a single alternative as strict let bindings
237 opt_PprCaseAsLet :: Bool
238 opt_PprCaseAsLet                = lookUp   (fsLit "-dppr-case-as-let")
239
240 -- | Set the maximum width of the dumps
241 --   If GHC's command line options are bad then the options parser uses the
242 --   pretty printer display the error message. In this case the staticFlags
243 --   won't be initialized yet, so we must check for this case explicitly 
244 --   and return the default value.
245 opt_PprCols :: Int
246 opt_PprCols 
247  = unsafePerformIO
248  $ do   ready <- readIORef v_opt_C_ready
249         if (not ready)
250                 then return 100
251                 else return $ lookup_def_int "-dppr-cols" 100
252
253
254 opt_PprStyle_Debug  :: Bool
255 opt_PprStyle_Debug              = lookUp  (fsLit "-dppr-debug")
256
257 opt_TraceLevel :: Int
258 opt_TraceLevel = lookup_def_int "-dtrace-level" 1       -- Standard level is 1
259                                                         -- Less verbose is 0
260
261 opt_PprUserLength   :: Int
262 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
263
264 opt_Fuel            :: Int
265 opt_Fuel                        = lookup_def_int "-dopt-fuel" maxBound
266
267 opt_NoDebugOutput   :: Bool
268 opt_NoDebugOutput               = lookUp  (fsLit "-dno-debug-output")
269
270 -- profiling opts
271 opt_SccProfilingOn :: Bool
272 opt_SccProfilingOn              = lookUp  (fsLit "-fscc-profiling")
273
274 -- Hpc opts
275 opt_Hpc :: Bool
276 opt_Hpc                         = lookUp (fsLit "-fhpc")  
277
278 -- language opts
279 opt_DictsStrict :: Bool
280 opt_DictsStrict                 = lookUp  (fsLit "-fdicts-strict")
281
282 opt_IrrefutableTuples :: Bool
283 opt_IrrefutableTuples           = lookUp  (fsLit "-firrefutable-tuples")
284
285 opt_Parallel :: Bool
286 opt_Parallel                    = lookUp  (fsLit "-fparallel")
287
288 opt_SimpleListLiterals :: Bool
289 opt_SimpleListLiterals          = lookUp  (fsLit "-fsimple-list-literals")
290
291 opt_NoStateHack :: Bool
292 opt_NoStateHack                 = lookUp  (fsLit "-fno-state-hack")
293
294 opt_CprOff :: Bool
295 opt_CprOff                      = lookUp  (fsLit "-fcpr-off")
296         -- Switch off CPR analysis in the new demand analyser
297 opt_MaxWorkerArgs :: Int
298 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
299
300 opt_GranMacros :: Bool
301 opt_GranMacros                  = lookUp  (fsLit "-fgransim")
302
303 opt_HiVersion :: Integer
304 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
305
306 opt_HistorySize :: Int
307 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
308
309 opt_OmitBlackHoling :: Bool
310 opt_OmitBlackHoling             = lookUp  (fsLit "-dno-black-holing")
311
312 opt_StubDeadValues  :: Bool
313 opt_StubDeadValues              = lookUp  (fsLit "-dstub-dead-values")
314
315 -- Simplifier switches
316 opt_SimplNoPreInlining :: Bool
317 opt_SimplNoPreInlining          = lookUp  (fsLit "-fno-pre-inlining")
318         -- NoPreInlining is there just to see how bad things
319         -- get if you don't do it!
320 opt_SimplExcessPrecision :: Bool
321 opt_SimplExcessPrecision        = lookUp  (fsLit "-fexcess-precision")
322
323 opt_NoOptCoercion :: Bool
324 opt_NoOptCoercion               = lookUp  (fsLit "-fno-opt-coercion")
325
326 -- Unfolding control
327 -- See Note [Discounts and thresholds] in CoreUnfold
328
329 opt_UF_CreationThreshold, opt_UF_UseThreshold :: Int
330 opt_UF_DearOp, opt_UF_FunAppDiscount, opt_UF_DictDiscount :: Int
331 opt_UF_KeenessFactor :: Float
332
333 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
334 opt_UF_UseThreshold      = lookup_def_int "-funfolding-use-threshold"      (6::Int)
335 opt_UF_FunAppDiscount    = lookup_def_int "-funfolding-fun-discount"       (6::Int)
336
337 opt_UF_DictDiscount      = lookup_def_int "-funfolding-dict-discount"      (3::Int)
338    -- Be fairly keen to inline a fuction if that means
339    -- we'll be able to pick the right method from a dictionary
340
341 opt_UF_KeenessFactor     = lookup_def_float "-funfolding-keeness-factor"   (1.5::Float)
342 opt_UF_DearOp            = ( 4 :: Int)
343
344
345 -- Related to linking
346 opt_PIC :: Bool
347 #if darwin_TARGET_OS && x86_64_TARGET_ARCH
348 opt_PIC                         = True
349 #elif darwin_TARGET_OS
350 opt_PIC                         = lookUp (fsLit "-fPIC") || not opt_Static
351 #else
352 opt_PIC                         = lookUp (fsLit "-fPIC")
353 #endif
354 opt_Static :: Bool
355 opt_Static                      = lookUp  (fsLit "-static")
356 opt_Unregisterised :: Bool
357 opt_Unregisterised              = lookUp  (fsLit "-funregisterised")
358
359 -- Derived, not a real option.  Determines whether we will be compiling
360 -- info tables that reside just before the entry code, or with an
361 -- indirection to the entry code.  See TABLES_NEXT_TO_CODE in 
362 -- includes/rts/storage/InfoTables.h.
363 tablesNextToCode :: Bool
364 tablesNextToCode                = not opt_Unregisterised
365                                   && cGhcEnableTablesNextToCode == "YES"
366
367 -- Include full span info in error messages, instead of just the start position.
368 opt_ErrorSpans :: Bool
369 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
370
371 opt_Ticky :: Bool
372 opt_Ticky                       = lookUp (fsLit "-ticky")
373
374 -- object files and libraries to be linked in are collected here.
375 -- ToDo: perhaps this could be done without a global, it wasn't obvious
376 -- how to do it though --SDM.
377 GLOBAL_VAR(v_Ld_inputs, [],      [String])
378
379 -----------------------------------------------------------------------------
380 -- Ways
381
382 -- The central concept of a "way" is that all objects in a given
383 -- program must be compiled in the same "way".  Certain options change
384 -- parameters of the virtual machine, eg. profiling adds an extra word
385 -- to the object header, so profiling objects cannot be linked with
386 -- non-profiling objects.
387
388 -- After parsing the command-line options, we determine which "way" we
389 -- are building - this might be a combination way, eg. profiling+threaded.
390
391 -- We then find the "build-tag" associated with this way, and this
392 -- becomes the suffix used to find .hi files and libraries used in
393 -- this compilation.
394
395 data WayName
396   = WayThreaded
397   | WayDebug
398   | WayProf
399   | WayEventLog
400   | WayPar
401   | WayGran
402   | WayNDP
403   | WayDyn
404   deriving (Eq,Ord)
405
406 GLOBAL_VAR(v_Ways, [] ,[Way])
407
408 allowed_combination :: [WayName] -> Bool
409 allowed_combination way = and [ x `allowedWith` y 
410                               | x <- way, y <- way, x < y ]
411   where
412         -- Note ordering in these tests: the left argument is
413         -- <= the right argument, according to the Ord instance
414         -- on Way above.
415
416         -- dyn is allowed with everything
417         _ `allowedWith` WayDyn                  = True
418         WayDyn `allowedWith` _                  = True
419
420         -- debug is allowed with everything
421         _ `allowedWith` WayDebug                = True
422         WayDebug `allowedWith` _                = True
423
424         WayProf `allowedWith` WayNDP            = True
425         WayThreaded `allowedWith` WayProf       = True
426         WayThreaded `allowedWith` WayEventLog   = True
427         _ `allowedWith` _                       = False
428
429
430 getWayFlags :: IO [String]  -- new options
431 getWayFlags = do
432   unsorted <- readIORef v_Ways
433   let ways = sortBy (compare `on` wayName) $
434              nubBy  ((==) `on` wayName) $ unsorted
435   writeIORef v_Ways ways
436
437   if not (allowed_combination (map wayName ways))
438       then ghcError (CmdLineError $
439                     "combination not supported: "  ++
440                     foldr1 (\a b -> a ++ '/':b) 
441                     (map wayDesc ways))
442       else
443            return (concatMap wayOpts ways)
444
445 mkBuildTag :: [Way] -> String
446 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
447
448 lkupWay :: WayName -> Way
449 lkupWay w = 
450    case listToMaybe (filter ((==) w . wayName) way_details) of
451         Nothing -> error "findBuildTag"
452         Just details -> details
453
454 isRTSWay :: WayName -> Bool
455 isRTSWay = wayRTSOnly . lkupWay 
456
457 data Way = Way {
458   wayName    :: WayName,
459   wayTag     :: String,
460   wayRTSOnly :: Bool,
461   wayDesc    :: String,
462   wayOpts    :: [String]
463   }
464
465 way_details :: [ Way ]
466 way_details =
467   [ Way WayThreaded "thr" True "Threaded" [
468 #if defined(freebsd_TARGET_OS)
469 --        "-optc-pthread"
470 --      , "-optl-pthread"
471         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
472         -- which GHC has some problems with.  It's currently not clear whether
473         -- the problems are our fault or theirs, but it seems that using the
474         -- alternative 1:1 threading library libthr works around it:
475           "-optl-lthr"
476 #elif defined(openbsd_TARGET_OS)
477           "-optc-pthread"
478         , "-optl-pthread"
479 #elif defined(solaris2_TARGET_OS)
480           "-optl-lrt"
481 #endif
482         ],
483
484     Way WayDebug "debug" True "Debug" [],
485
486     Way WayDyn "dyn" False "Dynamic"
487         [ "-DDYNAMIC"
488         , "-optc-DDYNAMIC" 
489 #if defined(mingw32_TARGET_OS)
490         -- On Windows, code that is to be linked into a dynamic library must be compiled
491         --      with -fPIC. Labels not in the current package are assumed to be in a DLL 
492         --      different from the current one.
493         , "-fPIC"
494 #elif defined(openbsd_TARGET_OS)
495         -- Without this, linking the shared libHSffi fails because
496         -- it uses pthread mutexes.
497         , "-optl-pthread"
498 #endif
499         ],
500
501     Way WayProf "p" False "Profiling"
502         [ "-fscc-profiling"
503         , "-DPROFILING"
504         , "-optc-DPROFILING" ],
505
506     Way WayEventLog "l" True "RTS Event Logging"
507         [ "-DTRACING"
508         , "-optc-DTRACING" ],
509
510     Way WayPar "mp" False "Parallel" 
511         [ "-fparallel"
512         , "-D__PARALLEL_HASKELL__"
513         , "-optc-DPAR"
514         , "-package concurrent"
515         , "-optc-w"
516         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
517         , "-optl-lpvm3"
518         , "-optl-lgpvm3" ],
519
520     -- at the moment we only change the RTS and could share compiler and libs!
521     Way WayPar "mt" False "Parallel ticky profiling" 
522         [ "-fparallel"
523         , "-D__PARALLEL_HASKELL__"
524         , "-optc-DPAR"
525         , "-optc-DPAR_TICKY"
526         , "-package concurrent"
527         , "-optc-w"
528         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
529         , "-optl-lpvm3"
530         , "-optl-lgpvm3" ],
531
532     Way WayPar "md" False "Distributed" 
533         [ "-fparallel"
534         , "-D__PARALLEL_HASKELL__"
535         , "-D__DISTRIBUTED_HASKELL__"
536         , "-optc-DPAR"
537         , "-optc-DDIST"
538         , "-package concurrent"
539         , "-optc-w"
540         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
541         , "-optl-lpvm3"
542         , "-optl-lgpvm3" ],
543
544     Way WayGran "mg" False "GranSim"
545         [ "-fgransim"
546         , "-D__GRANSIM__"
547         , "-optc-DGRAN"
548         , "-package concurrent" ],
549
550     Way WayNDP "ndp" False "Nested data parallelism"
551         [ "-XParr"
552         , "-fvectorise"]
553   ]