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