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