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