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