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