RTS tidyup sweep, first phase
[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(..), v_Ways, v_Build_tag, v_RTS_Build_tag, isRTSWay,
21
22         -- Output style options
23         opt_PprUserLength,
24         opt_SuppressUniques,
25         opt_PprStyle_Debug,
26         opt_NoDebugOutput,
27
28         -- profiling opts
29         opt_SccProfilingOn,
30
31         -- Hpc opts
32         opt_Hpc,
33
34         -- language opts
35         opt_DictsStrict,
36         opt_IrrefutableTuples,
37         opt_Parallel,
38
39         -- optimisation opts
40         opt_DsMultiTyVar,
41         opt_NoStateHack,
42         opt_SimpleListLiterals,
43         opt_SpecInlineJoinPoints,
44         opt_CprOff,
45         opt_SimplNoPreInlining,
46         opt_SimplExcessPrecision,
47         opt_MaxWorkerArgs,
48
49         -- Unfolding control
50         opt_UF_CreationThreshold,
51         opt_UF_UseThreshold,
52         opt_UF_FunAppDiscount,
53         opt_UF_KeenessFactor,
54         opt_UF_DearOp,
55
56         -- Optimization fuel controls
57         opt_Fuel,
58
59         -- Related to linking
60         opt_PIC,
61         opt_Static,
62
63         -- misc opts
64         opt_IgnoreDotGhci,
65         opt_ErrorSpans,
66         opt_GranMacros,
67         opt_HiVersion,
68         opt_HistorySize,
69         opt_OmitBlackHoling,
70         opt_Unregisterised,
71         v_Ld_inputs,
72         tablesNextToCode,
73         opt_StubDeadValues,
74
75     -- For the parser
76     addOpt, removeOpt, addWay, findBuildTag, v_opt_C_ready
77   ) where
78
79 #include "HsVersions.h"
80
81 import Config
82 import FastString
83 import Util
84 import Maybes           ( firstJust )
85 import Panic
86
87 import Data.IORef
88 import System.IO.Unsafe ( unsafePerformIO )
89 import Data.List
90
91 -----------------------------------------------------------------------------
92 -- Static flags
93
94 initStaticOpts :: IO ()
95 initStaticOpts = writeIORef v_opt_C_ready True
96
97 addOpt :: String -> IO ()
98 addOpt = consIORef v_opt_C
99
100 addWay :: WayName -> IO ()
101 addWay = consIORef v_Ways
102
103 removeOpt :: String -> IO ()
104 removeOpt f = do
105   fs <- readIORef v_opt_C
106   writeIORef v_opt_C $! filter (/= f) fs    
107
108 lookUp           :: FastString -> Bool
109 lookup_def_int   :: String -> Int -> Int
110 lookup_def_float :: String -> Float -> Float
111 lookup_str       :: String -> Maybe String
112
113 -- holds the static opts while they're being collected, before
114 -- being unsafely read by unpacked_static_opts below.
115 GLOBAL_VAR(v_opt_C, defaultStaticOpts, [String])
116 GLOBAL_VAR(v_opt_C_ready, False, Bool)
117
118 staticFlags :: [String]
119 staticFlags = unsafePerformIO $ do
120   ready <- readIORef v_opt_C_ready
121   if (not ready)
122         then panic "Static flags have not been initialised!\n        Please call GHC.newSession or GHC.parseStaticFlags early enough."
123         else readIORef v_opt_C
124
125 -- -static is the default
126 defaultStaticOpts :: [String]
127 defaultStaticOpts = ["-static"]
128
129 packed_static_opts :: [FastString]
130 packed_static_opts   = map mkFastString staticFlags
131
132 lookUp     sw = sw `elem` packed_static_opts
133         
134 -- (lookup_str "foo") looks for the flag -foo=X or -fooX, 
135 -- and returns the string X
136 lookup_str sw 
137    = case firstJust (map (stripPrefix sw) staticFlags) of
138         Just ('=' : str) -> Just str
139         Just str         -> Just str
140         Nothing          -> Nothing     
141
142 lookup_def_int sw def = case (lookup_str sw) of
143                             Nothing -> def              -- Use default
144                             Just xx -> try_read sw xx
145
146 lookup_def_float sw def = case (lookup_str sw) of
147                             Nothing -> def              -- Use default
148                             Just xx -> try_read sw xx
149
150
151 try_read :: Read a => String -> String -> a
152 -- (try_read sw str) tries to read s; if it fails, it
153 -- bleats about flag sw
154 try_read sw str
155   = case reads str of
156         ((x,_):_) -> x  -- Be forgiving: ignore trailing goop, and alternative parses
157         []        -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
158                         -- ToDo: hack alert. We should really parse the arugments
159                         --       and announce errors in a more civilised way.
160
161
162 {-
163  Putting the compiler options into temporary at-files
164  may turn out to be necessary later on if we turn hsc into
165  a pure Win32 application where I think there's a command-line
166  length limit of 255. unpacked_opts understands the @ option.
167
168 unpacked_opts :: [String]
169 unpacked_opts =
170   concat $
171   map (expandAts) $
172   map unpackFS argv  -- NOT ARGV any more: v_Static_hsc_opts
173   where
174    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
175    expandAts l = [l]
176 -}
177
178 opt_IgnoreDotGhci :: Bool
179 opt_IgnoreDotGhci               = lookUp (fsLit "-ignore-dot-ghci")
180
181 -- debugging opts
182 opt_SuppressUniques :: Bool
183 opt_SuppressUniques             = lookUp  (fsLit "-dsuppress-uniques")
184 opt_PprStyle_Debug  :: Bool
185 opt_PprStyle_Debug              = lookUp  (fsLit "-dppr-debug")
186 opt_PprUserLength   :: Int
187 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
188 opt_Fuel            :: Int
189 opt_Fuel                        = lookup_def_int "-dopt-fuel" maxBound
190 opt_NoDebugOutput   :: Bool
191 opt_NoDebugOutput               = lookUp  (fsLit "-dno-debug-output")
192
193
194 -- profiling opts
195 opt_SccProfilingOn :: Bool
196 opt_SccProfilingOn              = lookUp  (fsLit "-fscc-profiling")
197
198 -- Hpc opts
199 opt_Hpc :: Bool
200 opt_Hpc                         = lookUp (fsLit "-fhpc")  
201
202 -- language opts
203 opt_DictsStrict :: Bool
204 opt_DictsStrict                 = lookUp  (fsLit "-fdicts-strict")
205 opt_IrrefutableTuples :: Bool
206 opt_IrrefutableTuples           = lookUp  (fsLit "-firrefutable-tuples")
207 opt_Parallel :: Bool
208 opt_Parallel                    = lookUp  (fsLit "-fparallel")
209
210 -- optimisation opts
211 opt_DsMultiTyVar :: Bool
212 opt_DsMultiTyVar                = not (lookUp (fsLit "-fno-ds-multi-tyvar"))
213         -- On by default
214
215 opt_SpecInlineJoinPoints :: Bool
216 opt_SpecInlineJoinPoints        = lookUp  (fsLit "-fspec-inline-join-points")
217
218 opt_SimpleListLiterals :: Bool
219 opt_SimpleListLiterals          = lookUp  (fsLit "-fsimple-list-literals")
220
221 opt_NoStateHack :: Bool
222 opt_NoStateHack                 = lookUp  (fsLit "-fno-state-hack")
223
224 opt_CprOff :: Bool
225 opt_CprOff                      = lookUp  (fsLit "-fcpr-off")
226         -- Switch off CPR analysis in the new demand analyser
227 opt_MaxWorkerArgs :: Int
228 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
229
230 opt_GranMacros :: Bool
231 opt_GranMacros                  = lookUp  (fsLit "-fgransim")
232 opt_HiVersion :: Integer
233 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
234 opt_HistorySize :: Int
235 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
236 opt_OmitBlackHoling :: Bool
237 opt_OmitBlackHoling             = lookUp  (fsLit "-dno-black-holing")
238 opt_StubDeadValues  :: Bool
239 opt_StubDeadValues              = lookUp  (fsLit "-dstub-dead-values")
240
241 -- Simplifier switches
242 opt_SimplNoPreInlining :: Bool
243 opt_SimplNoPreInlining          = lookUp  (fsLit "-fno-pre-inlining")
244         -- NoPreInlining is there just to see how bad things
245         -- get if you don't do it!
246 opt_SimplExcessPrecision :: Bool
247 opt_SimplExcessPrecision        = lookUp  (fsLit "-fexcess-precision")
248
249 -- Unfolding control
250 opt_UF_CreationThreshold :: Int
251 opt_UF_CreationThreshold        = lookup_def_int "-funfolding-creation-threshold"  (45::Int)
252 opt_UF_UseThreshold :: Int
253 opt_UF_UseThreshold             = lookup_def_int "-funfolding-use-threshold"       (6::Int)     -- Discounts can be big
254 opt_UF_FunAppDiscount :: Int
255 opt_UF_FunAppDiscount           = lookup_def_int "-funfolding-fun-discount"        (6::Int)     -- It's great to inline a fn
256 opt_UF_KeenessFactor :: Float
257 opt_UF_KeenessFactor            = lookup_def_float "-funfolding-keeness-factor"    (1.5::Float)
258
259 opt_UF_DearOp :: Int
260 opt_UF_DearOp   = ( 4 :: Int)
261
262
263 -- Related to linking
264 opt_PIC :: Bool
265 #if darwin_TARGET_OS && x86_64_TARGET_ARCH
266 opt_PIC                         = True
267 #else
268 opt_PIC                         = lookUp (fsLit "-fPIC")
269 #endif
270 opt_Static :: Bool
271 opt_Static                      = lookUp  (fsLit "-static")
272 opt_Unregisterised :: Bool
273 opt_Unregisterised              = lookUp  (fsLit "-funregisterised")
274
275 -- Derived, not a real option.  Determines whether we will be compiling
276 -- info tables that reside just before the entry code, or with an
277 -- indirection to the entry code.  See TABLES_NEXT_TO_CODE in 
278 -- includes/rts/storage/InfoTables.h.
279 tablesNextToCode :: Bool
280 tablesNextToCode                = not opt_Unregisterised
281                                   && cGhcEnableTablesNextToCode == "YES"
282
283 -- Include full span info in error messages, instead of just the start position.
284 opt_ErrorSpans :: Bool
285 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
286
287
288 -- object files and libraries to be linked in are collected here.
289 -- ToDo: perhaps this could be done without a global, it wasn't obvious
290 -- how to do it though --SDM.
291 GLOBAL_VAR(v_Ld_inputs, [],      [String])
292
293 -----------------------------------------------------------------------------
294 -- Ways
295
296 -- The central concept of a "way" is that all objects in a given
297 -- program must be compiled in the same "way".  Certain options change
298 -- parameters of the virtual machine, eg. profiling adds an extra word
299 -- to the object header, so profiling objects cannot be linked with
300 -- non-profiling objects.
301
302 -- After parsing the command-line options, we determine which "way" we
303 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
304
305 -- We then find the "build-tag" associated with this way, and this
306 -- becomes the suffix used to find .hi files and libraries used in
307 -- this compilation.
308
309 GLOBAL_VAR(v_Build_tag, "", String)
310
311 -- The RTS has its own build tag, because there are some ways that
312 -- affect the RTS only.
313 GLOBAL_VAR(v_RTS_Build_tag, "", String)
314
315 data WayName
316   = WayThreaded
317   | WayDebug
318   | WayProf
319   | WayEventLog
320   | WayTicky
321   | WayPar
322   | WayGran
323   | WayNDP
324   | WayUser_a
325   | WayUser_b
326   | WayUser_c
327   | WayUser_d
328   | WayUser_e
329   | WayUser_f
330   | WayUser_g
331   | WayUser_h
332   | WayUser_i
333   | WayUser_j
334   | WayUser_k
335   | WayUser_l
336   | WayUser_m
337   | WayUser_n
338   | WayUser_o
339   | WayUser_A
340   | WayUser_B
341   deriving (Eq,Ord)
342
343 GLOBAL_VAR(v_Ways, [] ,[WayName])
344
345 allowed_combination :: [WayName] -> Bool
346 allowed_combination way = and [ x `allowedWith` y 
347                               | x <- way, y <- way, x < y ]
348   where
349         -- Note ordering in these tests: the left argument is
350         -- <= the right argument, according to the Ord instance
351         -- on Way above.
352
353         -- debug is allowed with everything
354         _ `allowedWith` WayDebug                = True
355         WayDebug `allowedWith` _                = True
356
357         WayProf `allowedWith` WayNDP            = True
358         WayThreaded `allowedWith` WayProf       = True
359         WayThreaded `allowedWith` WayEventLog   = True
360         _ `allowedWith` _                       = False
361
362
363 findBuildTag :: IO [String]  -- new options
364 findBuildTag = do
365   way_names <- readIORef v_Ways
366   let ws = sort (nub way_names)
367
368   if not (allowed_combination ws)
369       then ghcError (CmdLineError $
370                     "combination not supported: "  ++
371                     foldr1 (\a b -> a ++ '/':b) 
372                     (map (wayName . lkupWay) ws))
373       else let ways    = map lkupWay ws
374                tag     = mkBuildTag (filter (not.wayRTSOnly) ways)
375                rts_tag = mkBuildTag ways
376                flags   = map wayOpts ways
377            in do
378            writeIORef v_Build_tag tag
379            writeIORef v_RTS_Build_tag rts_tag
380            return (concat flags)
381
382
383
384 mkBuildTag :: [Way] -> String
385 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
386
387 lkupWay :: WayName -> Way
388 lkupWay w = 
389    case lookup w way_details of
390         Nothing -> error "findBuildTag"
391         Just details -> details
392
393 isRTSWay :: WayName -> Bool
394 isRTSWay = wayRTSOnly . lkupWay 
395
396 data Way = Way {
397   wayTag     :: String,
398   wayRTSOnly :: Bool,
399   wayName    :: String,
400   wayOpts    :: [String]
401   }
402
403 way_details :: [ (WayName, Way) ]
404 way_details =
405   [ (WayThreaded, Way "thr" True "Threaded" [
406 #if defined(freebsd_TARGET_OS)
407 --        "-optc-pthread"
408 --      , "-optl-pthread"
409         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
410         -- which GHC has some problems with.  It's currently not clear whether
411         -- the problems are our fault or theirs, but it seems that using the
412         -- alternative 1:1 threading library libthr works around it:
413           "-optl-lthr"
414 #elif defined(solaris2_TARGET_OS)
415           "-optl-lrt"
416 #endif
417         ] ),
418
419     (WayDebug, Way "debug" True "Debug" [] ),
420
421     (WayProf, Way  "p" False "Profiling"
422         [ "-fscc-profiling"
423         , "-DPROFILING"
424         , "-optc-DPROFILING" ]),
425
426     (WayEventLog, Way  "l" True "RTS Event Logging"
427         [ "-DEVENTLOG"
428         , "-optc-DEVENTLOG" ]),
429
430     (WayTicky, Way  "t" True "Ticky-ticky Profiling"  
431         [ "-DTICKY_TICKY"
432         , "-optc-DTICKY_TICKY" ]),
433
434     -- optl's below to tell linker where to find the PVM library -- HWL
435     (WayPar, Way  "mp" False "Parallel" 
436         [ "-fparallel"
437         , "-D__PARALLEL_HASKELL__"
438         , "-optc-DPAR"
439         , "-package concurrent"
440         , "-optc-w"
441         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
442         , "-optl-lpvm3"
443         , "-optl-lgpvm3" ]),
444
445     -- at the moment we only change the RTS and could share compiler and libs!
446     (WayPar, Way  "mt" False "Parallel ticky profiling" 
447         [ "-fparallel"
448         , "-D__PARALLEL_HASKELL__"
449         , "-optc-DPAR"
450         , "-optc-DPAR_TICKY"
451         , "-package concurrent"
452         , "-optc-w"
453         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
454         , "-optl-lpvm3"
455         , "-optl-lgpvm3" ]),
456
457     (WayPar, Way  "md" False "Distributed" 
458         [ "-fparallel"
459         , "-D__PARALLEL_HASKELL__"
460         , "-D__DISTRIBUTED_HASKELL__"
461         , "-optc-DPAR"
462         , "-optc-DDIST"
463         , "-package concurrent"
464         , "-optc-w"
465         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
466         , "-optl-lpvm3"
467         , "-optl-lgpvm3" ]),
468
469     (WayGran, Way  "mg" False "GranSim"
470         [ "-fgransim"
471         , "-D__GRANSIM__"
472         , "-optc-DGRAN"
473         , "-package concurrent" ]),
474
475     (WayNDP, Way  "ndp" False "Nested data parallelism"
476         [ "-XParr"
477         , "-fvectorise"]),
478
479     (WayUser_a,  Way  "a"  False "User way 'a'"  ["$WAY_a_REAL_OPTS"]), 
480     (WayUser_b,  Way  "b"  False "User way 'b'"  ["$WAY_b_REAL_OPTS"]), 
481     (WayUser_c,  Way  "c"  False "User way 'c'"  ["$WAY_c_REAL_OPTS"]), 
482     (WayUser_d,  Way  "d"  False "User way 'd'"  ["$WAY_d_REAL_OPTS"]), 
483     (WayUser_e,  Way  "e"  False "User way 'e'"  ["$WAY_e_REAL_OPTS"]), 
484     (WayUser_f,  Way  "f"  False "User way 'f'"  ["$WAY_f_REAL_OPTS"]), 
485     (WayUser_g,  Way  "g"  False "User way 'g'"  ["$WAY_g_REAL_OPTS"]), 
486     (WayUser_h,  Way  "h"  False "User way 'h'"  ["$WAY_h_REAL_OPTS"]), 
487     (WayUser_i,  Way  "i"  False "User way 'i'"  ["$WAY_i_REAL_OPTS"]), 
488     (WayUser_j,  Way  "j"  False "User way 'j'"  ["$WAY_j_REAL_OPTS"]), 
489     (WayUser_k,  Way  "k"  False "User way 'k'"  ["$WAY_k_REAL_OPTS"]), 
490     (WayUser_l,  Way  "l"  False "User way 'l'"  ["$WAY_l_REAL_OPTS"]), 
491     (WayUser_m,  Way  "m"  False "User way 'm'"  ["$WAY_m_REAL_OPTS"]), 
492     (WayUser_n,  Way  "n"  False "User way 'n'"  ["$WAY_n_REAL_OPTS"]), 
493     (WayUser_o,  Way  "o"  False "User way 'o'"  ["$WAY_o_REAL_OPTS"]), 
494     (WayUser_A,  Way  "A"  False "User way 'A'"  ["$WAY_A_REAL_OPTS"]), 
495     (WayUser_B,  Way  "B"  False "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
496   ]
497