[project @ 2002-09-13 15:02:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / DriverState.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverState.hs,v 1.82 2002/09/13 15:02:34 simonpj Exp $
3 --
4 -- Settings for the driver
5 --
6 -- (c) The University of Glasgow 2002
7 --
8 -----------------------------------------------------------------------------
9
10 module DriverState where
11
12 #include "../includes/config.h"
13 #include "HsVersions.h"
14
15 import SysTools         ( getTopDir )
16 import ParsePkgConf     ( loadPackageConfig )
17 import Packages         ( PackageConfig(..), PackageConfigMap, 
18                           PackageName, mkPackageName, packageNameString,
19                           packageDependents,
20                           mungePackagePaths, emptyPkgMap, extendPkgMap, lookupPkg,
21                           preludePackage, rtsPackage, haskell98Package  )
22 import CmdLineOpts
23 import DriverPhases
24 import DriverUtil
25 import Util
26 import Config
27 import Panic
28
29 import DATA_IOREF       ( IORef, newIORef, readIORef, writeIORef )
30 import EXCEPTION
31
32 import List
33 import Char  
34 import Monad
35 import Maybe     ( fromJust, isJust )
36 import Directory ( doesDirectoryExist )
37
38 -----------------------------------------------------------------------------
39 -- non-configured things
40
41 cHaskell1Version = "5" -- i.e., Haskell 98
42
43 -----------------------------------------------------------------------------
44 -- GHC modes of operation
45
46 data GhcMode
47   = DoMkDependHS                        -- ghc -M
48   | DoMkDLL                             -- ghc --mk-dll
49   | StopBefore Phase                    -- ghc -E | -C | -S | -c
50   | DoMake                              -- ghc --make
51   | DoInteractive                       -- ghc --interactive
52   | DoLink                              -- [ the default ]
53   deriving (Eq,Show)
54
55 GLOBAL_VAR(v_GhcMode,     DoLink, GhcMode)
56 GLOBAL_VAR(v_GhcModeFlag, "",     String)
57
58 setMode :: GhcMode -> String -> IO ()
59 setMode m flag = do
60   old_mode <- readIORef v_GhcMode
61   old_flag <- readIORef v_GhcModeFlag
62   when (notNull old_flag && flag /= old_flag) $
63       throwDyn (UsageError 
64           ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
65   writeIORef v_GhcMode m
66   writeIORef v_GhcModeFlag flag
67
68 isCompManagerMode DoMake        = True
69 isCompManagerMode DoInteractive = True
70 isCompManagerMode _             = False
71
72 -----------------------------------------------------------------------------
73 -- Global compilation flags
74
75 -- Cpp-related flags
76 v_Hs_source_cpp_opts = global
77         [ "-D__HASKELL1__="++cHaskell1Version
78         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
79         , "-D__HASKELL98__"
80         , "-D__CONCURRENT_HASKELL__"
81         ]
82 {-# NOINLINE v_Hs_source_cpp_opts #-}
83
84
85 -- Keep output from intermediate phases
86 GLOBAL_VAR(v_Keep_hi_diffs,             False,          Bool)
87 GLOBAL_VAR(v_Keep_hc_files,             False,          Bool)
88 GLOBAL_VAR(v_Keep_s_files,              False,          Bool)
89 GLOBAL_VAR(v_Keep_raw_s_files,          False,          Bool)
90 GLOBAL_VAR(v_Keep_tmp_files,            False,          Bool)
91 #ifdef ILX
92 GLOBAL_VAR(v_Keep_il_files,             False,          Bool)
93 GLOBAL_VAR(v_Keep_ilx_files,            False,          Bool)
94 #endif
95
96 -- Misc
97 GLOBAL_VAR(v_Scale_sizes_by,            1.0,            Double)
98 GLOBAL_VAR(v_Static,                    True,           Bool)
99 GLOBAL_VAR(v_NoHsMain,                  False,          Bool)
100 GLOBAL_VAR(v_Recomp,                    True,           Bool)
101 GLOBAL_VAR(v_Collect_ghc_timing,        False,          Bool)
102 GLOBAL_VAR(v_Do_asm_mangling,           True,           Bool)
103 GLOBAL_VAR(v_Excess_precision,          False,          Bool)
104 GLOBAL_VAR(v_Read_DotGHCi,              True,           Bool)
105
106 -- Preprocessor flags
107 GLOBAL_VAR(v_Hs_source_pp_opts, [], [String])
108
109 -----------------------------------------------------------------------------
110 -- Splitting object files (for libraries)
111
112 GLOBAL_VAR(v_Split_object_files,        False,          Bool)
113 GLOBAL_VAR(v_Split_info,                ("",0),         (String,Int))
114         -- The split prefix and number of files
115
116         
117 can_split :: Bool
118 can_split =  prefixMatch "i386"    cTARGETPLATFORM
119           || prefixMatch "alpha"   cTARGETPLATFORM
120           || prefixMatch "hppa"    cTARGETPLATFORM
121           || prefixMatch "m68k"    cTARGETPLATFORM
122           || prefixMatch "mips"    cTARGETPLATFORM
123           || prefixMatch "powerpc" cTARGETPLATFORM
124           || prefixMatch "rs6000"  cTARGETPLATFORM
125           || prefixMatch "sparc"   cTARGETPLATFORM
126
127 -----------------------------------------------------------------------------
128 -- Compiler output options
129
130 GLOBAL_VAR(v_Output_dir,  Nothing, Maybe String)
131 GLOBAL_VAR(v_Output_file, Nothing, Maybe String)
132 GLOBAL_VAR(v_Output_hi,   Nothing, Maybe String)
133
134 -- called to verify that the output files & directories
135 -- point somewhere valid. 
136 --
137 -- The assumption is that the directory portion of these output
138 -- options will have to exist by the time 'verifyOutputFiles'
139 -- is invoked.
140 -- 
141 verifyOutputFiles :: IO ()
142 verifyOutputFiles = do
143   odir <- readIORef v_Output_dir
144   when (isJust odir) $ do
145      let dir = fromJust odir
146      flg <- doesDirectoryExist dir
147      when (not flg) (nonExistentDir "-odir" dir)
148   ofile <- readIORef v_Output_file
149   when (isJust ofile) $ do
150      let fn = fromJust ofile
151      flg <- doesDirNameExist fn
152      when (not flg) (nonExistentDir "-o" fn)
153   ohi <- readIORef v_Output_hi
154   when (isJust ohi) $ do
155      let hi = fromJust ohi
156      flg <- doesDirNameExist hi
157      when (not flg) (nonExistentDir "-ohi" hi)
158  where
159    nonExistentDir flg dir = 
160      throwDyn (CmdLineError ("error: directory portion of " ++ 
161                              show dir ++ " does not exist (used with " ++ 
162                              show flg ++ " option.)"))
163
164 GLOBAL_VAR(v_Object_suf,  Nothing, Maybe String)
165 GLOBAL_VAR(v_HC_suf,      Nothing, Maybe String)
166 GLOBAL_VAR(v_Hi_dir,      Nothing, Maybe String)
167 GLOBAL_VAR(v_Hi_suf,      "hi",    String)
168
169 GLOBAL_VAR(v_Ld_inputs, [],      [String])
170
171 odir_ify :: String -> IO String
172 odir_ify f = do
173   odir_opt <- readIORef v_Output_dir
174   case odir_opt of
175         Nothing -> return f
176         Just d  -> return (newdir d f)
177
178 osuf_ify :: String -> IO String
179 osuf_ify f = do
180   osuf_opt <- readIORef v_Object_suf
181   case osuf_opt of
182         Nothing -> return f
183         Just s  -> return (newsuf s f)
184
185 -----------------------------------------------------------------------------
186 -- Compiler optimisation options
187
188 GLOBAL_VAR(v_OptLevel, 0, Int)
189
190 setOptLevel :: Int -> IO ()
191 setOptLevel n = do
192   when (n >= 1) $ setLang HscC          -- turn on -fvia-C with -O
193   writeIORef v_OptLevel n
194
195 GLOBAL_VAR(v_minus_o2_for_C,            False, Bool)
196 GLOBAL_VAR(v_MaxSimplifierIterations,   4,     Int)
197 GLOBAL_VAR(v_StgStats,                  False, Bool)
198 GLOBAL_VAR(v_UsageSPInf,                False, Bool)  -- Off by default
199 GLOBAL_VAR(v_Strictness,                True,  Bool)
200 GLOBAL_VAR(v_CSE,                       True,  Bool)
201 GLOBAL_VAR(v_RuleCheck,                 Nothing,  Maybe String)
202
203 -- these are the static flags you get without -O.
204 hsc_minusNoO_flags =
205        [ 
206         "-fignore-interface-pragmas",
207         "-fomit-interface-pragmas",
208         "-fdo-lambda-eta-expansion",    -- This one is important for a tiresome reason:
209                                         -- we want to make sure that the bindings for data 
210                                         -- constructors are eta-expanded.  This is probably
211                                         -- a good thing anyway, but it seems fragile.
212         "-flet-no-escape"
213         ]
214
215 -- these are the static flags you get when -O is on.
216 hsc_minusO_flags =
217   [ 
218         "-fignore-asserts",
219         "-ffoldr-build-on",
220         "-fdo-eta-reduction",
221         "-fdo-lambda-eta-expansion",
222         "-fcase-merge",
223         "-flet-to-case",
224         "-flet-no-escape"
225    ]
226
227 hsc_minusO2_flags = hsc_minusO_flags    -- for now
228
229 getStaticOptimisationFlags 0 = hsc_minusNoO_flags
230 getStaticOptimisationFlags 1 = hsc_minusO_flags
231 getStaticOptimisationFlags n = hsc_minusO2_flags
232
233 buildCoreToDo :: IO [CoreToDo]
234 buildCoreToDo = do
235    opt_level  <- readIORef v_OptLevel
236    max_iter   <- readIORef v_MaxSimplifierIterations
237    usageSP    <- readIORef v_UsageSPInf
238    strictness <- readIORef v_Strictness
239    cse        <- readIORef v_CSE
240    rule_check <- readIORef v_RuleCheck
241
242    if opt_level == 0 then return
243       [
244         CoreDoSimplify (SimplPhase 0) [
245             MaxSimplifierIterations max_iter
246         ]
247       ]
248
249     else {- opt_level >= 1 -} return [ 
250
251         -- initial simplify: mk specialiser happy: minimum effort please
252         CoreDoSimplify SimplGently [
253                         --      Simplify "gently"
254                         -- Don't inline anything till full laziness has bitten
255                         -- In particular, inlining wrappers inhibits floating
256                         -- e.g. ...(case f x of ...)...
257                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
258                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
259                         -- and now the redex (f x) isn't floatable any more
260                         -- Similarly, don't apply any rules until after full 
261                         -- laziness.  Notably, list fusion can prevent floating.
262
263             NoCaseOfCase,
264                         -- Don't do case-of-case transformations.
265                         -- This makes full laziness work better
266             MaxSimplifierIterations max_iter
267         ],
268
269         -- Specialisation is best done before full laziness
270         -- so that overloaded functions have all their dictionary lambdas manifest
271         CoreDoSpecialising,
272
273         CoreDoFloatOutwards (FloatOutSw False False),
274         CoreDoFloatInwards,
275
276         CoreDoSimplify (SimplPhase 2) [
277                 -- Want to run with inline phase 2 after the specialiser to give
278                 -- maximum chance for fusion to work before we inline build/augment
279                 -- in phase 1.  This made a difference in 'ansi' where an 
280                 -- overloaded function wasn't inlined till too late.
281            MaxSimplifierIterations max_iter
282         ],
283         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
284
285         -- infer usage information here in case we need it later.
286         -- (add more of these where you need them --KSW 1999-04)
287         if usageSP then CoreDoUSPInf else CoreDoNothing,
288
289         CoreDoSimplify (SimplPhase 1) [
290                 -- Need inline-phase2 here so that build/augment get 
291                 -- inlined.  I found that spectral/hartel/genfft lost some useful
292                 -- strictness in the function sumcode' if augment is not inlined
293                 -- before strictness analysis runs
294            MaxSimplifierIterations max_iter
295         ],
296         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
297
298         CoreDoSimplify (SimplPhase 0) [
299                 -- Phase 0: allow all Ids to be inlined now
300                 -- This gets foldr inlined before strictness analysis
301
302            MaxSimplifierIterations 3
303                 -- At least 3 iterations because otherwise we land up with
304                 -- huge dead expressions because of an infelicity in the 
305                 -- simpifier.   
306                 --      let k = BIG in foldr k z xs
307                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
308                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
309                 -- Don't stop now!
310
311         ],
312         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
313
314 #ifdef OLD_STRICTNESS
315         CoreDoOldStrictness
316 #endif
317         if strictness then CoreDoStrictness else CoreDoNothing,
318         CoreDoWorkerWrapper,
319         CoreDoGlomBinds,
320
321         CoreDoSimplify (SimplPhase 0) [
322            MaxSimplifierIterations max_iter
323         ],
324
325         CoreDoFloatOutwards (FloatOutSw False   -- Not lambdas
326                                         True),  -- Float constants
327                 -- nofib/spectral/hartel/wang doubles in speed if you
328                 -- do full laziness late in the day.  It only happens
329                 -- after fusion and other stuff, so the early pass doesn't
330                 -- catch it.  For the record, the redex is 
331                 --        f_el22 (f_el21 r_midblock)
332
333
334         -- We want CSE to follow the final full-laziness pass, because it may
335         -- succeed in commoning up things floated out by full laziness.
336         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
337
338         if cse then CoreCSE else CoreDoNothing,
339
340         CoreDoFloatInwards,
341
342 -- Case-liberation for -O2.  This should be after
343 -- strictness analysis and the simplification which follows it.
344
345         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
346
347         if opt_level >= 2 then
348            CoreLiberateCase
349         else
350            CoreDoNothing,
351         if opt_level >= 2 then
352            CoreDoSpecConstr
353         else
354            CoreDoNothing,
355
356         -- Final clean-up simplification:
357         CoreDoSimplify (SimplPhase 0) [
358           MaxSimplifierIterations max_iter
359         ]
360      ]
361
362 buildStgToDo :: IO [ StgToDo ]
363 buildStgToDo = do
364   stg_stats <- readIORef v_StgStats
365   let flags1 | stg_stats = [ D_stg_stats ]
366              | otherwise = [ ]
367
368         -- STG passes
369   ways_ <- readIORef v_Ways
370   let flags2 | WayProf `elem` ways_ = StgDoMassageForProfiling : flags1
371              | otherwise            = flags1
372
373   return flags2
374
375 -----------------------------------------------------------------------------
376 -- Paths & Libraries
377
378 split_marker = ':'   -- not configurable (ToDo)
379
380 v_Import_paths, v_Include_paths, v_Library_paths :: IORef [String]
381 GLOBAL_VAR(v_Import_paths,  ["."], [String])
382 GLOBAL_VAR(v_Include_paths, ["."], [String])
383 GLOBAL_VAR(v_Library_paths, [],  [String])
384
385 GLOBAL_VAR(v_Cmdline_libraries,   [], [String])
386
387 #ifdef darwin_TARGET_OS
388 GLOBAL_VAR(v_Framework_paths, [], [String])
389 GLOBAL_VAR(v_Cmdline_frameworks, [], [String])
390 #endif
391
392 addToDirList :: IORef [String] -> String -> IO ()
393 addToDirList ref path
394   = do paths           <- readIORef ref
395        shiny_new_ones  <- splitUp path
396        writeIORef ref (paths ++ filter notNull shiny_new_ones)
397                 -- empty paths are ignored: there might be a trailing
398                 -- ':' in the initial list, for example.  Empty paths can
399                 -- cause confusion when they are translated into -I options
400                 -- for passing to gcc.
401   where
402     splitUp ::String -> IO [String]
403 #ifdef mingw32_TARGET_OS
404      -- 'hybrid' support for DOS-style paths in directory lists.
405      -- 
406      -- That is, if "foo:bar:baz" is used, this interpreted as
407      -- consisting of three entries, 'foo', 'bar', 'baz'.
408      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
409      -- as four elts, "c:/foo", "c:\\foo", "x", and "/bar" --
410      -- *provided* c:/foo exists and x:/bar doesn't.
411      --
412      -- Notice that no attempt is made to fully replace the 'standard'
413      -- split marker ':' with the Windows / DOS one, ';'. The reason being
414      -- that this will cause too much breakage for users & ':' will
415      -- work fine even with DOS paths, if you're not insisting on being silly.
416      -- So, use either.
417     splitUp []         = return []
418     splitUp (x:':':div:xs) 
419       | div `elem` dir_markers = do
420           let (p,rs) = findNextPath xs
421           ps  <- splitUp rs
422            {-
423              Consult the file system to check the interpretation
424              of (x:':':div:p) -- this is arguably excessive, we
425              could skip this test & just say that it is a valid
426              dir path.
427            -}
428           flg <- doesDirectoryExist (x:':':div:p)
429           if flg then
430              return ((x:':':div:p):ps)
431            else
432              return ([x]:(div:p):ps)
433     splitUp xs = do
434       let (p,rs) = findNextPath xs
435       ps <- splitUp rs
436       return (cons p ps)
437     
438     cons "" xs = xs
439     cons x  xs = x:xs
440
441     -- will be called either when we've consumed nought or the "<Drive>:/" part of
442     -- a DOS path, so splitting is just a Q of finding the next split marker.
443     findNextPath xs = 
444         case break (`elem` split_markers) xs of
445            (p, d:ds) -> (p, ds)
446            (p, xs)   -> (p, xs)
447
448     split_markers :: [Char]
449     split_markers = [':', ';']
450
451     dir_markers :: [Char]
452     dir_markers = ['/', '\\']
453
454 #else
455     splitUp xs = return (split split_marker xs)
456 #endif
457
458 GLOBAL_VAR(v_HCHeader, "", String)
459
460 -----------------------------------------------------------------------------
461 -- Packages
462
463 ------------------------
464 -- The PackageConfigMap is read in from the configuration file
465 -- It doesn't change during a run
466 GLOBAL_VAR(v_Package_details, emptyPkgMap, PackageConfigMap)
467
468 readPackageConf :: String -> IO ()
469 readPackageConf conf_file = do
470   proto_pkg_configs <- loadPackageConfig conf_file
471   top_dir           <- getTopDir
472   old_pkg_map       <- readIORef v_Package_details
473
474   let pkg_configs = mungePackagePaths top_dir proto_pkg_configs
475       new_pkg_map = extendPkgMap old_pkg_map pkg_configs
476    
477   writeIORef v_Package_details new_pkg_map
478
479 getPackageConfigMap :: IO PackageConfigMap
480 getPackageConfigMap = readIORef v_Package_details
481
482
483 ------------------------
484 -- The package list reflects what was given as command-line options,
485 --      plus their dependent packages.
486 -- It is maintained in dependency order;
487 --      earlier ones depend on later ones, but not vice versa
488 GLOBAL_VAR(v_Packages, initPackageList, [PackageName])
489
490 getPackages :: IO [PackageName]
491 getPackages = readIORef v_Packages
492
493 initPackageList = [haskell98Package,
494                    preludePackage,
495                    rtsPackage]
496
497 addPackage :: String -> IO ()
498 addPackage package
499   = do  { pkg_details <- getPackageConfigMap
500         ; ps  <- readIORef v_Packages
501         ; ps' <- add_package pkg_details ps (mkPackageName package)
502                 -- Throws an exception if it fails
503         ; writeIORef v_Packages ps' }
504
505 add_package :: PackageConfigMap -> [PackageName]
506             -> PackageName -> IO [PackageName]
507 add_package pkg_details ps p    
508   | p `elem` ps -- Check if we've already added this package
509   = return ps
510   | Just details <- lookupPkg pkg_details p
511   = do  {       -- Add the package's dependents first
512           ps' <- foldM  (add_package pkg_details) ps 
513                         (packageDependents details)
514         ; return (p : ps') }
515
516   | otherwise
517   = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString p))
518
519 getPackageImportPath   :: IO [String]
520 getPackageImportPath = do
521   ps <- getPackageInfo
522   return (nub (filter notNull (concatMap import_dirs ps)))
523
524 getPackageIncludePath   :: IO [String]
525 getPackageIncludePath = do
526   ps <- getPackageInfo
527   return (nub (filter notNull (concatMap include_dirs ps)))
528
529         -- includes are in reverse dependency order (i.e. rts first)
530 getPackageCIncludes   :: IO [String]
531 getPackageCIncludes = do
532   ps <- getPackageInfo
533   return (reverse (nub (filter notNull (concatMap c_includes ps))))
534
535 getPackageLibraryPath  :: IO [String]
536 getPackageLibraryPath = do
537   ps <- getPackageInfo
538   return (nub (filter notNull (concatMap library_dirs ps)))
539
540 getPackageLibraries    :: IO [String]
541 getPackageLibraries = do
542   ps <- getPackageInfo
543   tag <- readIORef v_Build_tag
544   let suffix = if null tag then "" else '_':tag
545   return (concat (
546         map (\p -> map (++suffix) (hACK (hs_libraries p)) ++ extra_libraries p) ps
547      ))
548   where
549      -- This is a totally horrible (temporary) hack, for Win32.  Problem is
550      -- that package.conf for Win32 says that the main prelude lib is 
551      -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
552      -- in the GNU linker (PEi386 backend). However, we still only
553      -- have HSbase.a for static linking, not HSbase{1,2,3}.a
554      -- getPackageLibraries is called to find the .a's to add to the static
555      -- link line.  On Win32, this hACK detects HSbase{1,2,3} and 
556      -- replaces them with HSbase, so static linking still works.
557      -- Libraries needed for dynamic (GHCi) linking are discovered via
558      -- different route (in InteractiveUI.linkPackage).
559      -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
560      -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
561      -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
562      -- KAA 29 Mar  02: Same appalling hack for HSobjectio[1,2,3,4]
563      hACK libs
564 #      if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
565        = libs
566 #      else
567        = if   "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
568          then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
569          else
570          if   "HSwin321" `elem` libs && "HSwin322" `elem` libs
571          then "HSwin32" : filter (not.(isPrefixOf "HSwin32")) libs
572          else 
573          if   "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
574          then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
575          else 
576          libs
577 #      endif
578
579 getPackageExtraGhcOpts :: IO [String]
580 getPackageExtraGhcOpts = do
581   ps <- getPackageInfo
582   return (concatMap extra_ghc_opts ps)
583
584 getPackageExtraCcOpts  :: IO [String]
585 getPackageExtraCcOpts = do
586   ps <- getPackageInfo
587   return (concatMap extra_cc_opts ps)
588
589 getPackageExtraLdOpts  :: IO [String]
590 getPackageExtraLdOpts = do
591   ps <- getPackageInfo
592   return (concatMap extra_ld_opts ps)
593
594 #ifdef darwin_TARGET_OS
595 getPackageFrameworkPath  :: IO [String]
596 getPackageFrameworkPath = do
597   ps <- getPackageInfo
598   return (nub (filter notNull (concatMap framework_dirs ps)))
599
600 getPackageFrameworks  :: IO [String]
601 getPackageFrameworks = do
602   ps <- getPackageInfo
603   return (concatMap extra_frameworks ps)
604 #endif
605
606 getPackageInfo :: IO [PackageConfig]
607 getPackageInfo = do ps <- getPackages  
608                     getPackageDetails ps
609
610 getPackageDetails :: [PackageName] -> IO [PackageConfig]
611 getPackageDetails ps = do
612   pkg_details <- getPackageConfigMap
613   return [ pkg | Just pkg <- map (lookupPkg pkg_details) ps ]
614
615
616 -----------------------------------------------------------------------------
617 -- Ways
618
619 -- The central concept of a "way" is that all objects in a given
620 -- program must be compiled in the same "way".  Certain options change
621 -- parameters of the virtual machine, eg. profiling adds an extra word
622 -- to the object header, so profiling objects cannot be linked with
623 -- non-profiling objects.
624
625 -- After parsing the command-line options, we determine which "way" we
626 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
627
628 -- We then find the "build-tag" associated with this way, and this
629 -- becomes the suffix used to find .hi files and libraries used in
630 -- this compilation.
631
632 GLOBAL_VAR(v_Build_tag, "", String)
633
634 data WayName
635   = WayProf
636   | WayUnreg
637   | WayTicky
638   | WayPar
639   | WayGran
640   | WaySMP
641   | WayNDP
642   | WayDebug
643   | WayUser_a
644   | WayUser_b
645   | WayUser_c
646   | WayUser_d
647   | WayUser_e
648   | WayUser_f
649   | WayUser_g
650   | WayUser_h
651   | WayUser_i
652   | WayUser_j
653   | WayUser_k
654   | WayUser_l
655   | WayUser_m
656   | WayUser_n
657   | WayUser_o
658   | WayUser_A
659   | WayUser_B
660   deriving (Eq,Ord)
661
662 GLOBAL_VAR(v_Ways, [] ,[WayName])
663
664 allowed_combination way = way `elem` combs
665   where  -- the sub-lists must be ordered according to WayName, 
666          -- because findBuildTag sorts them
667     combs                = [ [WayProf, WayUnreg], 
668                              [WayProf, WaySMP]  ,
669                              [WayProf, WayNDP]  ]
670
671 findBuildTag :: IO [String]  -- new options
672 findBuildTag = do
673   way_names <- readIORef v_Ways
674   case sort way_names of
675      []  -> do  -- writeIORef v_Build_tag ""
676                 return []
677
678      [w] -> do let details = lkupWay w
679                writeIORef v_Build_tag (wayTag details)
680                return (wayOpts details)
681
682      ws  -> if not (allowed_combination ws)
683                 then throwDyn (CmdLineError $
684                                 "combination not supported: "  ++
685                                 foldr1 (\a b -> a ++ '/':b) 
686                                 (map (wayName . lkupWay) ws))
687                 else let stuff = map lkupWay ws
688                          tag   = concat (map wayTag stuff)
689                          flags = map wayOpts stuff
690                      in do
691                      writeIORef v_Build_tag tag
692                      return (concat flags)
693
694 lkupWay w = 
695    case lookup w way_details of
696         Nothing -> error "findBuildTag"
697         Just details -> details
698
699 data Way = Way {
700   wayTag   :: String,
701   wayName  :: String,
702   wayOpts  :: [String]
703   }
704
705 way_details :: [ (WayName, Way) ]
706 way_details =
707   [ (WayProf, Way  "p" "Profiling"  
708         [ "-fscc-profiling"
709         , "-DPROFILING"
710         , "-optc-DPROFILING"
711         , "-fvia-C" ]),
712
713     (WayTicky, Way  "t" "Ticky-ticky Profiling"  
714         [ "-fticky-ticky"
715         , "-DTICKY_TICKY"
716         , "-optc-DTICKY_TICKY"
717         , "-fvia-C" ]),
718
719     (WayUnreg, Way  "u" "Unregisterised" 
720         unregFlags ),
721
722     -- optl's below to tell linker where to find the PVM library -- HWL
723     (WayPar, Way  "mp" "Parallel" 
724         [ "-fparallel"
725         , "-D__PARALLEL_HASKELL__"
726         , "-optc-DPAR"
727         , "-package concurrent"
728         , "-optc-w"
729         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
730         , "-optl-lpvm3"
731         , "-optl-lgpvm3"
732         , "-fvia-C" ]),
733
734     -- at the moment we only change the RTS and could share compiler and libs!
735     (WayPar, Way  "mt" "Parallel ticky profiling" 
736         [ "-fparallel"
737         , "-D__PARALLEL_HASKELL__"
738         , "-optc-DPAR"
739         , "-optc-DPAR_TICKY"
740         , "-package concurrent"
741         , "-optc-w"
742         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
743         , "-optl-lpvm3"
744         , "-optl-lgpvm3"
745         , "-fvia-C" ]),
746
747     (WayPar, Way  "md" "Distributed" 
748         [ "-fparallel"
749         , "-D__PARALLEL_HASKELL__"
750         , "-D__DISTRIBUTED_HASKELL__"
751         , "-optc-DPAR"
752         , "-optc-DDIST"
753         , "-package concurrent"
754         , "-optc-w"
755         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
756         , "-optl-lpvm3"
757         , "-optl-lgpvm3"
758         , "-fvia-C" ]),
759
760     (WayGran, Way  "mg" "GranSim" 
761         [ "-fgransim"
762         , "-D__GRANSIM__"
763         , "-optc-DGRAN"
764         , "-package concurrent"
765         , "-fvia-C" ]),
766
767     (WaySMP, Way  "s" "SMP"
768         [ "-fsmp"
769         , "-optc-pthread"
770         , "-optl-pthread"
771         , "-optc-DSMP"
772         , "-fvia-C" ]),
773
774     (WayNDP, Way  "ndp" "Nested data parallelism"
775         [ "-fparr"
776         , "-fflatten"]),
777
778     (WayUser_a,  Way  "a"  "User way 'a'"  ["$WAY_a_REAL_OPTS"]),       
779     (WayUser_b,  Way  "b"  "User way 'b'"  ["$WAY_b_REAL_OPTS"]),       
780     (WayUser_c,  Way  "c"  "User way 'c'"  ["$WAY_c_REAL_OPTS"]),       
781     (WayUser_d,  Way  "d"  "User way 'd'"  ["$WAY_d_REAL_OPTS"]),       
782     (WayUser_e,  Way  "e"  "User way 'e'"  ["$WAY_e_REAL_OPTS"]),       
783     (WayUser_f,  Way  "f"  "User way 'f'"  ["$WAY_f_REAL_OPTS"]),       
784     (WayUser_g,  Way  "g"  "User way 'g'"  ["$WAY_g_REAL_OPTS"]),       
785     (WayUser_h,  Way  "h"  "User way 'h'"  ["$WAY_h_REAL_OPTS"]),       
786     (WayUser_i,  Way  "i"  "User way 'i'"  ["$WAY_i_REAL_OPTS"]),       
787     (WayUser_j,  Way  "j"  "User way 'j'"  ["$WAY_j_REAL_OPTS"]),       
788     (WayUser_k,  Way  "k"  "User way 'k'"  ["$WAY_k_REAL_OPTS"]),       
789     (WayUser_l,  Way  "l"  "User way 'l'"  ["$WAY_l_REAL_OPTS"]),       
790     (WayUser_m,  Way  "m"  "User way 'm'"  ["$WAY_m_REAL_OPTS"]),       
791     (WayUser_n,  Way  "n"  "User way 'n'"  ["$WAY_n_REAL_OPTS"]),       
792     (WayUser_o,  Way  "o"  "User way 'o'"  ["$WAY_o_REAL_OPTS"]),       
793     (WayUser_A,  Way  "A"  "User way 'A'"  ["$WAY_A_REAL_OPTS"]),       
794     (WayUser_B,  Way  "B"  "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
795   ]
796
797 unregFlags = 
798    [ "-optc-DNO_REGS"
799    , "-optc-DUSE_MINIINTERPRETER"
800    , "-fno-asm-mangling"
801    , "-funregisterised"
802    , "-fvia-C" ]
803
804 -----------------------------------------------------------------------------
805 -- Options for particular phases
806
807 GLOBAL_VAR(v_Opt_dep,    [], [String])
808 GLOBAL_VAR(v_Anti_opt_C, [], [String])
809 GLOBAL_VAR(v_Opt_C,      [], [String])
810 GLOBAL_VAR(v_Opt_l,      [], [String])
811 GLOBAL_VAR(v_Opt_dll,    [], [String])
812
813 getStaticOpts :: IORef [String] -> IO [String]
814 getStaticOpts ref = readIORef ref >>= return . reverse