[project @ 2000-06-13 16:07:20 by simonmar]
authorsimonmar <unknown>
Tue, 13 Jun 2000 16:07:21 +0000 (16:07 +0000)
committersimonmar <unknown>
Tue, 13 Jun 2000 16:07:21 +0000 (16:07 +0000)
New Driver
==========

Most things work now, so I'm committing this for a shake down.
Doubtless there'll be some breakage but things should be back to
normal by the end of the week.

NOTE: GHC 4.06 won't work to build this driver at the moment, due to a
bug in its parser.  I'll commit a workaround shortly.

There are several improvements here:

- the driver is written in Haskell, so is allegedly
  more maintainable than the previous one.  It's a bit shorter,
  at any rate.

- the package system has been generalised, so that eg.
  the RTS is a package, as is GMP and the prelude.  Packages
  are now configured via a configuration file, package.conf.
  Two versions of package.conf are automatically generated by
  PackageSrc.hs, one for ghc-inplace and one for the installed ghc.

- So that we only have to build the driver once, there's some
  special hackery to deal with locations of utilities, and
  other configuration stuff:

  ghc now has a -B option, which is used in a similar way
  to gcc's.  eg.

ghc -B/home/blah/fptools

  will run ghc in-place in the specified fptools tree, using
  /home/blah/fptools/ghc/utils/mkdependHS to find mkdependHS
  for example.  ghc-inplace is now a small shell script that
  simply invokes the above.  Whereas

ghc -B/usr/local/lib/ghc-4.07

  also works, for an installed copy of ghc in
  /usr/local/lib/ghc-4.07.

- the mangler, object splitter and GC stats gatherer are separate
  scripts in subdirectories of ghc/driver.  ghc-asm.lprl and
  ghc-split.lprl have been copied in the CVS repository to maintain
  the history (fingers crossed; I've never done this before)

Other notes:

- Java support isn't there yet.  Andy: don't update for the time
  being until I can sort this.

- Windows support is also broken, but will be fixed in due course.

16 files changed:
ghc/driver/Main.hs [new file with mode: 0644]
ghc/driver/Makefile
ghc/driver/Package.hs [new file with mode: 0644]
ghc/driver/PackageSrc.hs [new file with mode: 0644]
ghc/driver/ghc-asm.lprl [deleted file]
ghc/driver/ghc-consist.lprl [deleted file]
ghc/driver/ghc-split.lprl [deleted file]
ghc/driver/ghc.lprl [deleted file]
ghc/driver/mangler/Makefile [new file with mode: 0644]
ghc/driver/mangler/ghc-asm.lprl
ghc/driver/prefix.txt [deleted file]
ghc/driver/split/Makefile [new file with mode: 0644]
ghc/driver/split/ghc-split.lprl
ghc/driver/stats/Makefile [new file with mode: 0644]
ghc/driver/stats/ghc-stats.lprl [new file with mode: 0644]
ghc/mk/paths.mk

diff --git a/ghc/driver/Main.hs b/ghc/driver/Main.hs
new file mode 100644 (file)
index 0000000..0ccbfc6
--- /dev/null
@@ -0,0 +1,1928 @@
+-----------------------------------------------------------------------------
+-- GHC Driver program
+--
+-- (c) Simon Marlow 2000
+--
+-----------------------------------------------------------------------------
+
+module Main (main) where
+
+import Package
+import Config
+
+import RegexString
+import Concurrent
+import Posix
+import IOExts
+import Exception
+import Dynamic
+
+import IO
+import Array
+import List
+import System
+import Maybe
+import Char
+
+#define GLOBAL_VAR(name,value,ty)  \
+name = global (value) :: IORef (ty); \
+{-# NOINLINE name #-}
+
+-----------------------------------------------------------------------------
+-- ToDo:
+
+-- test:
+-- stub files
+
+-- time commands when run with -v
+-- split marker
+-- mkDLL
+-- java generation
+-- user ways
+-- Win32 support
+-- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
+
+-----------------------------------------------------------------------------
+-- Differences vs. old driver:
+
+-- consistency checking removed (may do this properly later)
+-- removed -noC
+-- no hi diffs (could be added later)
+-- no -Ofile
+
+-----------------------------------------------------------------------------
+-- non-configured things
+
+_Haskell1Version = "5" -- i.e., Haskell 98
+
+-----------------------------------------------------------------------------
+-- Usage Message
+
+short_usage = do
+  hPutStr stderr "\nUsage: For basic information, try the `-help' option.\n"
+  exitWith ExitSuccess
+   
+long_usage = do
+  let usage_dir = findFile "ghc-usage.txt" (_GHC_DRIVER_DIR++"/ghc-usage.txt")
+  usage <- readFile (usage_dir++"/ghc-usage.txt")
+  dump usage
+  exitWith ExitSuccess
+  where
+     dump "" = return ()
+     dump ('$':'$':s) = hPutStr stderr get_prog_name >> dump s
+     dump (c:s) = hPutChar stderr c >> dump s
+
+-----------------------------------------------------------------------------
+-- Phases
+
+{-
+Phase of the           | Suffix saying | Flag saying   | (suffix of)
+compilation system     | ``start here''| ``stop after''| output file
+
+literate pre-processor | .lhs          | -             | -
+C pre-processor (opt.) | -             | -E            | -
+Haskell compiler       | .hs           | -C, -S        | .hc, .s
+C compiler (opt.)      | .hc or .c     | -S            | .s
+assembler              | .s  or .S     | -c            | .o
+linker                 | other         | -             | a.out
+-}
+
+data Phase 
+       = MkDependHS    -- haskell dependency generation
+       | Unlit
+       | Cpp
+       | Hsc
+       | Cc
+       | HCc           -- Haskellised C (as opposed to vanilla C) compilation
+       | Mangle        -- assembly mangling, now done by a separate script.
+       | SplitMangle   -- after mangler if splitting
+       | As
+       | Ln 
+  deriving (Eq,Ord,Enum,Ix,Show,Bounded)
+
+initial_phase = Unlit
+
+-----------------------------------------------------------------------------
+-- Errors
+
+data BarfKind
+  = UnknownFileType String
+  | UnknownFlag String
+  | AmbiguousPhase
+  | MultipleSrcsOneOutput
+  | UnknownPackage String
+  | WayCombinationNotSupported [WayName]
+  | PhaseFailed String ExitCode
+  | Interrupted
+  deriving Eq
+
+GLOBAL_VAR(prog_name, "ghc", String)
+
+get_prog_name = unsafePerformIO (readIORef prog_name) -- urk!
+
+instance Show BarfKind where
+  showsPrec _ e 
+       = showString get_prog_name . showString ": " . showBarf e
+
+showBarf AmbiguousPhase
+   = showString "only one of the flags -M, -E, -C, -S, -c is allowed"
+showBarf (UnknownFileType s)
+   = showString "unknown file type, and linking not done: " . showString s
+showBarf (UnknownFlag s)
+   = showString "unrecognised flag: " . showString s
+showBarf MultipleSrcsOneOutput
+   = showString "can't apply -o option to multiple source files"
+showBarf (UnknownPackage s)
+   = showString "unknown package name: " . showString s
+showBarf (WayCombinationNotSupported ws)
+   = showString "combination not supported: " 
+   . foldr1 (\a b -> a . showChar '/' . b) 
+       (map (showString . wayName . lkupWay) ws)
+
+barfKindTc = mkTyCon "BarfKind"
+
+instance Typeable BarfKind where
+  typeOf _ = mkAppTy barfKindTc []
+
+-----------------------------------------------------------------------------
+-- Temporary files
+
+GLOBAL_VAR(files_to_clean, [], [String])
+
+cleanTempFiles :: IO ()
+cleanTempFiles = do
+  fs <- readIORef files_to_clean
+  verb <- readIORef verbose
+
+  let blowAway f =
+          (do  on verb (hPutStrLn stderr ("removing: " ++ f))
+               if '*' `elem` f then system ("rm -f " ++ f) >> return ()
+                               else removeLink f)
+           `catchAllIO`
+          (\e -> on verb (hPutStrLn stderr 
+                               ("warning: can't remove tmp file" ++ f)))
+  mapM_ blowAway fs
+
+-----------------------------------------------------------------------------
+-- Which phase to stop at
+
+GLOBAL_VAR(stop_after, Ln, Phase)
+
+end_phase_flag :: String -> Maybe Phase
+end_phase_flag "-M" = Just MkDependHS
+end_phase_flag "-E" = Just Cpp
+end_phase_flag "-C" = Just Hsc
+end_phase_flag "-S" = Just Mangle
+end_phase_flag "-c" = Just As
+end_phase_flag _    = Nothing
+
+getStopAfter :: [String]
+        -> IO ( [String]   -- rest of command line
+              , Phase      -- stop after phase
+              , Bool       -- do linking?
+              )
+getStopAfter flags 
+  = case my_partition end_phase_flag flags of
+       ([]   , rest) -> return (rest, As,  True)
+       ([one], rest) -> return (rest, one, False)
+       (_    , rest) -> throwDyn AmbiguousPhase
+
+-----------------------------------------------------------------------------
+-- Global compilation flags
+
+       -- Cpp-related flags
+GLOBAL_VAR(cpp_flag, False, Bool)
+hs_source_cpp_opts = global
+       [ "-D__HASKELL1__="++_Haskell1Version
+       , "-D__GLASGOW_HASKELL__="++_ProjectVersionInt                          
+       , "-D__HASKELL98__"
+       , "-D__CONCURRENT_HASKELL__"
+       ]
+
+       -- Keep output from intermediate phases
+GLOBAL_VAR(keep_hi_diffs,      False,          Bool)
+GLOBAL_VAR(keep_hc_files,      False,          Bool)
+GLOBAL_VAR(keep_s_files,       False,          Bool)
+GLOBAL_VAR(keep_raw_s_files,   False,          Bool)
+
+       -- Compiler RTS options
+GLOBAL_VAR(specific_heap_size,  6 * 1000 * 1000, Integer)
+GLOBAL_VAR(specific_stack_size, 1000 * 1000,     Integer)
+GLOBAL_VAR(scale_sizes_by,      1.0,            Double)
+
+       -- Verbose
+GLOBAL_VAR(verbose, False, Bool)
+is_verbose = do v <- readIORef verbose; if v then return "-v" else return ""
+
+       -- Misc
+GLOBAL_VAR(dry_run,            False,          Bool)
+GLOBAL_VAR(recomp,             True,           Bool)
+GLOBAL_VAR(tmp_prefix,                 _TMPDIR,        String)
+GLOBAL_VAR(stolen_x86_regs,    4,              Int)
+GLOBAL_VAR(static,             True,           Bool)  -- ToDo: not for mingw32
+GLOBAL_VAR(collect_ghc_timing,         False,          Bool)
+GLOBAL_VAR(do_asm_mangling,    True,           Bool)
+
+-----------------------------------------------------------------------------
+-- Splitting object files (for libraries)
+
+GLOBAL_VAR(split_object_files, False,          Bool)
+GLOBAL_VAR(split_prefix,       "",             String)
+GLOBAL_VAR(n_split_files,      0,              Int)
+       
+can_split :: Bool
+can_split =  prefixMatch "i386" _TARGETPLATFORM
+         || prefixMatch "alpha" _TARGETPLATFORM
+         || prefixMatch "hppa" _TARGETPLATFORM
+         || prefixMatch "m68k" _TARGETPLATFORM
+         || prefixMatch "mips" _TARGETPLATFORM
+         || prefixMatch "powerpc" _TARGETPLATFORM
+         || prefixMatch "rs6000" _TARGETPLATFORM
+         || prefixMatch "sparc" _TARGETPLATFORM
+
+-----------------------------------------------------------------------------
+-- Compiler output options
+
+data HscLang
+  = HscC
+  | HscAsm
+  | HscJava
+
+GLOBAL_VAR(hsc_lang, if _GhcWithNativeCodeGen == "YES" && 
+                        prefixMatch "i386" _TARGETPLATFORM
+                       then  HscAsm
+                       else  HscC, 
+          HscLang)
+
+GLOBAL_VAR(output_dir,  Nothing, Maybe String)
+GLOBAL_VAR(output_suf,  Nothing, Maybe String)
+GLOBAL_VAR(output_file, Nothing, Maybe String)
+GLOBAL_VAR(output_hi,   Nothing, Maybe String)
+
+GLOBAL_VAR(ld_inputs,  [],      [String])
+
+odir_ify :: String -> IO String
+odir_ify f = do
+  odir_opt <- readIORef output_dir
+  case odir_opt of
+       Nothing -> return f
+       Just d  -> return (newdir f d)
+
+osuf_ify :: String -> IO String
+osuf_ify f = do
+  osuf_opt <- readIORef output_suf
+  case osuf_opt of
+       Nothing -> return f
+       Just s  -> return (newsuf f s)
+
+-----------------------------------------------------------------------------
+-- Hi Files
+
+GLOBAL_VAR(produceHi,          True,   Bool)
+GLOBAL_VAR(hi_on_stdout,       False,  Bool)
+GLOBAL_VAR(hi_with,            "",     String)
+GLOBAL_VAR(hi_suf,             "hi",   String)
+
+data HiDiffFlag = NormalHiDiffs | UsageHiDiffs | NoHiDiffs
+GLOBAL_VAR(hi_diffs, NoHiDiffs, HiDiffFlag)
+
+-----------------------------------------------------------------------------
+-- Warnings & sanity checking
+
+-- Warning packages that are controlled by -W and -Wall.  The 'standard'
+-- warnings that you get all the time are
+--        
+--        -fwarn-overlapping-patterns
+--        -fwarn-missing-methods
+--        -fwarn-missing-fields
+--        -fwarn-deprecations
+--        -fwarn-duplicate-exports
+-- 
+-- these are turned off by -Wnot.
+
+standardWarnings  = [ "-fwarn-overlapping-patterns"
+                   , "-fwarn-missing-methods"
+                   , "-fwarn-missing-fields"
+                   , "-fwarn-deprecations"
+                   , "-fwarn-duplicate-exports"
+                   ]
+minusWOpts       = standardWarnings ++ 
+                   [ "-fwarn-unused-binds"
+                   , "-fwarn-unused-matches"
+                   , "-fwarn-incomplete-patterns"
+                   , "-fwarn-unused-imports"
+                   ]
+minusWallOpts    = minusWOpts ++
+                   [ "-fwarn-type-defaults"
+                   , "-fwarn-name-shadowing"
+                   , "-fwarn-missing-signatures"
+                   ]
+
+data WarningState = W_default | W_ | W_all | W_not
+
+GLOBAL_VAR(warning_opt, W_default, WarningState)
+
+-----------------------------------------------------------------------------
+-- Compiler optimisation options
+
+GLOBAL_VAR(opt_level, 0, Int)
+
+setOptLevel :: String -> IO ()
+setOptLevel ""             = do { writeIORef opt_level 1; go_via_C }
+setOptLevel "not"          = writeIORef opt_level 0
+setOptLevel [c] | isDigit c = do
+   let level = ord c - ord '0'
+   writeIORef opt_level level
+   on (level >= 1) go_via_C
+setOptLevel s = throwDyn (UnknownFlag ("-O"++s))
+
+go_via_C = do
+   l <- readIORef hsc_lang
+   case l of { HscAsm -> writeIORef hsc_lang HscC; 
+              _other -> return () }
+
+GLOBAL_VAR(opt_minus_o2_for_C, False, Bool)
+
+GLOBAL_VAR(opt_MaxSimplifierIterations, 4, Int)
+GLOBAL_VAR(opt_StgStats,    False, Bool)
+GLOBAL_VAR(opt_UsageSPInf,  False, Bool)  -- Off by default
+
+hsc_minusO2_flags = hsc_minusO_flags   -- for now
+
+hsc_minusNoO_flags = do
+  iter        <- readIORef opt_MaxSimplifierIterations
+  return [ 
+       "-fignore-interface-pragmas",
+       "-fomit-interface-pragmas",
+       "-fsimplify",
+           "[",
+               "-fmax-simplifier-iterations" ++ show iter,
+           "]"
+       ]
+
+hsc_minusO_flags = do
+  iter       <- readIORef opt_MaxSimplifierIterations
+  usageSP    <- readIORef opt_UsageSPInf
+  stgstats   <- readIORef opt_StgStats
+
+  return [ 
+       "-ffoldr-build-on",
+
+        "-fdo-eta-reduction",
+       "-fdo-lambda-eta-expansion",
+       "-fcase-of-case",
+       "-fcase-merge",
+       "-flet-to-case",
+
+       -- initial simplify: mk specialiser happy: minimum effort please
+
+       "-fsimplify",
+         "[", 
+               "-finline-phase0",
+                       -- Don't inline anything till full laziness has bitten
+                       -- In particular, inlining wrappers inhibits floating
+                       -- e.g. ...(case f x of ...)...
+                       --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
+                       --  ==> ...(case x of I# x# -> case fw x# of ...)...
+                       -- and now the redex (f x) isn't floatable any more
+
+               "-fno-rules",
+                       -- Similarly, don't apply any rules until after full 
+                       -- laziness.  Notably, list fusion can prevent floating.
+
+               "-fno-case-of-case",
+                       -- Don't do case-of-case transformations.
+                       -- This makes full laziness work better
+
+               "-fmax-simplifier-iterations2",
+         "]",
+
+       -- Specialisation is best done before full laziness
+       -- so that overloaded functions have all their dictionary lambdas manifest
+       "-fspecialise",
+
+       "-ffloat-outwards",
+       "-ffloat-inwards",
+
+       "-fsimplify",
+         "[", 
+               "-finline-phase1",
+               -- Want to run with inline phase 1 after the specialiser to give
+               -- maximum chance for fusion to work before we inline build/augment
+               -- in phase 2.  This made a difference in 'ansi' where an 
+               -- overloaded function wasn't inlined till too late.
+               "-fmax-simplifier-iterations" ++ show iter,
+         "]",
+
+       -- infer usage information here in case we need it later.
+        -- (add more of these where you need them --KSW 1999-04)
+        if usageSP then "-fusagesp" else "",
+
+       "-fsimplify",
+         "[", 
+               -- Need inline-phase2 here so that build/augment get 
+               -- inlined.  I found that spectral/hartel/genfft lost some useful
+               -- strictness in the function sumcode' if augment is not inlined
+               -- before strictness analysis runs
+
+               "-finline-phase2",
+               "-fmax-simplifier-iterations2",
+         "]",
+
+
+       "-fsimplify",
+         "[", 
+               "-fmax-simplifier-iterations2",
+               -- No -finline-phase: allow all Ids to be inlined now
+               -- This gets foldr inlined before strictness analysis
+         "]",
+
+       "-fstrictness",
+       "-fcpr-analyse",
+       "-fworker-wrapper",
+
+       "-fsimplify",
+         "[", 
+               "-fmax-simplifier-iterations" ++ show iter,
+               -- No -finline-phase: allow all Ids to be inlined now
+         "]",
+
+       "-ffloat-outwards",
+               -- nofib/spectral/hartel/wang doubles in speed if you
+               -- do full laziness late in the day.  It only happens
+               -- after fusion and other stuff, so the early pass doesn't
+               -- catch it.  For the record, the redex is 
+               --        f_el22 (f_el21 r_midblock)
+
+-- Leave out lambda lifting for now
+--       "-fsimplify", -- Tidy up results of full laziness
+--         "[", 
+--               "-fmax-simplifier-iterations2",
+--         "]",
+--       "-ffloat-outwards-full",      
+
+       -- We want CSE to follow the final full-laziness pass, because it may
+       -- succeed in commoning up things floated out by full laziness.
+       --
+       -- CSE must immediately follow a simplification pass, because it relies
+       -- on the no-shadowing invariant.  See comments at the top of CSE.lhs
+       -- So it must NOT follow float-inwards, which can give rise to shadowing,
+       -- even if its input doesn't have shadows.  Hence putting it between
+       -- the two passes.
+       "-fcse",        
+                       
+
+       "-ffloat-inwards",
+
+-- Case-liberation for -O2.  This should be after
+-- strictness analysis and the simplification which follows it.
+
+--       ( ($OptLevel != 2)
+--       ? ""
+--       : "-fliberate-case -fsimplify [ $Oopt_FB_Support -ffloat-lets-exposing-whnf -ffloat-primops-ok -fcase-of-case -fdo-case-elim -fcase-merge -fdo-lambda-eta-expansion -freuse-con -flet-to-case $Oopt_PedanticBottoms $Oopt_MaxSimplifierIterations $Oopt_ShowSimplifierProgress ]" ),
+--
+--       "-fliberate-case",
+
+       -- Final clean-up simplification:
+       "-fsimplify",
+         "[", 
+               "-fmax-simplifier-iterations" ++ show iter,
+               -- No -finline-phase: allow all Ids to be inlined now
+         "]"
+
+       ]
+
+-----------------------------------------------------------------------------
+-- Paths & Libraries
+
+split_marker = ':'   -- not configurable
+
+import_paths, include_paths, library_paths :: IORef [String]
+GLOBAL_VAR(import_paths,  ["."], [String])
+GLOBAL_VAR(include_paths, ["."], [String])
+GLOBAL_VAR(library_paths, [],   [String])
+
+GLOBAL_VAR(cmdline_libraries,   [], [String])
+GLOBAL_VAR(cmdline_hc_includes,        [], [String])
+
+augment_import_paths :: String -> IO ()
+augment_import_paths "" = writeIORef import_paths []
+augment_import_paths path
+  = do paths <- readIORef import_paths
+       writeIORef import_paths (paths ++ dirs)
+  where dirs = split split_marker path
+
+augment_include_paths :: String -> IO ()
+augment_include_paths path
+  = do paths <- readIORef include_paths
+       writeIORef include_paths (paths ++ split split_marker path)
+
+augment_library_paths :: String -> IO ()
+augment_library_paths path
+  = do paths <- readIORef library_paths
+       writeIORef library_paths (paths ++ split split_marker path)
+
+-----------------------------------------------------------------------------
+-- Packages
+
+-- package list is maintained in dependency order
+packages = global ["std", "rts", "gmp"] :: IORef [String]
+-- comma in value, so can't use macro, grrr
+{-# NOINLINE packages #-}
+
+addPackage :: String -> IO ()
+addPackage package
+  = do pkg_details <- readIORef package_details
+       case lookup package pkg_details of
+         Nothing -> throwDyn (UnknownPackage package)
+         Just details -> do
+           ps <- readIORef packages
+           if package `elem` ps 
+               then return ()
+               else do mapM_ addPackage (package_deps details)
+                       ps <- readIORef packages
+                       writeIORef packages (package:ps)
+
+getPackageImportPath   :: IO [String]
+getPackageImportPath = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (nub (concat (map import_dirs ps')))
+
+getPackageIncludePath   :: IO [String]
+getPackageIncludePath = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (nub (filter (not.null) (map include_dir ps')))
+
+       -- includes are in reverse dependency order (i.e. rts first)
+getPackageCIncludes   :: IO [String]
+getPackageCIncludes = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (reverse (nub (filter (not.null) (map c_include ps'))))
+
+getPackageLibraryPath  :: IO [String]
+getPackageLibraryPath = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (nub (concat (map library_dirs ps')))
+
+getPackageLibraries    :: IO [String]
+getPackageLibraries = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  tag <- readIORef build_tag
+  let suffix = if null tag then "" else '_':tag
+  return (concat (map libraries ps'))
+
+getPackageExtraGhcOpts :: IO [String]
+getPackageExtraGhcOpts = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (map extra_ghc_opts ps')
+
+getPackageExtraCcOpts  :: IO [String]
+getPackageExtraCcOpts = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (map extra_cc_opts ps')
+
+getPackageExtraLdOpts  :: IO [String]
+getPackageExtraLdOpts = do
+  ps <- readIORef packages
+  ps' <- getPackageDetails ps
+  return (map extra_ld_opts ps')
+
+getPackageDetails ps = do
+  pkg_details <- readIORef package_details
+  let getDetails p =  case lookup p pkg_details of
+                       Just details -> return details
+                       Nothing -> error "getPackageDetails"
+  mapM getDetails ps
+
+GLOBAL_VAR(package_details, (error "package_details"), [(String,Package)])
+
+-----------------------------------------------------------------------------
+-- Ways
+
+-- The central concept of a "way" is that all objects in a given
+-- program must be compiled in the same "way".  Certain options change
+-- parameters of the virtual machine, eg. profiling adds an extra word
+-- to the object header, so profiling objects cannot be linked with
+-- non-profiling objects.
+
+-- After parsing the command-line options, we determine which "way" we
+-- are building - this might be a combination way, eg. profiling+ticky-ticky.
+
+-- We then find the "build-tag" associated with this way, and this
+-- becomes the suffix used to find .hi files and libraries used in
+-- this compilation.
+
+GLOBAL_VAR(build_tag, "", String)
+
+data WayName
+  = WayProf
+  | WayUnreg
+  | WayTicky
+  | WayPar
+  | WayGran
+  | WaySMP
+  | WayDebug
+  | WayUser_a
+  | WayUser_b
+  | WayUser_c
+  | WayUser_d
+  | WayUser_e
+  | WayUser_f
+  | WayUser_g
+  | WayUser_h
+  | WayUser_i
+  | WayUser_j
+  | WayUser_k
+  | WayUser_l
+  | WayUser_m
+  | WayUser_n
+  | WayUser_o
+  | WayUser_A
+  | WayUser_B
+  deriving (Eq,Ord)
+
+GLOBAL_VAR(ways, [] ,[WayName])
+
+allowed_combinations = 
+   [  [WayProf,WayUnreg],
+      [WayProf,WaySMP]    -- works???
+   ]
+
+findBuildTag :: IO [String]  -- new options
+findBuildTag = do
+  way_names <- readIORef ways
+  case sort way_names of
+     []  -> do  writeIORef build_tag ""
+               return []
+
+     [w] -> do let details = lkupWay w
+              writeIORef build_tag (wayTag details)
+              return (wayOpts details)
+
+     ws  -> if  ws `notElem` allowed_combinations
+               then throwDyn (WayCombinationNotSupported ws)
+               else let stuff = map lkupWay ws
+                        tag   = concat (map wayTag stuff)
+                        flags = map wayOpts stuff
+                    in do
+                    writeIORef build_tag tag
+                    return (concat flags)
+
+lkupWay w = 
+   case lookup w way_details of
+       Nothing -> error "findBuildTag"
+       Just details -> details
+
+data Way = Way {
+  wayTag   :: String,
+  wayName  :: String,
+  wayOpts  :: [String]
+  }
+
+way_details :: [ (WayName, Way) ]
+way_details =
+  [ (WayProf, Way  "p" "Profiling"  
+       [ "-fscc-profiling"
+       , "-DPROFILING"
+       , "-optc-DPROFILING" ]),
+
+    (WayTicky, Way  "t" "Ticky-ticky Profiling"  
+       [ "-fticky-ticky"
+       , "-DTICKY_TICKY"
+       , "-optc-DTICKY_TICKY" ]),
+
+    (WayUnreg, Way  "u" "Unregisterised" 
+       [ "-optc-DNO_REGS"
+       , "-optc-DUSE_MINIINTERPRETER"
+       , "-fno-asm-mangling"
+       , "-funregisterised" ]),
+
+    (WayPar, Way  "mp" "Parallel" 
+       [ "-fstack-check"
+       , "-fparallel"
+       , "-D__PARALLEL_HASKELL__"
+       , "-optc-DPAR"
+       , "-package concurrent" ]),
+
+    (WayGran, Way  "mg" "Gransim" 
+       [ "-fstack-check"
+       , "-fgransim"
+       , "-D__GRANSIM__"
+       , "-optc-DGRAN"
+       , "-package concurrent" ]),
+
+    (WaySMP, Way  "s" "SMP"  
+       [ "-fsmp"
+       , "-optc-pthread"
+       , "-optl-pthread"
+       , "-optc-DSMP" ]),
+
+    (WayUser_a,  Way  "a"  "User way 'a'"  ["$WAY_a_REAL_OPTS"]),      
+    (WayUser_b,  Way  "b"  "User way 'b'"  ["$WAY_b_REAL_OPTS"]),      
+    (WayUser_c,  Way  "c"  "User way 'c'"  ["$WAY_c_REAL_OPTS"]),      
+    (WayUser_d,  Way  "d"  "User way 'd'"  ["$WAY_d_REAL_OPTS"]),      
+    (WayUser_e,  Way  "e"  "User way 'e'"  ["$WAY_e_REAL_OPTS"]),      
+    (WayUser_f,  Way  "f"  "User way 'f'"  ["$WAY_f_REAL_OPTS"]),      
+    (WayUser_g,  Way  "g"  "User way 'g'"  ["$WAY_g_REAL_OPTS"]),      
+    (WayUser_h,  Way  "h"  "User way 'h'"  ["$WAY_h_REAL_OPTS"]),      
+    (WayUser_i,  Way  "i"  "User way 'i'"  ["$WAY_i_REAL_OPTS"]),      
+    (WayUser_j,  Way  "j"  "User way 'j'"  ["$WAY_j_REAL_OPTS"]),      
+    (WayUser_k,  Way  "k"  "User way 'k'"  ["$WAY_k_REAL_OPTS"]),      
+    (WayUser_l,  Way  "l"  "User way 'l'"  ["$WAY_l_REAL_OPTS"]),      
+    (WayUser_m,  Way  "m"  "User way 'm'"  ["$WAY_m_REAL_OPTS"]),      
+    (WayUser_n,  Way  "n"  "User way 'n'"  ["$WAY_n_REAL_OPTS"]),      
+    (WayUser_o,  Way  "o"  "User way 'o'"  ["$WAY_o_REAL_OPTS"]),      
+    (WayUser_A,  Way  "A"  "User way 'A'"  ["$WAY_A_REAL_OPTS"]),      
+    (WayUser_B,  Way  "B"  "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
+  ]
+
+-----------------------------------------------------------------------------
+-- Programs for particular phases
+
+GLOBAL_VAR(pgm_dep, findFile "mkdependHS" _GHC_MKDEPENDHS, String)
+GLOBAL_VAR(pgm_L,   findFile "unlit"      _GHC_UNLIT,      String)
+GLOBAL_VAR(pgm_P,   findFile "hscpp"      _GHC_HSCPP,      String)
+GLOBAL_VAR(pgm_C,   findFile "hsc"        _GHC_HSC,        String)
+GLOBAL_VAR(pgm_c,   _GCC,                                 String)
+GLOBAL_VAR(pgm_m,   findFile "ghc-asm"    _GHC_MANGLER,    String)
+GLOBAL_VAR(pgm_s,   findFile "ghc-split"  _GHC_SPLIT,      String)
+GLOBAL_VAR(pgm_a,   _GCC,                                 String)
+GLOBAL_VAR(pgm_l,   _GCC,                                 String)
+
+-----------------------------------------------------------------------------
+-- Options for particular phases
+
+GLOBAL_VAR(opt_dep, [], [String])
+GLOBAL_VAR(opt_L, [], [String])
+GLOBAL_VAR(opt_P, [], [String])
+GLOBAL_VAR(opt_C, [], [String])
+GLOBAL_VAR(opt_Crts, [], [String])
+GLOBAL_VAR(opt_c, [], [String])
+GLOBAL_VAR(opt_a, [], [String])
+GLOBAL_VAR(opt_m, [], [String])
+GLOBAL_VAR(opt_l, [], [String])
+GLOBAL_VAR(opt_dll, [], [String])
+
+       -- we add to the options from the front, so we need to reverse the list
+getOpts :: IORef [String] -> IO [String]
+getOpts opts = readIORef opts >>= return . reverse
+
+GLOBAL_VAR(anti_opt_C, [], [String])
+
+-----------------------------------------------------------------------------
+-- Via-C compilation stuff
+
+-- flags returned are: ( all C compilations
+--                    , registerised HC compilations
+--                    )
+
+machdepCCOpts 
+   | prefixMatch "alpha"   _TARGETPLATFORM  
+       = return ( ["-static"], [] )
+
+   | prefixMatch "hppa"    _TARGETPLATFORM  
+        -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
+        -- (very nice, but too bad the HP /usr/include files don't agree.)
+       = return ( ["-static", "-D_HPUX_SOURCE"], [] )
+
+   | prefixMatch "m68k"    _TARGETPLATFORM
+      -- -fno-defer-pop : for the .hc files, we want all the pushing/
+      --    popping of args to routines to be explicit; if we let things
+      --    be deferred 'til after an STGJUMP, imminent death is certain!
+      --
+      -- -fomit-frame-pointer : *don't*
+      --     It's better to have a6 completely tied up being a frame pointer
+      --     rather than let GCC pick random things to do with it.
+      --     (If we want to steal a6, then we would try to do things
+      --     as on iX86, where we *do* steal the frame pointer [%ebp].)
+       = return ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
+
+   | prefixMatch "i386"    _TARGETPLATFORM  
+      -- -fno-defer-pop : basically the same game as for m68k
+      --
+      -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
+      --   the fp (%ebp) for our register maps.
+       = do n_regs <- readIORef stolen_x86_regs
+            sta    <- readIORef static
+            return ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else "" ],
+                     [ "-fno-defer-pop", "-fomit-frame-pointer",
+                       "-DSTOLEN_X86_REGS="++show n_regs ]
+                   )
+
+   | prefixMatch "mips"    _TARGETPLATFORM
+       = return ( ["static"], [] )
+
+   | prefixMatch "powerpc" _TARGETPLATFORM || prefixMatch "rs6000" _TARGETPLATFORM
+       = return ( ["static"], ["-finhibit-size-directive"] )
+
+   | otherwise
+       = return ( [], [] )
+
+-----------------------------------------------------------------------------
+-- Build the Hsc command line
+
+build_hsc_opts :: IO [String]
+build_hsc_opts = do
+  opt_C_ <- getOpts opt_C              -- misc hsc opts
+
+       -- warnings
+  warn_level <- readIORef warning_opt
+  let warn_opts =  case warn_level of
+                       W_default -> standardWarnings
+                       W_        -> minusWOpts
+                       W_all     -> minusWallOpts
+                       W_not     -> []
+
+       -- optimisation
+  minus_o <- readIORef opt_level
+  optimisation_opts <-
+        case minus_o of
+           0 -> hsc_minusNoO_flags
+           1 -> hsc_minusO_flags
+           2 -> hsc_minusO2_flags
+           -- ToDo: -Ofile
+       -- STG passes
+  ways_ <- readIORef ways
+  let stg_massage | WayProf `elem` ways_ =  "-fmassage-stg-for-profiling"
+                 | otherwise            = ""
+
+  stg_stats <- readIORef opt_StgStats
+  let stg_stats_flag | stg_stats = "-dstg-stats"
+                    | otherwise = ""
+
+  let stg_opts = [ stg_massage, stg_stats_flag, "-flet-no-escape" ]
+       -- let-no-escape always on for now
+
+  verb <- is_verbose
+  let hi_vers = "-fhi-version="++_ProjectVersionInt
+  static <- (do s <- readIORef static; if s then return "-static" else return "")
+
+  l <- readIORef hsc_lang
+  let lang = case l of
+               HscC    -> "-olang=C"
+               HscAsm  -> "-olang=asm"
+               HscJava -> "-olang=java"
+
+  -- get hi-file suffix
+  hisuf <- readIORef hi_suf
+
+  -- hi-suffix for packages depends on the build tag.
+  package_hisuf <-
+       do tag <- readIORef build_tag
+          if null tag
+               then return "hi"
+               else return (tag ++ "_hi")
+
+  import_dirs <- readIORef import_paths
+  package_import_dirs <- getPackageImportPath
+  
+  let hi_map = "-himap=" ++
+               makeHiMap import_dirs hisuf 
+                        package_import_dirs package_hisuf
+                        split_marker
+
+      hi_map_sep = "-himap-sep=" ++ [split_marker]
+
+  scale <- readIORef scale_sizes_by
+  heap  <- readIORef specific_heap_size
+  stack <- readIORef specific_stack_size
+  cmdline_rts_opts <- getOpts opt_Crts
+  let heap'  = truncate (fromIntegral heap  * scale) :: Integer
+      stack' = truncate (fromIntegral stack * scale) :: Integer
+      rts_opts = [ "+RTS", "-H"++show heap', "-K"++show stack' ]
+                ++ cmdline_rts_opts ++ [ "-RTS" ]
+
+  -- take into account -fno-* flags by removing the equivalent -f*
+  -- flag from our list.
+  anti_flags <- getOpts anti_opt_C
+  let basic_opts = opt_C_ ++ warn_opts ++ optimisation_opts ++ stg_opts
+      filtered_opts = filter (`notElem` anti_flags) basic_opts
+  
+  return 
+       (  
+       filtered_opts
+       -- ToDo: C stub files
+       ++ [ hi_vers, static, verb, lang, hi_map, hi_map_sep ]
+       ++ rts_opts
+       )
+
+makeHiMap 
+  (import_dirs         :: [String])
+  (hi_suffix           :: String)
+  (package_import_dirs :: [String])
+  (package_hi_suffix   :: String)   
+  (split_marker        :: Char)
+  = foldr (add_dir hi_suffix) 
+       (foldr (add_dir package_hi_suffix) "" package_import_dirs)
+       import_dirs
+  where
+     add_dir hisuf dir str = dir ++ "%." ++ hisuf ++ split_marker : str
+
+
+getOptionsFromSource 
+       :: String               -- input file
+       -> IO [String]          -- options, if any
+getOptionsFromSource file
+  = do h <- openFile file ReadMode
+       look h
+  where
+       look h = do
+           l <- hGetLine h
+           case () of
+               () | null l -> look h
+                  | prefixMatch "{-# LINE" l -> look h
+                  | Just (opts:_) <- matchRegex optionRegex l
+                       -> return (words opts)
+                  | otherwise -> return []
+
+optionRegex = mkRegex "{-#[ \t]+OPTIONS[ \t]+(.*)#-}"
+
+-----------------------------------------------------------------------------
+-- Main loop
+
+get_source_files :: [String] -> ([String],[String])
+get_source_files = partition (('-' /=) . head)
+
+suffixes :: [(String,Phase)]
+suffixes =
+  [ ("lhs",   Unlit)
+  , ("hs",    Cpp)
+  , ("hc",    HCc)
+  , ("c",     Cc)
+  , ("raw_s", Mangle)
+  , ("s",     As)
+  , ("S",     As)
+  , ("o",     Ln)
+  ]
+
+phase_input_ext Unlit       = "lhs"
+phase_input_ext        Cpp         = "lpp"
+phase_input_ext        Hsc         = "cpp"
+phase_input_ext        HCc         = "hc"
+phase_input_ext Cc          = "c"
+phase_input_ext        Mangle      = "raw_s"
+phase_input_ext        SplitMangle = "split_s" -- not really generated
+phase_input_ext        As          = "s"
+phase_input_ext        Ln          = "o"
+
+find_phase :: String -> ([(Phase,String)], [String])
+   -> ([(Phase,String)], [String])
+find_phase f (phase_srcs, unknown_srcs)
+  = case lookup ext suffixes of
+       Just the_phase -> ((the_phase,f):phase_srcs, unknown_srcs)
+       Nothing        -> (phase_srcs, f:unknown_srcs)
+  where (basename,ext) = split_filename f
+
+
+find_phases srcs = (phase_srcs, unknown_srcs)
+  where (phase_srcs, unknown_srcs) = foldr find_phase ([],[]) srcs
+
+main =
+  -- all error messages are propagated as exceptions
+  my_catchDyn (\dyn -> case dyn of
+                         PhaseFailed phase code -> exitWith code
+                         Interrupted -> exitWith (ExitFailure 1)
+                         _ -> do hPutStrLn stderr (show (dyn :: BarfKind))
+                                 exitWith (ExitFailure 1)) $
+
+  later cleanTempFiles $
+       -- exceptions will be blocked while we clean the temporary files,
+       -- so there shouldn't be any difficulty if we receive further
+       -- signals.
+
+  do
+       -- install signal handlers
+   main_thread <- myThreadId
+   let sig_handler = Catch (raiseInThread main_thread 
+                               (DynException (toDyn Interrupted)))
+   installHandler sigQUIT sig_handler Nothing 
+   installHandler sigINT  sig_handler Nothing
+
+   pgm    <- getProgName
+   writeIORef prog_name pgm
+
+   argv   <- getArgs
+
+   -- grab any -B options from the command line first
+   argv'  <- setTopDir argv
+
+   -- read the package configuration
+   let conf = findFile "package.conf" (_GHC_DRIVER_DIR++"/package.conf.inplace")
+   contents <- readFile conf
+   writeIORef package_details (read contents)
+
+   -- find the phase to stop after (i.e. -E, -C, -c, -S flags)
+   (flags2, stop_phase, do_linking) <- getStopAfter argv'
+
+   -- process all the other arguments, and get the source files
+   srcs   <- processArgs flags2 []
+
+   -- find the build tag, and re-process the build-specific options
+   more_opts <- findBuildTag
+   _ <- processArgs more_opts []
+
+   if stop_phase == MkDependHS         -- mkdependHS is special
+       then do_mkdependHS flags2 srcs
+       else do
+
+   -- for each source file, find which phase to start at
+   let (phase_srcs, unknown_srcs) = find_phases srcs
+
+   o_file <- readIORef output_file
+   if isJust o_file && not do_linking && length phase_srcs > 1
+       then throwDyn MultipleSrcsOneOutput
+       else do
+
+   -- if we have unknown files, and we're not doing linking, complain
+   -- (otherwise pass them through to the linker).
+   if not (null unknown_srcs) && not do_linking
+       then throwDyn (UnknownFileType (head unknown_srcs))
+       else do
+
+
+   let  compileFile :: (Phase, String) -> IO String
+       compileFile (phase, src) = do
+         let (orig_base, _) = split_filename src
+         if phase < Ln -- anything to do?
+               then run_pipeline stop_phase do_linking orig_base (phase,src)
+               else return src
+
+   o_files <- mapM compileFile phase_srcs
+
+   if do_linking
+       then do_link o_files unknown_srcs
+       else return ()
+
+
+-- The following compilation pipeline algorithm is fairly hacky.  A
+-- better way to do this would be to express the whole comilation as a
+-- data flow DAG, where the nodes are the intermediate files and the
+-- edges are the compilation phases.  This framework would also work
+-- nicely if a haskell dependency generator was included in the
+-- driver.
+
+-- It would also deal much more cleanly with compilation phases that
+-- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
+-- possibly stub files), where some of the output files need to be
+-- processed further (eg. the stub files need to be compiled by the C
+-- compiler).
+
+-- A cool thing to do would then be to execute the data flow graph
+-- concurrently, automatically taking advantage of extra processors on
+-- the host machine.  For example, when compiling two Haskell files
+-- where one depends on the other, the data flow graph would determine
+-- that the C compiler from the first comilation can be overlapped
+-- with the hsc comilation for the second file.
+
+run_pipeline
+  :: Phase             -- phase to end on (never Linker)
+  -> Bool              -- doing linking afterward?
+  -> String            -- original basename (eg. Main)
+  -> (Phase, String)    -- phase to run, input file
+  -> IO String         -- return final filename
+
+run_pipeline last_phase do_linking orig_basename (phase, input_fn) = do
+
+     let (basename,ext) = split_filename input_fn
+
+     split <- readIORef split_object_files
+     mangle <- readIORef do_asm_mangling
+     lang <- readIORef hsc_lang
+
+       -- figure out what the next phase is.  This is
+       -- straightforward, apart from the fact that hsc can generate
+       -- either C or assembler direct, and assembly mangling is
+       -- optional.
+     let next_phase =
+         case phase of
+               Hsc -> case lang of
+                           HscC   -> HCc
+                           HscAsm -> As
+
+               HCc  | mangle    -> Mangle
+                    | otherwise -> As
+
+               Cc -> As
+
+               Mangle | not split -> As
+       
+               _  -> succ phase
+
+
+       -- filename extension for the output
+     let new_ext = phase_input_ext next_phase
+
+       -- Figure out what the output from this pass should be called.
+
+       -- If we're keeping the output from this phase, then we just save
+       -- it in the current directory, otherwise we generate a new temp file.
+     keep_s <- readIORef keep_s_files
+     keep_raw_s <- readIORef keep_raw_s_files
+     keep_hc <- readIORef keep_hc_files
+     let keep_this_output = 
+          case next_phase of
+               Ln -> True
+               Mangle | keep_raw_s -> True -- first enhancement :)
+               As | keep_s  -> True
+               Cc | keep_hc -> True
+               _other -> False
+
+     output_fn <- 
+       (if phase == last_phase && not do_linking
+           then do o_file <- readIORef output_file
+                   case o_file of 
+                       Just s  -> return s
+                       Nothing -> do
+                           f <- odir_ify (orig_basename ++ '.':new_ext)
+                           osuf_ify f
+
+               -- .o files are always kept.  .s files and .hc file may be kept.
+               else if keep_this_output
+                       then odir_ify (orig_basename ++ '.':new_ext)
+                       else do filename <- newTempName new_ext
+                               add files_to_clean filename
+                               return filename
+       )
+
+     run_phase phase orig_basename input_fn output_fn
+
+     if (phase == last_phase)
+       then return output_fn
+       else run_pipeline last_phase do_linking 
+               orig_basename (next_phase, output_fn)
+
+
+-- find a temporary name that doesn't already exist.
+newTempName :: String -> IO String
+newTempName extn = do
+  x <- getProcessID
+  tmp_dir <- readIORef tmp_prefix 
+  findTempName tmp_dir x
+  where findTempName tmp_dir x = do
+          let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
+          b  <- fileExist filename
+          if b then findTempName tmp_dir (x+1)
+               else return filename
+
+-------------------------------------------------------------------------------
+-- mkdependHS phase 
+
+do_mkdependHS :: [String] -> [String] -> IO ()
+do_mkdependHS cmd_opts srcs = do
+       -- ToDo: push (@MkDependHS_flags, "-o$Osuffix") if $Osuffix;
+    --         # They're not (currently) needed, but we need to quote any -#include options
+    -- foreach (@Cmd_opts) {
+    --            s/-#include.*$/'$&'/g;
+    -- };  
+
+   mkdependHS      <- readIORef pgm_dep
+   mkdependHS_opts <- getOpts opt_dep
+   hs_src_cpp_opts <- readIORef hs_source_cpp_opts
+
+   run_something "Dependency generation"
+       (unwords (mkdependHS : 
+                     mkdependHS_opts
+                  ++ hs_src_cpp_opts
+                  ++ ("--" : cmd_opts )
+                  ++ ("--" : srcs)
+       ))
+
+-------------------------------------------------------------------------------
+-- Unlit phase 
+
+run_phase Unlit basename input_fn output_fn
+  = do unlit <- readIORef pgm_L
+       unlit_flags <- getOpts opt_L
+       run_something "Literate pre-processor"
+         (unlit ++ ' ':input_fn ++ " - >> " ++ output_fn)
+
+--    $to_do  = "echo '#line 1 \"$in_lit2pgm\"' > $lit2pgm_hscpp && " if ($Cpp_flag_set);
+
+-------------------------------------------------------------------------------
+-- HsCpp phase 
+
+run_phase Cpp basename input_fn output_fn
+  = do src_opts <- getOptionsFromSource input_fn
+       processArgs src_opts []
+
+       do_cpp <- readIORef cpp_flag
+       if do_cpp
+          then do
+                   cpp <- readIORef pgm_P
+           hscpp_opts <- getOpts opt_P
+                   hs_src_cpp_opts <- readIORef hs_source_cpp_opts
+
+           cmdline_include_paths <- readIORef include_paths
+           let cmdline_include_flags = map (\p -> "-I"++p) cmdline_include_paths
+
+           verb <- is_verbose
+           run_something "C pre-processor" 
+               (unwords
+                          (["echo \'{-# LINE 1 \"hello.hs\" -}\'", ">", output_fn, "&&",
+                    cpp, verb] 
+                   ++ cmdline_include_flags
+                   ++ hs_src_cpp_opts
+                   ++ hscpp_opts
+                   ++ [ input_fn, ">>", output_fn ]
+                  ))
+         else do
+           run_something "Inefective C pre-processor"
+                  ("echo '{-# LINE 1 \""  ++ input_fn ++ "\" -}' > " 
+                   ++ output_fn ++ " && cat " ++ input_fn
+                   ++ " >> " ++ output_fn)
+
+-----------------------------------------------------------------------------
+-- Hsc phase
+
+run_phase Hsc  basename input_fn output_fn
+  = do  hsc <- readIORef pgm_C
+       
+  -- we add the current directory (i.e. the directory in which
+  -- the .hs files resides) to the import path, since this is
+  -- what gcc does, and it's probably what you want.
+       let (root,dir) = break (=='/') (reverse basename)
+           current_dir = if null dir then "." else reverse dir
+       
+       paths <- readIORef include_paths
+       writeIORef include_paths (current_dir : paths)
+       
+  -- build the hsc command line
+       hsc_opts <- build_hsc_opts
+       
+       doing_hi <- readIORef produceHi
+       tmp_hi_file <- if doing_hi      
+                         then do fn <- newTempName "hi"
+                                 add files_to_clean fn
+                                 return fn
+                         else return ""
+       
+       let hi_flag = if doing_hi then "-hifile=" ++ tmp_hi_file
+                                 else ""
+       
+  -- deal with -Rghc-timing
+       timing <- readIORef collect_ghc_timing
+        stat_file <- newTempName "stat"
+        add files_to_clean stat_file
+       let stat_opts | timing    = [ "+RTS", "-S"++stat_file, "-RTS" ]
+                     | otherwise = []
+
+  -- tmp files for foreign export stub code
+       tmp_stub_h <- newTempName "stub_h"
+       tmp_stub_c <- newTempName "stub_c"
+       add files_to_clean tmp_stub_h
+       add files_to_clean tmp_stub_c
+       
+       run_something "Haskell Compiler" 
+                (unwords (hsc : input_fn : (
+                   hsc_opts
+                   ++ [ hi_flag, " -ofile="++output_fn ]
+                   ++ [ "-F="++tmp_stub_c, "-FH="++tmp_stub_h ]
+                   ++ stat_opts
+                )))
+
+  -- Copy the .hi file into the current dir if it changed
+       on doing_hi 
+                 (do ohi <- readIORef output_hi
+                     hisuf <- readIORef hi_suf
+                     let hi_target = case ohi of
+                                       Nothing -> basename ++ '.':hisuf
+                                       Just fn -> fn
+                     new_hi_file <- fileExist tmp_hi_file
+                     on new_hi_file
+                            (run_something "Copy hi file"
+                               (unwords ["mv", tmp_hi_file, hi_target]))
+                 )     
+       
+  -- Generate -Rghc-timing info
+       on (timing) (
+           run_something "Generate timing stats"
+               (findFile "ghc-stats" _GHC_STATS ++ ' ':stat_file)
+        )
+
+  -- Deal with stubs
+       let stub_h = basename ++ "_stub.h"
+       let stub_c = basename ++ "_stub.c"
+       
+               -- copy .h_stub file into current dir if present
+       b <- fileExist tmp_stub_h
+       on b (do
+               run_something "Copy stub .h file"
+                               ("cp " ++ tmp_stub_h ++ ' ':stub_h)
+       
+                       -- #include <..._stub.h> in .hc file
+               add cmdline_hc_includes tmp_stub_h      -- hack
+
+                       -- copy the _stub.c file into the current dir
+               run_something "Copy stub .c file" 
+                   (unwords [ 
+                       "rm -f", stub_c, "&&",
+                       "echo \'#include \""++stub_h++"\"\' >"++stub_c, " &&",
+                       "cat", tmp_stub_c, ">> ", stub_c
+                       ])
+
+                       -- compile the _stub.c file w/ gcc
+               run_pipeline As False (basename++"_stub") (Cc, stub_c)
+               add ld_inputs (basename++"_stub.o")
+        )
+
+-----------------------------------------------------------------------------
+-- Cc phase
+
+-- we don't support preprocessing .c files (with -E) now.  Doing so introduces
+-- way too many hacks, and I can't say I've ever used it anyway.
+
+run_phase cc_phase basename input_fn output_fn
+   | cc_phase == Cc || cc_phase == HCc
+   = do        cc <- readIORef pgm_c
+               cc_opts <- getOpts opt_c
+               cmdline_include_dirs <- readIORef include_paths
+       -- ToDo: $c_flags .= " -mno-cygwin" if ( $TargetPlatform =~ /-mingw32$/ );
+
+        let hcc = cc_phase == HCc
+
+               -- add package include paths even if we're just compiling
+               -- .c files; this is the Value Add(TM) that using
+               -- ghc instead of gcc gives you :)
+        pkg_include_dirs <- getPackageIncludePath
+       let include_paths = map (\p -> "-I"++p) (cmdline_include_dirs 
+                                                       ++ pkg_include_dirs)
+
+       c_includes <- getPackageCIncludes
+       cmdline_includes <- readIORef cmdline_hc_includes -- -#include options
+
+       let cc_injects | hcc = unlines (map mk_include 
+                                       (c_includes ++ reverse cmdline_includes))
+                      | otherwise = ""
+           mk_include h_file = 
+               case h_file of 
+                  '"':_{-"-} -> "#include "++h_file
+                  '<':_      -> "#include "++h_file
+                  _          -> "#include \""++h_file++"\""
+
+       cc_help <- newTempName "c"
+       add files_to_clean cc_help
+       h <- openFile cc_help WriteMode
+       hPutStr h cc_injects
+       hPutStrLn h ("#include \"" ++ input_fn ++ "\"\n")
+       hClose h
+
+       ccout <- newTempName "ccout"
+       add files_to_clean ccout
+
+       mangle <- readIORef do_asm_mangling
+       (md_c_flags, md_regd_c_flags) <- machdepCCOpts
+
+        verb <- is_verbose
+
+       o2 <- readIORef opt_minus_o2_for_C
+       let opt_flag | o2        = "-O2"
+                    | otherwise = "-O"
+
+       run_something "C Compiler"
+        (unwords ([ cc, "-x", "c", cc_help, "-o", output_fn ]
+                  ++ md_c_flags
+                  ++ (if cc_phase == HCc && mangle
+                        then md_regd_c_flags
+                        else [])
+                  ++ [ verb, "-S", "-Wimplicit", opt_flag ]
+                  ++ cc_opts
+                  ++ include_paths
+--                ++ [">", ccout]
+                  ))
+
+       -- ToDo: postprocess the output from gcc
+
+-----------------------------------------------------------------------------
+-- Mangle phase
+
+run_phase Mangle basename input_fn output_fn
+  = do mangler <- readIORef pgm_m
+       mangler_opts <- getOpts opt_m
+       machdep_opts <-
+        if (prefixMatch "i386" _TARGETPLATFORM)
+           then do n_regs <- readIORef stolen_x86_regs
+                   return [ show n_regs ]
+           else return []
+       run_something "Assembly Mangler"
+       (unwords (mangler : 
+                    mangler_opts
+                 ++ [ input_fn, output_fn ]
+                 ++ machdep_opts
+               ))
+
+-----------------------------------------------------------------------------
+-- Splitting phase
+
+run_phase SplitMangle basename input_fn outputfn
+  = do  splitter <- readIORef pgm_s
+
+       -- this is the prefix used for the split .s files
+       tmp_pfx <- readIORef tmp_prefix
+       x <- getProcessID
+       let split_s_prefix = tmp_pfx ++ "/ghc" ++ show x
+       writeIORef split_prefix split_s_prefix
+       add files_to_clean (split_s_prefix ++ "__*") -- d:-)
+
+       -- allocate a tmp file to put the no. of split .s files in (sigh)
+       n_files <- newTempName "n_files"
+       add files_to_clean n_files
+
+       run_something "Split Assembly File"
+        (unwords [ splitter
+                 , input_fn
+                 , split_s_prefix
+                 , n_files ]
+        )
+
+       -- save the number of split files for future references
+       s <- readFile n_files
+       let n = read s :: Int
+       writeIORef n_split_files n
+
+-----------------------------------------------------------------------------
+-- As phase
+
+run_phase As basename input_fn output_fn
+  = do         split <- readIORef split_object_files
+       as <- readIORef pgm_a
+        as_opts <- getOpts opt_a
+
+        if not split then do
+            cmdline_include_paths <- readIORef include_paths
+            let cmdline_include_flags = map (\p -> "-I"++p) cmdline_include_paths
+            run_something "Assembler"
+            (unwords (as : as_opts
+                      ++ cmdline_include_flags
+                      ++ [ "-c", input_fn, "-o",  output_fn ]
+                   ))
+
+        else do
+           odir_opt <- readIORef output_dir
+           let odir | Just s <- odir_opt = s
+                    | otherwise          = basename
+           
+           split_s_prefix <- readIORef split_prefix
+           n <- readIORef n_split_files
+
+           odir <- readIORef output_dir
+           let real_odir = case odir of
+                               Nothing -> basename
+                               Just d  -> d
+           
+           let assemble_file n = do
+                   let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
+                   let output_o = newdir real_odir 
+                                       (basename ++ "__" ++ show n ++ ".o")
+                   run_something "Assembler" 
+                           (unwords (as : as_opts
+                                     ++ [ "-c", "-o ", output_o, input_s ]
+                           ))
+           
+           mapM_ assemble_file [1..n]
+
+-----------------------------------------------------------------------------
+-- Linking
+
+do_link :: [String] -> [String] -> IO ()
+do_link o_files unknown_srcs = do
+    ln <- readIORef pgm_l
+    verb <- is_verbose
+    o_file <- readIORef output_file
+    let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
+
+    pkg_lib_paths <- getPackageLibraryPath
+    let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
+
+    lib_paths <- readIORef library_paths
+    let lib_path_opts = map ("-L"++) lib_paths
+
+    pkg_libs <- getPackageLibraries
+    let pkg_lib_opts = map ("-l"++) pkg_libs
+
+    libs <- readIORef cmdline_libraries
+    let lib_opts = map ("-l"++) (reverse libs)
+        -- reverse because they're added in reverse order from the cmd line
+
+    pkg_extra_ld_opts <- getPackageExtraLdOpts
+
+       -- probably _stub.o files
+    extra_ld_inputs <- readIORef ld_inputs
+
+    run_something "Linker"
+       (unwords 
+        ([ ln, verb, "-o", output_fn ]
+            -- ToDo: -u <blah> options
+        ++ o_files
+        ++ unknown_srcs
+        ++ extra_ld_inputs
+        ++ lib_path_opts
+        ++ lib_opts
+        ++ pkg_lib_path_opts
+        ++ pkg_lib_opts
+        ++ pkg_extra_ld_opts
+       )
+       )
+
+-----------------------------------------------------------------------------
+-- Running an external program
+
+run_something phase_name cmd
+ = do
+   verb <- readIORef verbose
+   if verb then do
+       putStr phase_name
+       putStrLn ":"
+       putStrLn cmd
+     else
+       return ()
+
+   -- test for -n flag
+   n <- readIORef dry_run
+   if n then return () else do 
+
+   -- and run it!
+   exit_code <- system cmd  `catchAllIO` 
+                  (\e -> throwDyn (PhaseFailed phase_name (ExitFailure 1)))
+
+   if exit_code /= ExitSuccess
+       then throwDyn (PhaseFailed phase_name exit_code)
+       else do on verb (putStr "\n")
+               return ()
+
+-----------------------------------------------------------------------------
+-- Flags
+
+data OptKind 
+       = NoArg (IO ())                 -- flag with no argument
+       | HasArg (String -> IO ())      -- flag has an argument (maybe prefix)
+       | SepArg (String -> IO ())      -- flag has a separate argument
+       | Prefix (String -> IO ())      -- flag is a prefix only
+       | OptPrefix (String -> IO ())   -- flag may be a prefix
+       | AnySuffix (String -> IO ())   -- flag is a prefix, pass whole arg to fn
+       | PassFlag  (String -> IO ())   -- flag with no arg, pass flag to fn
+
+opts = 
+  [  ------- help -------------------------------------------------------
+     ( "?"             , NoArg long_usage)
+  ,  ( "-help"         , NoArg long_usage)
+  
+
+      ------- version ----------------------------------------------------
+  ,  ( "-version"      , NoArg (do hPutStrLn stderr (_ProjectName
+                                     ++ ", version " ++ _ProjectVersion
+                                     ++ ", patchlevel " ++ _ProjectPatchLevel)
+                                   exitWith ExitSuccess))
+
+      ------- verbosity ----------------------------------------------------
+  ,  ( "v"             , NoArg (writeIORef verbose True) )
+  ,  ( "n"              , NoArg (writeIORef dry_run True) )
+
+       ------- recompilation checker --------------------------------------
+  ,  ( "recomp"                , NoArg (writeIORef recomp True) )
+  ,  ( "no-recomp"     , NoArg (writeIORef recomp False) )
+
+       ------- ways --------------------------------------------------------
+  ,  ( "prof"          , NoArg (add ways WayProf) )
+  ,  ( "unreg"         , NoArg (add ways WayUnreg) )
+  ,  ( "ticky"         , NoArg (add ways WayTicky) )
+  ,  ( "parallel"      , NoArg (add ways WayPar) )
+  ,  ( "gransim"       , NoArg (add ways WayGran) )
+  ,  ( "smp"           , NoArg (add ways WaySMP) )
+  ,  ( "debug"         , NoArg (add ways WayDebug) )
+       -- ToDo: user ways
+
+       ------- Interface files ---------------------------------------------
+  ,  ( "hi"            , NoArg (writeIORef produceHi True) )
+  ,  ( "nohi"          , NoArg (writeIORef produceHi False) )
+  ,  ( "hi-diffs"      , NoArg (writeIORef hi_diffs  NormalHiDiffs) )
+  ,  ( "no-hi-diffs"   , NoArg (writeIORef hi_diffs  NoHiDiffs) )
+  ,  ( "hi-diffs-with-usages" , NoArg (writeIORef hi_diffs UsageHiDiffs) )
+  ,  ( "keep-hi-diffs" , NoArg (writeIORef keep_hi_diffs True) )
+       --"hi-with-*"    -> hiw <- readIORef hi_with  (ToDo)
+
+       --------- Profiling --------------------------------------------------
+  ,  ( "auto-dicts"    , NoArg (add opt_C "-fauto-sccs-on-dicts") )
+  ,  ( "auto-all"      , NoArg (add opt_C "-fauto-sccs-on-all-toplevs") )
+  ,  ( "auto"          , NoArg (add opt_C "-fauto-sccs-on-exported-toplevs") )
+  ,  ( "caf-all"       , NoArg (add opt_C "-fauto-sccs-on-individual-cafs") )
+         -- "ignore-sccs"  doesn't work  (ToDo)
+
+       ------- Miscellaneous -----------------------------------------------
+  ,  ( "cpp"           , NoArg (writeIORef cpp_flag True) )
+  ,  ( "#include"      , SepArg (add cmdline_hc_includes) )
+
+       ------- Output Redirection ------------------------------------------
+  ,  ( "odir"          , HasArg (writeIORef output_dir  . Just) )
+  ,  ( "o"             , SepArg (writeIORef output_file . Just) )
+  ,  ( "osuf"          , HasArg (writeIORef output_suf  . Just) )
+  ,  ( "hisuf"         , HasArg (writeIORef hi_suf) )
+  ,  ( "tmpdir"                , HasArg (writeIORef tmp_prefix  . (++ "/")) )
+  ,  ( "ohi"           , HasArg (\s -> case s of 
+                                         "-" -> writeIORef hi_on_stdout True
+                                         _   -> writeIORef output_hi (Just s)) )
+       -- -odump?
+
+  ,  ( "keep-hc-file"   , AnySuffix (\_ -> writeIORef keep_hc_files True) )
+  ,  ( "keep-s-file"    , AnySuffix (\_ -> writeIORef keep_s_files  True) )
+  ,  ( "keep-raw-s-file", AnySuffix (\_ -> writeIORef keep_raw_s_files  True) )
+
+  ,  ( "split-objs"    , NoArg (if can_split
+                                   then do writeIORef split_object_files True
+                                           writeIORef hsc_lang HscC
+                                           add opt_C "-fglobalise-toplev-names"
+                                           add opt_c "-DUSE_SPLIT_MARKERS"
+                                   else hPutStrLn stderr
+                                           "warning: don't know how to  split \
+                                           \object files on this architecture"
+                               ) )
+  
+       ------- Include/Import Paths ----------------------------------------
+  ,  ( "i"             , OptPrefix augment_import_paths )
+  ,  ( "I"             , Prefix augment_include_paths )
+
+       ------- Libraries ---------------------------------------------------
+  ,  ( "L"             , Prefix augment_library_paths )
+  ,  ( "l"             , Prefix (add cmdline_libraries) )
+
+        ------- Packages ----------------------------------------------------
+  ,  ( "package-name"   , HasArg (\s -> add opt_C ("-inpackage="++s)) )
+
+  ,  ( "package"        , HasArg (addPackage) )
+  ,  ( "syslib"         , HasArg (addPackage) )        -- for compatibility w/ old vsns
+
+        ------- Specific phases  --------------------------------------------
+  ,  ( "pgmdep"         , HasArg (writeIORef pgm_dep) )
+  ,  ( "pgmL"           , HasArg (writeIORef pgm_L) )
+  ,  ( "pgmP"           , HasArg (writeIORef pgm_P) )
+  ,  ( "pgmC"           , HasArg (writeIORef pgm_C) )
+  ,  ( "pgmc"           , HasArg (writeIORef pgm_c) )
+  ,  ( "pgmm"           , HasArg (writeIORef pgm_m) )
+  ,  ( "pgms"           , HasArg (writeIORef pgm_s) )
+  ,  ( "pgma"           , HasArg (writeIORef pgm_a) )
+  ,  ( "pgml"           , HasArg (writeIORef pgm_l) )
+
+  ,  ( "optdep"                , HasArg (add opt_dep) )
+  ,  ( "optL"          , HasArg (add opt_L) )
+  ,  ( "optP"          , HasArg (add opt_P) )
+  ,  ( "optC"          , HasArg (add opt_C) )
+  ,  ( "optCrts"        , HasArg (add opt_Crts) )
+  ,  ( "optc"          , HasArg (add opt_c) )
+  ,  ( "optm"          , HasArg (add opt_m) )
+  ,  ( "opta"          , HasArg (add opt_a) )
+  ,  ( "optl"          , HasArg (add opt_l) )
+  ,  ( "optdll"                , HasArg (add opt_dll) )
+
+       ------ HsCpp opts ---------------------------------------------------
+  ,  ( "D"             , Prefix (\s -> add opt_P ("-D'"++s++"'") ) )
+  ,  ( "U"             , Prefix (\s -> add opt_P ("-U'"++s++"'") ) )
+
+       ------ Warning opts -------------------------------------------------
+  ,  ( "W"             , NoArg (writeIORef warning_opt W_))
+  ,  ( "Wall"          , NoArg (writeIORef warning_opt W_all))
+  ,  ( "Wnot"          , NoArg (writeIORef warning_opt W_not))
+  ,  ( "w"             , NoArg (writeIORef warning_opt W_not))
+
+       ----- Linker --------------------------------------------------------
+  ,  ( "static"        , NoArg (writeIORef static True) )
+
+        ------ Compiler RTS options -----------------------------------------
+  ,  ( "H"                 , HasArg (sizeOpt specific_heap_size) )
+  ,  ( "K"                 , HasArg (sizeOpt specific_stack_size) )
+  ,  ( "Rscale-sizes"     , HasArg (floatOpt scale_sizes_by) )
+  ,  ( "Rghc-timing"      , NoArg (writeIORef collect_ghc_timing True) )
+
+       ------ Debugging ----------------------------------------------------
+  ,  ( "dstg-stats"       , NoArg (writeIORef opt_StgStats True) )
+
+  ,  ( "dno-"             , Prefix (\s -> add anti_opt_C ("-d"++s)) )
+  ,  ( "d"                , AnySuffix (add opt_C) )
+
+       ------ Machine dependant (-m<blah>) stuff ---------------------------
+
+  ,  ( "monly-2-regs",                 NoArg (writeIORef stolen_x86_regs 2) )
+  ,  ( "monly-3-regs",                 NoArg (writeIORef stolen_x86_regs 3) )
+  ,  ( "monly-4-regs",                 NoArg (writeIORef stolen_x86_regs 4) )
+
+        ------ Compiler flags -----------------------------------------------
+  ,  ( "O2-for-C"         , NoArg (writeIORef opt_minus_o2_for_C True) )
+  ,  ( "O"                , OptPrefix (setOptLevel) )
+
+  ,  ( "fglasgow-exts-no-lang", NoArg ( do add opt_C "-fglasgow-exts") )
+
+  ,  ( "fglasgow-exts"     , NoArg (do add opt_C "-fglasgow-exts"
+                                      addPackage "lang"))
+
+  ,  ( "fasm"             , OptPrefix (\_ -> writeIORef hsc_lang HscAsm) )
+
+  ,  ( "fvia-C"                   , NoArg (writeIORef hsc_lang HscC) )
+
+  ,  ( "fno-asm-mangling"  , NoArg (writeIORef do_asm_mangling True) )
+
+  ,  ( "fmax-simplifier-iterations", 
+               Prefix (writeIORef opt_MaxSimplifierIterations . read) )
+
+  ,  ( "fusagesp",             NoArg (do writeIORef opt_UsageSPInf True
+                                         add opt_C "-fusagesp-on") )
+
+       -- flags that are "active negatives"
+  ,  ( "fno-implicit-prelude"  , PassFlag (add opt_C) )
+  ,  ( "fno-prune-tydecls"     , PassFlag (add opt_C) )
+  ,  ( "fno-prune-instdecls"   , PassFlag (add opt_C) )
+  ,  ( "fno-pre-inlining"      , PassFlag (add opt_C) )
+
+       -- All other "-fno-<blah>" options cancel out "-f<blah>" on the hsc cmdline
+  ,  ( "fno-",                 Prefix (\s -> add anti_opt_C ("-f"++s)) )
+
+       -- Pass all remaining "-f<blah>" options to hsc
+  ,  ( "f",                    AnySuffix (add opt_C) )
+  ]
+
+-----------------------------------------------------------------------------
+-- Process command-line  
+
+processArgs :: [String] -> [String] -> IO [String]  -- returns spare args
+processArgs [] spare = return (reverse spare)
+processArgs args@(('-':_):_) spare = do
+  args' <- processOneArg args
+  processArgs args' spare
+processArgs (arg:args) spare = 
+  processArgs args (arg:spare)
+
+processOneArg :: [String] -> IO [String]
+processOneArg (('-':arg):args) = do
+  let (rest,action) = findArg arg
+      dash_arg = '-':arg
+  case action of
+
+       NoArg  io -> 
+               if rest == ""
+                       then io >> return args
+                       else throwDyn (UnknownFlag dash_arg)
+
+       HasArg fio -> 
+               if rest /= "" 
+                       then fio rest >> return args
+                       else case args of
+                               [] -> throwDyn (UnknownFlag dash_arg)
+                               (arg1:args1) -> fio arg1 >> return args1
+
+       SepArg fio -> 
+               case args of
+                       [] -> throwDyn (UnknownFlag dash_arg)
+                       (arg1:args1) -> fio arg1 >> return args1
+
+       Prefix fio -> 
+               if rest /= ""
+                       then fio rest >> return args
+                       else throwDyn (UnknownFlag dash_arg)
+       
+       OptPrefix fio -> fio rest >> return args
+
+       AnySuffix fio -> fio ('-':arg) >> return args
+
+       PassFlag fio  -> 
+               if rest /= ""
+                       then throwDyn (UnknownFlag dash_arg)
+                       else fio ('-':arg) >> return args
+
+findArg :: String -> (String,OptKind)
+findArg arg
+  = case [ (rest,k) | (pat,k) <- opts, 
+                     Just rest <- [my_prefix_match pat arg],
+                     is_prefix k || null rest ] of
+       [] -> throwDyn (UnknownFlag ('-':arg))
+       (one:_) -> one
+
+is_prefix (NoArg _) = False
+is_prefix (SepArg _) = False
+is_prefix (PassFlag _) = False
+is_prefix _ = True
+
+-----------------------------------------------------------------------------
+-- convert sizes like "3.5M" into integers
+
+sizeOpt :: IORef Integer -> String -> IO ()
+sizeOpt ref str
+  | c == ""             = writeSizeOpt ref (truncate n)
+  | c == "K" || c == "k" = writeSizeOpt        ref (truncate (n * 1000))
+  | c == "M" || c == "m" = writeSizeOpt        ref (truncate (n * 1000 * 1000))
+  | c == "G" || c == "g" = writeSizeOpt        ref (truncate (n * 1000 * 1000 * 1000))
+  | otherwise            = throwDyn (UnknownFlag str)
+  where (m, c) = span pred str
+        n      = read m  :: Double
+       pred c = isDigit c || c == '.'
+
+writeSizeOpt :: IORef Integer -> Integer -> IO ()
+writeSizeOpt ref new = do
+  current <- readIORef ref
+  if (new > current) 
+       then writeIORef ref new
+       else return ()
+
+floatOpt :: IORef Double -> String -> IO ()
+floatOpt ref str
+  = writeIORef ref (read str :: Double)
+
+-----------------------------------------------------------------------------
+-- Finding files in the installation
+
+GLOBAL_VAR(topDir, _libdir, String)
+
+       -- grab the last -B option on the command line, and
+       -- set topDir to its value.
+setTopDir :: [String] -> IO [String]
+setTopDir args = do
+  let (minusbs, others) = partition (prefixMatch "-B") args
+  (case minusbs of
+    []   -> writeIORef topDir _libdir
+    some -> writeIORef topDir (drop 2 (last some)))
+  return others
+
+findFile name alt_path = unsafePerformIO (do
+  top_dir <- readIORef topDir
+  let installed_file = top_dir ++ '/':name
+  let inplace_file   = top_dir ++ '/':_CURRENT_DIR ++ '/':alt_path
+  b <- fileExist inplace_file
+  if b  then return inplace_file
+       else return installed_file
+ )
+
+-----------------------------------------------------------------------------
+-- Utils
+
+my_partition :: (a -> Maybe b) -> [a] -> ([b],[a])
+my_partition p [] = ([],[])
+my_partition p (a:as)
+  = let (bs,cs) = my_partition p as in
+    case p a of
+       Nothing -> (bs,a:cs)
+       Just b  -> (b:bs,cs)
+
+my_prefix_match :: String -> String -> Maybe String
+my_prefix_match [] rest = Just rest
+my_prefix_match (p:pat) [] = Nothing
+my_prefix_match (p:pat) (r:rest)
+  | p == r    = my_prefix_match pat rest
+  | otherwise = Nothing
+
+prefixMatch :: Eq a => [a] -> [a] -> Bool
+prefixMatch [] str = True
+prefixMatch pat [] = False
+prefixMatch (p:ps) (s:ss) | p == s    = prefixMatch ps ss
+                         | otherwise = False
+
+postfixMatch :: String -> String -> Bool
+postfixMatch pat str = prefixMatch (reverse pat) (reverse str)
+
+later = flip finally
+
+on b io = if b then io >> return (error "on") else return (error "on")
+
+my_catch = flip catchAllIO
+my_catchDyn = flip catchDyn
+
+global :: a -> IORef a
+global a = unsafePerformIO (newIORef a)
+
+split_filename :: String -> (String,String)
+split_filename f = (reverse rev_basename, reverse rev_ext)
+  where (rev_ext, '.':rev_basename) = span ('.' /=) (reverse f)
+
+split :: Char -> String -> [String]
+split c s = case rest of
+               []     -> [chunk] 
+               _:rest -> chunk : split c rest
+  where (chunk, rest) = break (==c) s
+
+add :: IORef [a] -> a -> IO ()
+add var x = do
+  xs <- readIORef var
+  writeIORef var (x:xs)
+
+remove_suffix :: String -> Char -> String
+remove_suffix s c 
+  | null pre  = reverse suf
+  | otherwise = reverse pre
+  where (suf,pre) = break (==c) (reverse s)
+
+drop_longest_prefix :: String -> Char -> String
+drop_longest_prefix s c = reverse suf
+  where (suf,pre) = break (==c) (reverse s)
+
+take_longest_prefix :: String -> Char -> String
+take_longest_prefix s c = reverse pre
+  where (suf,pre) = break (==c) (reverse s)
+
+newsuf :: String -> String -> String
+newsuf suf s = remove_suffix s '.' ++ suf
+
+newdir :: String -> String -> String
+newdir dir s = dir ++ '/':drop_longest_prefix s '/'
index 7c65e00..9bfcedd 100644 (file)
 #-----------------------------------------------------------------------------
-# $Id: Makefile,v 1.31 2000/05/25 13:11:17 panne Exp $
-
-# We create two driver scripts: 
-#      - one to run in-place in the build tree for building libraries
-#      - one wired to the install locations for later installation
+# $Id: Makefile,v 1.32 2000/06/13 16:07:20 simonmar Exp $
 #
-# the installation script is built first, and we invoke make recursively
-# to build the in-place version.
 
 TOP=..
 CURRENT_DIR=ghc/driver
 include $(TOP)/mk/boilerplate.mk
 
-INSTALLING=1
-
-DYN_LOADABLE_BITS = \
-       ghc-asm.prl \
-       ghc-consist.prl \
-       ghc-split.prl
-
-INSTALLED_SCRIPT_PROG  = ghc-$(ProjectVersion)
-INPLACE_SCRIPT_PROG    = ghc-inplace
-
-ifeq "$(INSTALLING)" "1"
-TOP_PWD        := $(prefix)
-SCRIPT_PROG    =  $(INSTALLED_SCRIPT_PROG)
-SCRIPT_LINK    =  ghc
+ifneq "$(GhcWithHscBuiltViaC)" "YES"
+HC=$(WithGhcHc)
 else
-TOP_PWD        := $(FPTOOLS_TOP_ABS)
-SCRIPT_PROG    =  $(INPLACE_SCRIPT_PROG)
-endif
-
-SCRIPT_OBJS = ghc.prl
-INTERP=perl
-
-#
-# The driver needs to know the options and names for 
-# all possible ways, so we magically generate the
-# the make variable names for them here.
-#
-
-USER_WAY_NAMES = $(foreach way,$(USER_WAYS),WAY_$(way)_NAME)
-USER_WAY_OPTS  = $(foreach way,$(USER_WAYS),WAY_$(way)_REAL_OPTS)
-
-SCRIPT_SUBST_VARS := \
-  INSTALLING \
-  ProjectName ProjectVersion ProjectVersionInt \
-  HscMajorVersion HscMinorVersion CcMajorVersion CcMinorVersion \
-  CURRENT_DIR HOSTPLATFORM TARGETPLATFORM \
-  GHC_LIB_DIR GHC_RUNTIME_DIR GHC_INCLUDE_DIR \
-  GHC_OPT_HILEV_ASM GhcWithNativeCodeGen LeadingUnderscore\
-  GHC_UNLIT GHC_HSCPP GHC_MKDEPENDHS GHC_HSC GHC_SYSMAN EnableWin32DLLs \
-  CP RM CONTEXT_DIFF LibGmp GhcWithRegisterised LibsReadline \
-  $(USER_WAY_NAMES) $(USER_WAY_OPTS)
-
-#
-# When creating a binary distribution, we prefix the driver script
-# with a short msg about what variables need to be set to get the
-# script going. 
-#
-
-ifeq "$(BIN_DIST)" "1"
-SCRIPT_PREFIX_FILES=prefix.txt
-else
-SCRIPT_SUBST_VARS += libdir includedir libexecdir datadir bindir TMPDIR TOP_PWD
-endif
-
-all :: $(DYN_LOADABLE_BITS)
-
-# don't recurse on 'make install'
-#
-ifeq "$(INSTALLING)" "1"
-all clean distclean mostlyclean maintainer-clean ::
-       $(MAKE) INSTALLING=0 BIN_DIST=0 $(MFLAGS) $@
+HC=$(GHC_INPLACE)
 endif
 
-#
-# Install setup:
-#   the driver goes in $(bindir), the perl script helpers
-#   in $(libdir)
-#
-# ToDo: allow different install name for driver?
-#
-INSTALL_SCRIPTS += $(SCRIPT_PROG)
-INSTALL_LIBS    += $(DYN_LOADABLE_BITS)
-
-#
-# depend setup: other directories need the driver script to compute
-# their dependencies, so `depend' is simply an alias for `all' here.
-depend :: all
-
-#
-# Clean up
-#
-CLEAN_FILES += $(SCRIPT_OBJS) $(SCRIPT_LINK) $(DYN_LOADABLE_BITS) ghc-[0-9].*
-
-#
-# Source distribution
-#
-SRC_DEST_FILES=$(patsubst %.prl,%.lprl,$(DYN_LOADABLE_BITS)) ghc.lprl ordering-passes test_mangler
+SRC_HC_OPTS += -fglasgow-exts -cpp -syslib concurrent -syslib posix -syslib text
+
+HS_PROG = ghc-$(ProjectVersion)
+HS_SRCS = Config.hs Package.hs Main.hs
+MKDEPENDHS_SRCS = Config.hs Main.hs PackageSrc.hs
+LINK = ghc
+
+SUBDIRS = mangler split stats
+
+# -----------------------------------------------------------------------------
+# Create driver configuration
+
+boot :: Config.hs
+
+Config.hs : $(FPTOOLS_TOP)/mk/config.mk Makefile
+       @$(RM) -f Config.hs
+       @echo -n "Creating Config.hs ... "
+       @echo "module Config where" >>Config.hs
+       @echo "_ProjectName          = \"$(ProjectName)\"" >> Config.hs            
+       @echo "_ProjectVersion       = \"$(ProjectVersion)\"" >> Config.hs         
+       @echo "_ProjectVersionInt    = \"$(ProjectVersionInt)\"" >> Config.hs      
+       @echo "_ProjectPatchLevel    = \"$(ProjectPatchLevel)\"" >> Config.hs      
+       @echo "_HOSTPLATFORM         = \"$(HOSTPLATFORM)\"" >> Config.hs           
+       @echo "_TARGETPLATFORM       = \"$(TARGETPLATFORM)\"" >> Config.hs         
+       @echo "_CURRENT_DIR          = \"$(CURRENT_DIR)\"" >> Config.hs            
+       @echo "_GHC_LIB_DIR          = \"$(GHC_LIB_DIR)\"" >> Config.hs            
+       @echo "_GHC_RUNTIME_DIR      = \"$(GHC_RUNTIME_DIR)\"" >> Config.hs        
+       @echo "_GHC_UTILS_DIR        = \"$(GHC_UTILS_DIR)\"" >> Config.hs          
+       @echo "_GHC_INCLUDE_DIR      = \"$(GHC_INCLUDE_DIR)\"" >> Config.hs        
+       @echo "_GHC_DRIVER_DIR       = \"$(GHC_DRIVER_DIR)\"" >> Config.hs        
+       @echo "_GCC                  = \"$(WhatGccIsCalled)\"" >> Config.hs
+       @echo "_GhcWithNativeCodeGen = \"$(GhcWithNativeCodeGen)\"" >> Config.hs   
+       @echo "_LeadingUnderscore    = \"$(LeadingUnderscore)\"" >> Config.hs      
+       @echo "_GHC_MKDEPENDHS       = \"$(GHC_MKDEPENDHS)\"" >> Config.hs
+       @echo "_GHC_UNLIT            = \"$(GHC_UNLIT)\"" >> Config.hs              
+       @echo "_GHC_HSCPP            = \"$(GHC_HSCPP)\"" >> Config.hs              
+       @echo "_GHC_HSC              = \"$(GHC_HSC)\"" >> Config.hs                
+       @echo "_GHC_MANGLER          = \"$(GHC_MANGLER)\"" >> Config.hs
+       @echo "_GHC_SPLIT            = \"$(GHC_SPLIT)\"" >> Config.hs
+       @echo "_GHC_STATS            = \"$(GHC_STATS)\"" >> Config.hs
+       @echo "_GHC_SYSMAN           = \"$(GHC_SYSMAN)\"" >> Config.hs             
+       @echo "_EnableWin32DLLs      = \"$(EnableWin32DLLs)\"" >> Config.hs        
+       @echo "_CP                   = \"$(CP)\"" >> Config.hs                     
+       @echo "_RM                   = \"$(RM)\"" >> Config.hs                     
+       @echo "_CONTEXT_DIFF         = \"$(CONTEXT_DIFF)\"" >> Config.hs           
+       @echo "_HaveLibGmp           = \"$(HaveLibGmp)\"" >> Config.hs
+       @echo "_GhcWithRegisterised  = \"$(GhcWithRegisterised)\"" >> Config.hs    
+       @echo "_USER_WAY_NAMES       = \"$(USER_WAY_NAMES)\"" >> Config.hs         
+       @echo "_USER_WAY_OPTS        = \"$(USER_WAY_OPTS)\"" >> Config.hs          
+       @echo "_libdir               = \"$(libdir)\"" >> Config.hs                 
+       @echo "_libexecdir           = \"$(libexecdir)\"" >> Config.hs             
+       @echo "_datadir              = \"$(datadir)\"" >> Config.hs                
+       @echo "_bindir               = \"$(bindir)\"" >> Config.hs                 
+       @echo "_TMPDIR               = \"$(TMPDIR)\"" >> Config.hs                 
+       @echo "_FPTOOLS_TOP_ABS      = \"$(FPTOOLS_TOP_ABS)\"" >> Config.hs
+       @echo done.
+
+CLEAN_FILES += Config.hs
+
+# -----------------------------------------------------------------------------
+# Create link to from ghc-x.xx to ghc...
+
+all :: $(LINK)
+
+$(LINK) : $(HS_PROG)
+       @if ( $(PERL) -e '$$fn="$(LINK)"; exit ((! -f $$fn || -l $$fn) ? 0 : 1);' ); then \
+          echo "Creating a symbolic link from $(HS_PROG) to $(LINK)"; \
+          $(RM) $(LINK); \
+          $(LN_S) $(HS_PROG) $(LINK); \
+        else \
+          echo "Creating a symbolic link from $(HS_PROG) to $(LINK) failed: \`$(LINK)' already exists"; \
+          echo "Perhaps remove \`$(LINK)' manually?"; \
+          exit 1; \
+        fi;
+
+# -----------------------------------------------------------------------------
+# create ghc-inplace, a convenient way to run ghc from the build tree...
+
+all :: ghc-inplace
+
+ghc-inplace : ghc
+       @$(RM) $@
+       echo '#!/bin/sh' >>$@
+       echo exec $(FPTOOLS_TOP_ABS)/ghc/driver/ghc -B$(FPTOOLS_TOP_ABS) $$\* >>$@
+       chmod 755 $@
+
+# -----------------------------------------------------------------------------
+# package configuration files...
+
+all :: package.conf package.conf.inplace
+
+pkgconf : Config.o Package.o PackageSrc.o
+       $(HC) $(HC_OPTS) $(LD_OPTS) Config.o Package.o PackageSrc.o -o pkgconf
+
+package.conf.inplace : pkgconf
+       ./pkgconf in-place >$@
+
+package.conf : pkgconf
+       ./pkgconf install >$@
+
+INSTALL_DATAS += package.conf
+
+CLEAN_FILES += pkgconf package.conf.inplace package.conf
+
+# -----------------------------------------------------------------------------
+# installation...
+
+INSTALL_PROGS = ghc
+
+override datadir=$(libdir)
+INSTALL_DATAS += ghc-usage.txt
+
+# -----------------------------------------------------------------------------
 
 include $(TOP)/mk/target.mk
-
-ghc.prl : $(TOP)/mk/version.mk
-
-#
-# Another hack (hmm..I can see a pattern developing here :-)
-# In ghc/driver, we create a symlink from ghc-<whatever-version> to
-# ghc, but we don't want this included in a source distribution.
-# We `solve' this by removing `ghc' from the dist tree here.
-dist ::
-       @echo "Patching dist tree: removing $(SRC_DIST_DIR)/ghc symlink"
-       $(RM) $(SRC_DIST_DIR)/ghc
diff --git a/ghc/driver/Package.hs b/ghc/driver/Package.hs
new file mode 100644 (file)
index 0000000..f064f62
--- /dev/null
@@ -0,0 +1,45 @@
+module Package where
+
+import Pretty
+
+data Package = Package {
+               import_dirs    :: [String],
+               library_dirs   :: [String],
+               libraries      :: [String],
+               include_dir    :: String,
+               c_include      :: String,
+               package_deps   :: [String],
+               extra_ghc_opts :: String,
+               extra_cc_opts  :: String,
+               extra_ld_opts  :: String
+               }
+  deriving (Read, Show)
+
+pprPackage :: [(String,Package)] -> String
+pprPackage pkgs = render (brackets (vcat (punctuate comma (map pprPkg pkgs))))
+
+pprPkg (name, (Package
+       { import_dirs    = import_dirs    
+       , library_dirs   = library_dirs   
+       , libraries      = libraries      
+       , include_dir    = include_dir    
+       , c_include      = c_include      
+       , package_deps   = package_deps   
+       , extra_ghc_opts = extra_ghc_opts 
+       , extra_cc_opts  = extra_cc_opts  
+       , extra_ld_opts  = extra_ld_opts   }))
+   = parens ( 
+       text (show name) <> comma
+    <+> text "Package" <+> braces (
+       vcat [
+          text "import_dirs = "    <> text (show import_dirs) <> comma,
+          text "library_dirs = "   <> text (show library_dirs) <> comma,
+          text "libraries = "      <> text (show libraries) <> comma,
+          text "include_dir = "    <> text (show include_dir) <> comma,
+          text "c_include = "      <> text (show c_include) <> comma,
+          text "package_deps = "   <> text (show package_deps) <> comma,
+          text "extra_ghc_opts = " <> text (show extra_ghc_opts) <> comma,
+          text "extra_cc_opts = "  <> text (show extra_cc_opts) <> comma,
+          text "extra_ld_opts = "  <> text (show extra_ld_opts)
+       ])
+    )
diff --git a/ghc/driver/PackageSrc.hs b/ghc/driver/PackageSrc.hs
new file mode 100644 (file)
index 0000000..5395b05
--- /dev/null
@@ -0,0 +1,312 @@
+module Main (main) where
+
+import IOExts
+import IO
+import System
+import Config
+import Package
+
+main = do
+  args <- getArgs
+  case args of
+       [ "install"  ] -> do { putStr (pprPackage (package_details True)) }
+       [ "in-place" ] -> do { putStr (pprPackage (package_details False)) }
+       _ -> do hPutStr stderr "usage: pkgconf (install | in-place)\n"
+               exitWith (ExitFailure 1)
+
+package_details :: Bool -> [(String,Package)]
+package_details installing =
+ [
+      ( "gmp", -- GMP is at the bottom of the heap
+       Package {
+       import_dirs    = [],
+       library_dirs   = if _HaveLibGmp == "YES"
+                            then []
+                            else if installing 
+                                  then [ _libdir ]
+                                  else [ ghc_src_dir _GHC_RUNTIME_DIR ++ "/gmp" ],
+       libraries      = [ "gmp" ],
+       include_dir    = "",
+       c_include      = "",
+       package_deps   = [],
+       extra_ghc_opts = "",
+       extra_cc_opts  = "",
+       extra_ld_opts  = ""
+       }
+       ),
+
+      ( "rts", -- The RTS is just another package!
+       Package {
+       import_dirs    = [],
+       library_dirs   = [ if installing 
+                             then _libdir
+                             else ghc_src_dir _GHC_RUNTIME_DIR ],
+       libraries      = [ "HSrts" ],
+       include_dir    = if installing 
+                           then "" 
+                           else ghc_src_dir _GHC_INCLUDE_DIR,
+       c_include      = "Stg.h",               -- ha!
+       package_deps   = [ "gmp" ],
+       extra_ghc_opts = "",
+       extra_cc_opts  = "",
+               -- the RTS forward-references to a bunch of stuff in the prelude,
+               -- so we force it to be included with special options to ld.
+       extra_ld_opts  = unwords [
+         "-u PrelMain_mainIO_closure",
+         "-u PrelBase_Izh_static_info",
+         "-u PrelBase_Czh_static_info",
+         "-u PrelFloat_Fzh_static_info",
+         "-u PrelFloat_Dzh_static_info",
+         "-u PrelAddr_Azh_static_info",
+         "-u PrelAddr_Wzh_static_info",
+         "-u PrelAddr_I64zh_static_info",
+         "-u PrelAddr_W64zh_static_info",
+         "-u PrelStable_StablePtr_static_info",
+        "-u PrelBase_Izh_con_info",
+         "-u PrelBase_Czh_con_info",
+         "-u PrelFloat_Fzh_con_info",
+         "-u PrelFloat_Dzh_con_info",
+         "-u PrelAddr_Azh_con_info",
+         "-u PrelAddr_Wzh_con_info",
+         "-u PrelAddr_I64zh_con_info",
+         "-u PrelAddr_W64zh_con_info",
+         "-u PrelStable_StablePtr_con_info",
+         "-u PrelBase_False_closure",
+         "-u PrelBase_True_closure",
+         "-u PrelPack_unpackCString_closure",
+         "-u PrelException_stackOverflow_closure",
+         "-u PrelException_heapOverflow_closure",
+         "-u PrelException_NonTermination_closure",
+         "-u PrelException_PutFullMVar_closure",
+         "-u PrelException_BlockedOnDeadMVar_closure",
+        "-u PrelWeak_runFinalizzerBatch_closure",
+         "-u __init_Prelude",
+         "-u __init_PrelMain"
+         ]
+       }
+      ),
+
+      ( "std", -- The Prelude & Standard Libraries
+       Package {
+       import_dirs    = [ if installing 
+                            then _libdir ++ "/imports/std"
+                            else ghc_src_dir _GHC_LIB_DIR ++ "/std" ],
+       library_dirs   = if installing 
+                          then [ _libdir ]
+                          else [ ghc_src_dir _GHC_LIB_DIR ++ "/std"
+                               , ghc_src_dir _GHC_LIB_DIR ++ "/std/cbits" ],
+       libraries      = [ "HSstd", "HSstd_cbits" ],
+       include_dir    = if installing 
+                          then "" 
+                          else ghc_src_dir _GHC_LIB_DIR ++ "/std/cbits",
+       c_include      = "HsStd.h",
+       package_deps   = [ "rts" ],
+       extra_ghc_opts = "",
+       extra_cc_opts  = "",
+       extra_ld_opts  = "-lm"
+       }
+       ),
+
+       ( "lang",
+        Package { 
+        import_dirs    = if installing 
+                          then [ _libdir ++ "/imports/lang" ]
+                          else [ _FPTOOLS_TOP_ABS ++ "/hslibs/lang"
+                               , _FPTOOLS_TOP_ABS ++ "/hslibs/lang/monads"],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/lang"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/lang/cbits" ],
+        libraries      = [ "HSlang", "HSlang_cbits" ],
+        include_dir    = if installing 
+                            then "" 
+                            else _FPTOOLS_TOP_ABS ++ "/hslibs/lang/cbits",
+        c_include      = "HsLang.h",
+        package_deps   = [],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = ""
+       }
+       ),
+
+       ( "concurrent",
+        Package {
+        import_dirs    = [ if installing 
+                               then _libdir ++ "/imports/concurrent"
+                               else _FPTOOLS_TOP_ABS ++ "/hslibs/concurrent" ],
+        library_dirs   = [ if installing 
+                               then _libdir
+                               else _FPTOOLS_TOP_ABS ++ "/hslibs/concurrent" ],
+        libraries      = [ "HSconcurrent" ],
+        include_dir    = if installing 
+                           then "" 
+                           else _FPTOOLS_TOP_ABS ++ "/hslibs/concurrent/cbits",
+        c_include      = "HsConcurrent.h",
+        package_deps   = [ "lang" ],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = ""
+       }
+       ),
+
+       ( "data",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/data" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/data"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/data/edison"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/data/edison/Assoc"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/data/edison/Coll"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/data/edison/Seq" ],
+        library_dirs   = if installing 
+                            then [_libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/data" ],
+        libraries      = [ "HSdata" ],
+        include_dir    = if installing 
+                            then "" 
+                            else _FPTOOLS_TOP_ABS ++ "/hslibs/data/cbits",
+        c_include      = "HsData.h",
+        package_deps   = [ "lang" ],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = ""
+       }
+       ),
+
+       ( "net",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/net" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/net" ],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/net"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/net/cbits" ],
+        libraries      = [ "HSnet", "HSnet_cbits" ],
+        include_dir    = if installing 
+                            then "" 
+                            else _FPTOOLS_TOP_ABS ++ "/hslibs/net/cbits",
+        c_include      = "HsNet.h",
+        package_deps   = [ "lang", "text" ],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = if postfixMatch "solaris2" _TARGETPLATFORM
+                               then "-lnsl -lsocket"
+                               else ""
+       }
+       ),
+
+       ( "posix",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/posix" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/posix" ],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/posix"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/posix/cbits" ],
+        libraries      = [ "HSposix", "HSposix_cbits" ],
+        include_dir    = if installing 
+                            then "" 
+                            else _FPTOOLS_TOP_ABS ++ "/hslibs/posix/cbits",
+        c_include      = "HsPosix.h",
+        package_deps   = [ "lang" ],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = ""
+       }
+       ),
+
+       ( "text",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/text" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/text" 
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/text/html" 
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/text/haxml/lib" 
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/text/parsec" ],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/text"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/text/cbits" ],
+        libraries      = [ "HStext", "HStext_cbits" ],
+        include_dir    = if installing 
+                            then "" 
+                            else _FPTOOLS_TOP_ABS ++ "/hslibs/text/cbits",
+        c_include      = "HsText.h",
+        package_deps   = [ "lang", "data" ],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = ""
+       }
+       ),
+
+       ( "util",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/util" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/util"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/util/check" ],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/util"
+                                 , _FPTOOLS_TOP_ABS ++ "/hslibs/util/cbits" ],
+        libraries      = [ "HSutil", "HSutil_cbits" ],
+        include_dir    = if installing 
+                            then "" 
+                            else _FPTOOLS_TOP_ABS ++ "/hslibs/util/cbits",
+        c_include      = "HsUtil.h",
+        package_deps   = ["lang", "concurrent", "posix"],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = ""
+       }
+       ),
+
+       ( "win32",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/win32" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/win32/src" ],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hslibs/win32/src" ],
+        libraries      = [ "HSwin32" ],
+        include_dir    = "",
+        c_include      = "",           -- ???
+        package_deps   = ["lang"],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = "-luser32 -lgdi32"
+       }
+       ),
+
+       ( "com",
+        Package {
+        import_dirs    = if installing 
+                            then [ _libdir ++ "/imports/com" ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hdirect/lib" ],
+        library_dirs   = if installing 
+                            then [ _libdir ]
+                            else [ _FPTOOLS_TOP_ABS ++ "/hdirect/lib" ],
+        libraries      = [ "HScom" ],
+        include_dir    = "",
+        c_include      = "",           -- ???
+        package_deps   = [ "lang" ],
+        extra_ghc_opts = "",
+        extra_cc_opts  = "",
+        extra_ld_opts  = "-luser32 -lole32 -loleaut32 -ladvapi32"
+       }
+       )
+   ]
+
+ghc_src_dir path = _FPTOOLS_TOP_ABS ++ '/':_CURRENT_DIR ++ '/':path
+
+prefixMatch :: Eq a => [a] -> [a] -> Bool
+prefixMatch [] str = True
+prefixMatch pat [] = False
+prefixMatch (p:ps) (s:ss) | p == s    = prefixMatch ps ss
+                         | otherwise = False
+
+postfixMatch :: String -> String -> Bool
+postfixMatch pat str = prefixMatch (reverse pat) (reverse str)
diff --git a/ghc/driver/ghc-asm.lprl b/ghc/driver/ghc-asm.lprl
deleted file mode 100644 (file)
index d15003b..0000000
+++ /dev/null
@@ -1,1501 +0,0 @@
-%************************************************************************
-%*                                                                     *
-\section[Driver-asm-fiddling]{Fiddling with assembler files}
-%*                                                                     *
-%************************************************************************
-
-Tasks:
-\begin{itemize}
-\item
-Utterly stomp out C functions' prologues and epilogues; i.e., the
-stuff to do with the C stack.
-\item
-Any other required tidying up.
-\end{itemize}
-
-HPPA specific notes:
-\begin{itemize}
-\item
-The HP linker is very picky about symbols being in the appropriate
-space (code vs. data).  When we mangle the threaded code to put the
-info tables just prior to the code, they wind up in code space
-rather than data space.  This means that references to *_info from
-un-mangled parts of the RTS (e.g. unthreaded GC code) get
-unresolved symbols.  Solution:  mini-mangler for .c files on HP.  I
-think this should really be triggered in the driver by a new -rts
-option, so that user code doesn't get mangled inappropriately.
-\item
-With reversed tables, jumps are to the _info label rather than to
-the _entry label.  The _info label is just an address in code
-space, rather than an entry point with the descriptive blob we
-talked about yesterday.  As a result, you can't use the call-style
-JMP_ macro.  However, some JMP_ macros take _info labels as targets
-and some take code entry points within the RTS.  The latter won't
-work with the goto-style JMP_ macro.  Sigh.  Solution: Use the goto
-style JMP_ macro, and mangle some more assembly, changing all
-"RP'literal" and "LP'literal" references to "R'literal" and
-"L'literal," so that you get the real address of the code, rather
-than the descriptive blob.  Also change all ".word P%literal"
-entries in info tables and vector tables to just ".word literal,"
-for the same reason.  Advantage: No more ridiculous call sequences.
-\end{itemize}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Constants for various architectures}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub init_TARGET_STUFF {
-
-    #--------------------------------------------------------#
-    if ( $TargetPlatform =~ /^alpha-.*-.*/ ) {
-
-    $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
-    $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^\$C(\d+):$'; # regexp for what such a lbl looks like
-    $T_POST_LBL            = ':';
-
-    $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.(globl|ent)\s+\S+|\#.*|\.(file|loc)\s+\S+\s+\S+|\.text|\.r?data)\n)';
-    $T_COPY_DIRVS   = '^\s*(\#|\.(file|globl|ent|loc))';
-
-    $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
-    $T_DOT_WORD            = '\.quad';
-    $T_DOT_GLOBAL   = '^\t\.globl';
-    $T_HDR_literal  = "\.rdata\n\t\.align 3\n";
-    $T_HDR_misc            = "\.text\n\t\.align 3\n";
-    $T_HDR_data            = "\.data\n\t\.align 3\n";
-    $T_HDR_consist  = "\.text\n";
-    $T_HDR_closure  = "\.data\n\t\.align 3\n";
-    $T_HDR_srt      = "\.text\n\t\.align 3\n";
-    $T_HDR_info            = "\.text\n\t\.align 3\n";
-    $T_HDR_entry    = "\.text\n\t\.align 3\n";
-    $T_HDR_fast            = "\.text\n\t\.align 3\n";
-    $T_HDR_vector   = "\.text\n\t\.align 3\n";
-    $T_HDR_direct   = "\.text\n\t\.align 3\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^hppa/ ) {
-
-    $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
-    $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^L\$C(\d+)$'; # regexp for what such a lbl looks like
-    $T_POST_LBL            = '';
-
-    $T_MOVE_DIRVS   = '^((\s+\.(IMPORT|EXPORT|PARAM).*|\s+\.align\s+\d+|\s+\.(SPACE|SUBSPA)\s+\S+|\s*)\n)';
-    $T_COPY_DIRVS   = '^\s+\.(IMPORT|EXPORT)';
-
-    $T_hsc_cc_PAT   = '\.STRING.*\)(hsc|cc) (.*)\\\\x09(.*)\\\\x00"';
-    $T_DOT_WORD            = '\.(blockz|word|half|byte)';
-    $T_DOT_GLOBAL   = '^\s+\.EXPORT';
-    $T_HDR_literal  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
-    $T_HDR_misc            = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
-    $T_HDR_data            = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
-    $T_HDR_consist  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
-    $T_HDR_closure  = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
-    $T_HDR_srt      = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
-    $T_HDR_info            = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
-    $T_HDR_entry    = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
-    $T_HDR_fast            = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
-    $T_HDR_vector   = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
-    $T_HDR_direct   = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^i386-.*-(linuxaout|freebsd2|netbsd|nextstep3|cygwin32|mingw32)$/ ) {
-                               # NeXT added but not tested. CaS
-
-    $T_STABBY      = 1; # 1 iff .stab things (usually if a.out format)
-    $T_US          = '_'; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = '^#'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^LC(\d+):$';
-    $T_POST_LBL            = ':';
-    $T_X86_PRE_LLBL_PAT = 'L';
-    $T_X86_PRE_LLBL        = 'L';
-    $T_X86_BADJMP   = '^\tjmp [^L\*]';
-
-    $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.stab[^n].*|\.type\s+.*|\.size\s+.*)\n)';
-    $T_COPY_DIRVS   = '\.(globl|stab)';
-    $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
-    $T_DOT_WORD            = '\.(long|word|value|byte|space)';
-    $T_DOT_GLOBAL   = '\.globl';
-    $T_HDR_literal  = "\.text\n\t\.align 2\n";
-    $T_HDR_misc            = "\.text\n\t\.align 2,0x90\n";
-    $T_HDR_data            = "\.data\n\t\.align 2\n";
-    $T_HDR_consist  = "\.text\n";
-    $T_HDR_closure  = "\.data\n\t\.align 2\n";
-    $T_HDR_closure  = "\.data\n\t\.align 2\n\t.long 0\n" if ( $TargetPlatform =~ /.*-mingw32$/ );
-    $T_HDR_srt      = "\.text\n\t\.align 2\n";
-    $T_HDR_info            = "\.text\n\t\.align 2\n"; # NB: requires padding
-    $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
-    $T_HDR_fast            = "\.text\n\t\.align 2,0x90\n";
-    $T_HDR_vector   = "\.text\n\t\.align 2\n"; # NB: requires padding
-    $T_HDR_direct   = "\.text\n\t\.align 2,0x90\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^i386-.*-(solaris2|linux|freebsd|netbsd_elf)$/ ) {
-
-    $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
-    $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = # regexp that says what comes before APP/NO_APP
-                     ($TargetPlatform =~ /-(linux|freebsd|netbsd_elf)$/) ? '#' : '/' ;
-    $T_CONST_LBL    = '^\.LC(\d+):$'; # regexp for what such a lbl looks like
-    $T_POST_LBL            = ':';
-    $T_X86_PRE_LLBL_PAT = '\.L';
-    $T_X86_PRE_LLBL        = '.L';
-    $T_X86_BADJMP   = '^\tjmp [^\.\*]';
-
-    $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.Lfe.*\n\t\.size\s+.*|\.size\s+.*|\.ident.*)\n)';
-    $T_COPY_DIRVS   = '\.(globl)';
-
-    if ( $TargetPlatform =~ /freebsd|netbsd_elf/ ) {
-        $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
-    } else {
-        $T_hsc_cc_PAT   = '\.string.*\)(hsc|cc) (.*)\\\\t(.*)"';
-    }
-
-    $T_DOT_WORD            = '\.(long|value|byte|zero)';
-    $T_DOT_GLOBAL   = '\.globl';
-    $T_HDR_literal  = "\.section\t\.rodata\n"; # or just use .text??? (WDP 95/11)
-    $T_HDR_misc            = "\.text\n\t\.align 4\n";
-    $T_HDR_data            = "\.data\n\t\.align 4\n"; # ToDo: change align??
-    $T_HDR_consist  = "\.text\n";
-    $T_HDR_closure  = "\.data\n\t\.align 4\n"; # ToDo: change align?
-    $T_HDR_srt      = "\.text\n\t\.align 4\n"; # ToDo: change align?
-    $T_HDR_info            = "\.text\n\t\.align 4\n"; # NB: requires padding
-    $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
-    $T_HDR_fast            = "\.text\n\t\.align 4\n";
-    $T_HDR_vector   = "\.text\n\t\.align 4\n"; # NB: requires padding
-    $T_HDR_direct   = "\.text\n\t\.align 4\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^m68k-.*-sunos4/ ) {
-
-    $T_STABBY      = 1; # 1 iff .stab things (usually if a.out format)
-    $T_US          = '_'; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = '^# MAY NOT APPLY'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^LC(\d+):$';
-    $T_POST_LBL            = ':';
-
-    $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.proc\s+\d+|\.const|\.cstring|\.globl\s+\S+|\.text|\.data|\.even|\.stab[^n].*)\n)';
-    $T_COPY_DIRVS   = '\.(globl|proc|stab)';
-    $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
-
-    $T_DOT_WORD            = '\.long';
-    $T_DOT_GLOBAL   = '\.globl';
-    $T_HDR_literal  = "\.text\n\t\.even\n";
-    $T_HDR_misc            = "\.text\n\t\.even\n";
-    $T_HDR_data            = "\.data\n\t\.even\n";
-    $T_HDR_consist  = "\.text\n";
-    $T_HDR_closure  = "\.data\n\t\.even\n";
-    $T_HDR_srt      = "\.text\n\t\.even\n";
-    $T_HDR_info            = "\.text\n\t\.even\n";
-    $T_HDR_entry    = "\.text\n\t\.even\n";
-    $T_HDR_fast            = "\.text\n\t\.even\n";
-    $T_HDR_vector   = "\.text\n\t\.even\n";
-    $T_HDR_direct   = "\.text\n\t\.even\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^mips-.*/ ) {
-
-    $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
-    $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = '^\s*#'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^\$LC(\d+):$'; # regexp for what such a lbl looks like
-    $T_POST_LBL            = ':';
-
-    $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.(globl|ent)\s+\S+|\.text|\.r?data)\n)';
-    $T_COPY_DIRVS   = '\.(globl|ent)';
-
-    $T_hsc_cc_PAT   = 'I WAS TOO LAZY TO DO THIS BIT (WDP 95/05)';
-    $T_DOT_WORD            = '\.word';
-    $T_DOT_GLOBAL   = '^\t\.globl';
-    $T_HDR_literal  = "\t\.rdata\n\t\.align 2\n";
-    $T_HDR_misc            = "\t\.text\n\t\.align 2\n";
-    $T_HDR_data            = "\t\.data\n\t\.align 2\n";
-    $T_HDR_consist  = 'TOO LAZY TO DO THIS TOO';
-    $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
-    $T_HDR_srt      = "\t\.text\n\t\.align 2\n";
-    $T_HDR_info            = "\t\.text\n\t\.align 2\n";
-    $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
-    $T_HDR_fast            = "\t\.text\n\t\.align 2\n";
-    $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
-    $T_HDR_direct   = "\t\.text\n\t\.align 2\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^powerpc-.*|^rs6000-.*/ ) {
-
-    $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
-    $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = 'NOT APPLICABLE'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = 'NOT APPLICABLE'; # regexp for what such a lbl looks like
-    $T_POST_LBL            = ':';
-
-    $T_MOVE_DIRVS   = '^(\s*(\.toc|\.align \d+|\.csect \S+|\t\.?l?globl \S+)\n)';
-    $T_COPY_DIRVS   = '\.(l?globl)';
-
-    $T_hsc_cc_PAT   = '\.byte.*\)(hsc|cc) (.*)"\n\t\.byte \d+\n\t\.byte "(.*)"\n\t\.byte \d+';
-    $T_DOT_WORD            = '\.long';
-    $T_DOT_GLOBAL   = '\.globl';
-    $T_HDR_toc      = "\.toc\n";
-    $T_HDR_literal  = "\.csect .data[RW]\n\t\.align 2\n";              #not RO!?
-    $T_HDR_misc            = "# misc\n\.csect \.text[PR]\n\t\.align 2\n";
-    $T_HDR_data            = "# data\n\.csect \.data[RW]\n\t\.align 2\n";
-    $T_HDR_consist  = "# consist\n\.csect \.data[RW]\n\t\.align 2\n";
-    $T_HDR_closure  = "# closure\n\.csect \.data[RW]\n\t\.align 2\n";
-    $T_HDR_srt      = "# closure\n\.csect \.data[RW]\n\t\.align 2\n";
-    $T_HDR_info            = "# info\n\.csect \.data[RW]\n\t\.align 2\n"; #not RO!?
-    $T_HDR_entry    = "# entry\n\.csect \.text[PR]\n\t\.align 2\n";
-    $T_HDR_fast            = "# fast\n\.csect \.text[PR]\n\t\.align 2\n";
-    $T_HDR_vector   = "# vector\n\.csect \.data[RW]\n\t\.align 2\n"; #not RO!?
-    $T_HDR_direct   = "# direct\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^sparc-.*-solaris2/ ) {
-
-    $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
-    $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = 'DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^\.LLC(\d+):$'; # regexp for what such a lbl looks like
-    $T_POST_LBL            = ':';
-
-    $T_MOVE_DIRVS   = '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\.text|\.data|\.stab.*|\.section.*|\s+\.type.*|\s+\.size.*)\n)';
-    $T_COPY_DIRVS   = '\.(global|proc|stab)';
-
-    $T_hsc_cc_PAT   = '\.asciz.*\)(hsc|cc) (.*)\\\\t(.*)"';
-    $T_DOT_WORD            = '\.(word|byte|half|skip|uahalf|uaword)';
-    $T_DOT_GLOBAL   = '^\t\.global';
-    $T_HDR_literal  = "\.text\n\t\.align 8\n";
-    $T_HDR_misc            = "\.text\n\t\.align 4\n";
-    $T_HDR_data            = "\.data\n\t\.align 8\n";
-    $T_HDR_consist  = "\.text\n";
-    $T_HDR_closure  = "\.data\n\t\.align 4\n";
-    $T_HDR_srt      = "\.data\n\t\.align 4\n";
-    $T_HDR_info            = "\.text\n\t\.align 4\n";
-    $T_HDR_entry    = "\.text\n\t\.align 4\n";
-    $T_HDR_fast            = "\.text\n\t\.align 4\n";
-    $T_HDR_vector   = "\.text\n\t\.align 4\n";
-    $T_HDR_direct   = "\.text\n\t\.align 4\n";
-
-    #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^sparc-.*-sunos4/ ) {
-
-    $T_STABBY      = 1; # 1 iff .stab things (usually if a.out format)
-    $T_US          = '_'; # _ if symbols have an underscore on the front
-    $T_PRE_APP     = '^# DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
-    $T_CONST_LBL    = '^LC(\d+):$';
-    $T_POST_LBL            = ':';
-
-    $T_MOVE_DIRVS   = '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\.text|\.data|\.stab.*)\n)';
-    $T_COPY_DIRVS   = '\.(global|proc|stab)';
-    $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
-
-    $T_DOT_WORD            = '\.word';
-    $T_DOT_GLOBAL   = '^\t\.global';
-    $T_HDR_literal  = "\.text\n\t\.align 8\n";
-    $T_HDR_misc            = "\.text\n\t\.align 4\n";
-    $T_HDR_data            = "\.data\n\t\.align 8\n";
-    $T_HDR_consist  = "\.text\n";
-    $T_HDR_closure  = "\.data\n\t\.align 4\n";
-    $T_HDR_srt      = "\.data\n\t\.align 4\n";
-    $T_HDR_info            = "\.text\n\t\.align 4\n";
-    $T_HDR_entry    = "\.text\n\t\.align 4\n";
-    $T_HDR_fast            = "\.text\n\t\.align 4\n";
-    $T_HDR_vector   = "\.text\n\t\.align 4\n";
-    $T_HDR_direct   = "\.text\n\t\.align 4\n";
-
-    #--------------------------------------------------------#
-    } else {
-       print STDERR "$Pgm: don't know how to mangle assembly language for: $TargetPlatform\n";
-       exit 1;
-    }
-
-if ( 0 ) {
-print STDERR "T_STABBY: $T_STABBY\n";
-print STDERR "T_US: $T_US\n";
-print STDERR "T_PRE_APP: $T_PRE_APP\n";
-print STDERR "T_CONST_LBL: $T_CONST_LBL\n";
-print STDERR "T_POST_LBL: $T_POST_LBL\n";
-if ( $TargetPlatform =~ /^i386-/ ) {
-    print STDERR "T_X86_PRE_LLBL_PAT: $T_X86_PRE_LLBL_PAT\n";
-    print STDERR "T_X86_PRE_LLBL: $T_X86_PRE_LLBL\n";
-    print STDERR "T_X86_BADJMP: $T_X86_BADJMP\n";
-}
-print STDERR "T_MOVE_DIRVS: $T_MOVE_DIRVS\n";
-print STDERR "T_COPY_DIRVS: $T_COPY_DIRVS\n";
-print STDERR "T_hsc_cc_PAT: $T_hsc_cc_PAT\n";
-print STDERR "T_DOT_WORD: $T_DOT_WORD\n";
-print STDERR "T_HDR_literal: $T_HDR_literal\n";
-print STDERR "T_HDR_misc: $T_HDR_misc\n";
-print STDERR "T_HDR_data: $T_HDR_data\n";
-print STDERR "T_HDR_consist: $T_HDR_consist\n";
-print STDERR "T_HDR_closure: $T_HDR_closure\n";
-print STDERR "T_HDR_info: $T_HDR_info\n";
-print STDERR "T_HDR_entry: $T_HDR_entry\n";
-print STDERR "T_HDR_fast: $T_HDR_fast\n";
-print STDERR "T_HDR_vector: $T_HDR_vector\n";
-print STDERR "T_HDR_direct: $T_HDR_direct\n";
-}
-
-}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Mangle away}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub mangle_asm {
-    local($in_asmf, $out_asmf) = @_;
-
-    # multi-line regexp matching:
-    local($*) = 1;
-    local($i, $c);
-
-
-    &init_TARGET_STUFF();
-    &init_FUNNY_THINGS();
-
-    # perl4 on alphas SEGVs when give ${foo} substitutions in patterns.
-    # To avoid them we declare some locals that allows to avoid using curlies.
-    local($TUS)      = ${T_US};
-    local($TPOSTLBL) = ${T_POST_LBL};
-    local($TMOVEDIRVS) = ${T_MOVE_DIRVS};
-    local($TPREAPP)    = ${T_PRE_APP};
-    local($TCOPYDIRVS) = ${T_COPY_DIRVS};
-    local($TDOTWORD)   = ${T_DOT_WORD};
-
-    open(INASM, "< $in_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
-    open(OUTASM,"> $out_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
-
-    # read whole file, divide into "chunks":
-    #  record some info about what we've found...
-
-    @chk = ();         # contents of the chunk
-    $numchks = 0;      # number of them
-    @chkcat = ();      # what category of thing in each chunk
-    @chksymb = ();     # what symbol(base) is defined in this chunk
-    %slowchk = ();     # ditto, its regular "slow" entry code
-    %fastchk = ();     # ditto, fast entry code
-    %closurechk = ();  # ditto, the (static) closure
-    %srtchk = ();      # ditto, its SRT (for top-level things)
-    %infochk = ();     # given a symbol base, say what chunk its info tbl is in
-    %vectorchk = ();    # ditto, return vector table
-    $EXTERN_DECLS = '';        # .globl <foo> .text (MIPS only)
-
-    $i = 0; $chkcat[0] = 'misc'; $chk[0] = '';
-
-    while (<INASM>) {
-       next if $T_STABBY && /^\.stab.*$TUS[@]?__stg_split_marker/o;
-       next if $T_STABBY && /^\.stab.*ghc.*c_ID/;
-       next if /^\t\.def.*endef$/;
-       next if /$TPREAPP(NO_)?APP/o; 
-       next if /^;/ && $TargetPlatform =~ /^hppa/;
-
-       next if /(^$|^\t\.file\t|^ # )/ && $TargetPlatform =~ /^(mips|powerpc|rs6000)-/;
-
-       last if /^_section_\.text:$/ && $TargetPlatform =~ /^powerpc-|^rs6000-/;
-
-       if ( $TargetPlatform =~ /^mips-/ 
-         && /^\t\.(globl \S+ \.text|comm\t)/ ) {
-           $EXTERN_DECLS .= $_ unless /(__DISCARD__|\b(PK_|ASSIGN_)(FLT|DBL)\b)/;
-  
-       # As a temporary solution for compiling "foreign export" declarations,
-       # we use global variables to pass arguments from C to STG land.
-       # These declarations live in the .hc file and not in the generated C
-       # stub file, so we let them pass through here.
-       } elsif ( /^\t\.comm\t__fexp_.*$/ ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'data';
-           $chksymb[$i] = '';
-
-       } elsif ( /^\s+/ ) { # most common case first -- a simple line!
-           # duplicated from the bottom
-
-           $chk[$i] .= $_;
-
-       } elsif ( /\.\.ng:$/ && $TargetPlatform =~ /^alpha-/ ) {
-           # Alphas: Local labels not to be confused with new chunks
-           $chk[$i] .= $_;
-  
-       # NB: all the rest start with a non-space
-
-       } elsif ( $TargetPlatform =~ /^mips-/
-              && /^\d+:/ ) { # a funny-looking very-local label
-           $chk[$i] .= $_;
-
-       } elsif ( /$T_CONST_LBL/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'literal';
-           $chksymb[$i] = $1;
-
-       } elsif ( /^$TUS[@]?__stg_split_marker(\d*)$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'splitmarker';
-           $chksymb[$i] = $1;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_info$TPOSTLBL[@]?$/o ) {
-           $symb = $1;
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'infotbl';
-           $chksymb[$i] = $symb;
-
-           die "Info table already? $symb; $i\n" if defined($infochk{$symb});
-
-           $infochk{$symb} = $i;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_(entry|ret)$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'slow';
-           $chksymb[$i] = $1;
-
-           $slowchk{$1} = $i;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_fast\d*$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'fast';
-           $chksymb[$i] = $1;
-
-           $fastchk{$1} = $i;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_closure$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'closure';
-           $chksymb[$i] = $1;
-
-           $closurechk{$1} = $i;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_srt$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'srt';
-           $chksymb[$i] = $1;
-
-           $srtchk{$1} = $i;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_ct$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'data';
-           $chksymb[$i] = '';
-
-       } elsif ( /^$TUS[@]?ghc.*c_ID$TPOSTLBL/o ) {
-           $chk[++$i]  = $_;
-           $chkcat[$i] = 'consist';
-
-       } elsif ( /^($TUS[@]?__gnu_compiled_c|gcc2_compiled\.)$TPOSTLBL/o ) {
-           ; # toss it
-
-       } elsif ( /^$TUS[A-Za-z0-9_]+\.\d+$TPOSTLBL[@]?$/o
-              || /^$TUS[@]?.*_CAT$TPOSTLBL[@]?$/o              # PROF: _entryname_CAT
-              || /^$TUS[@]?.*_done$TPOSTLBL[@]?$/o             # PROF: _module_done
-              || /^$TUS[@]?_module_registered$TPOSTLBL[@]?$/o  # PROF: _module_registered
-              ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'data';
-           $chksymb[$i] = '';
-
-       } elsif ( /^([A-Za-z0-9_]+)\s+\.comm/ && $TargetPlatform =~ /^hppa/ ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'bss';
-           $chksymb[$i] = '';
-
-       } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ && /^LC\.\.([0-9]+)/ ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'toc';
-           $chksymb[$i] = $1;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_cc(s)?$TPOSTLBL[@]?$/o ) {
-            # all CC_ symbols go in the data section...
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'data';
-           $chksymb[$i] = '';
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_(alt|dflt)$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'misc';
-           $chksymb[$i] = '';
-           #$symbtmp = $1;
-            #$chksymb[$i] = $symbtmp if ($TargetPlatform =~ /^powerpc-|^rs6000-/) ; #rm andre
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_vtbl$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'vector';
-           $chksymb[$i] = $1;
-
-           $vectorchk{$1} = $i;
-
-       # As a temporary solution for compiling "foreign export" declarations,
-       # we use global variables to pass arguments from C to STG land.
-       # These declarations live in the .hc file and not in the generated C
-       # stub file, so we let them pass through here.
-       } elsif ( /^[\t ]+\.comm[\t ]+__fexp_.*$/ ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'data';
-           $chksymb[$i] = '';
-
-       } elsif ( $TargetPlatform =~ /^i386-.*-solaris2/
-            &&   /^(_uname|uname|stat|fstat):/ ) {
-           # for some utterly bizarre reason, this platform
-           # likes to drop little local C routines with these names
-           # into each and every .o file that #includes the
-           # relevant system .h file.  Yuck.  We just don't
-           # tolerate them in .hc files (which we are processing
-           # here).  If you need to call one of these things from
-           # Haskell, make a call to your own C wrapper, then
-           # put that C wrapper (which calls one of these) in a
-           # plain .c file.  WDP 95/12
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'toss';
-           $chksymb[$i] = $1;
-
-       } elsif ( /^$TUS[@]?[A-Za-z0-9_]/o
-               && ( $TargetPlatform !~ /^hppa/ # need to avoid local labels in this case
-                  || ! /^L\$\d+$/ )
-               && ( $TargetPlatform !~ /^powerpc|^rs6000/ # ditto
-                  || ! /^(L\.\.\d+|LT\.\..*):$/ ) ) {
-           local($thing);
-           chop($thing = $_);
-           print "Funny global thing?: $_"
-               unless $KNOWN_FUNNY_THING{$thing}
-                   || /^$TUS[@]?stg_.*$TPOSTLBL[@]?$/o    # RTS internals
-                   || /^$TUS[@]__fexp_.*$TPOSTLBL$/o      # foreign export
-                   || /^$TUS[@]?__init.*$TPOSTLBL$/o      # __init<module>
-                   || /^$TUS[@]?.*_btm$TPOSTLBL$/o        # large bitmaps
-                   || /^$TUS[@]?.*_closure_tbl$TPOSTLBL$/o; # closure tables
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'misc';
-            if ($TargetPlatform =~ /^powerpc-|^rs6000-/) 
-              { $chksymb[$i] = $thing; }
-           else { $chksymb[$i] = ''; };
-
-       } else { # simple line (duplicated at the top)
-
-           $chk[$i] .= $_;
-       }
-    }
-    $numchks = $#chk + 1;
-
-    # the division into chunks is imperfect;
-    # we throw some things over the fence into the next
-    # chunk.
-    #
-    # also, there are things we would like to know
-    # about the whole module before we start spitting
-    # output.
-
-    local($FIRST_MANGLABLE) = ($TargetPlatform =~ /^(alpha-|hppa|mips-)/) ? 1 : 0;
-
-#   print STDERR "first chunk to mangle: $FIRST_MANGLABLE\n";
-
-    # Alphas: NB: we start meddling at chunk 1, not chunk 0
-    # The first ".rdata" is quite magical; as of GCC 2.7.x, it
-    # spits a ".quad 0" in after the v first ".rdata"; we
-    # detect this special case (tossing the ".quad 0")!
-    local($magic_rdata_seen) = 0;
-  
-    # HPPAs, MIPSen: also start medding at chunk 1
-
-    if ($TargetPlatform =~ /^powerpc|^rs6000/) {
-       print OUTASM $T_HDR_toc; # yes, we have to put a .toc 
-                                # in the beginning of every file!
-    %tocequiv = ();          # maps toc symbol number to toc symbol
-    %revtocequiv = ();       # maps toc symbol to toc symbol number
-    for ($i = 1; $i < $numchks; $i++) {
-       $chk[$i] =~ s/\[RW\]//g;
-       $chk[$i] =~ s/\[DS\]//g;
-       $chk[$i] =~ s/^\.csect .*\[DS\]$//g;
-
-       if ( $chkcat[$i] eq 'toc' && $chk[$i] !~ /\.byte/ )
-#ToDo: instead of all these changes, just fix mangle_powerpc_tailjump and delete/ignore these tocs?
-          { $chk[$i] =~ s/$T_MOVE_DIRVS//g;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(\S+_fast\d+)/\t\.tc \1\[TC\],\.\2/; 
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(\S+_entry)\n/\t\.tc \1\[TC\],\.\2\n/;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(ret_\S+)/\t\.tc \1\[TC\],\.\2/;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(alt_\S+)/\t\.tc \1\[TC\],\.\2/;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(vtbl_\S+)/\t\.tc \1\[TC\],\.\2/;
-
-             $tocnumber = $chksymb[$i];
-             $tocsymb = $chk[$i];
-             $tocsymb =~ s/^LC\.\.\d+:\n//;
-             $tocsymb =~ s/^\t\.tc \S+,(\S+)\n/\1/;
-             $tocequiv{$tocnumber} = $tocsymb;
-
-           } elsif ( $chkcat[$i] eq 'toc' && $chk[$i] =~ /\.byte/ ) {
-             $chkcat[$i] = 'literal';
-           }
-    }
-    };
-
-    for ($i = $FIRST_MANGLABLE; $i < $numchks; $i++) {
-       $c = $chk[$i]; # convenience copy
-
-#      print STDERR "\nCHK $i (BEFORE) (",$chkcat[$i],"):\n", $c;
-
-       # toss all prologue stuff; HPPA is pretty weird
-       # (see elsewhere)
-       $c = &mash_hppa_prologue($c) if $TargetPlatform =~ /^hppa/;
-
-       # be slightly paranoid to make sure there's
-       # nothing surprising in there
-       if ( $c =~ /--- BEGIN ---/ ) {
-           if (($p, $r) = split(/--- BEGIN ---/, $c)) {
-
-               if ($TargetPlatform =~ /^i386-/) {
-                   $p =~ s/^\tpushl \%edi\n//;
-                   $p =~ s/^\tpushl \%esi\n//;
-                   $p =~ s/^\tpushl \%ebx\n//;
-                   $p =~ s/^\tsubl \$\d+,\%esp\n//;
-                    $p =~ s/^\tmovl \$\d+,\%eax\n\tcall __alloca\n// if ($TargetPlatform =~ /^.*-cygwin32/);
-               } elsif ($TargetPlatform =~ /^m68k-/) {
-                   $p =~ s/^\tlink a6,#-?\d.*\n//;
-                   $p =~ s/^\tpea a6@\n\tmovel sp,a6\n//;    
-                               # The above showed up in the asm code,
-                               # so I added it here.
-                               # I hope it's correct.
-                               # CaS
-                   $p =~ s/^\tmovel d2,sp\@-\n//;
-                   $p =~ s/^\tmovel d5,sp\@-\n//; # SMmark.* only?
-                   $p =~ s/^\tmoveml \#0x[0-9a-f]+,sp\@-\n//; # SMmark.* only?
-               } elsif ($TargetPlatform =~ /^mips-/) {
-                   # the .frame/.mask/.fmask that we use is the same
-                   # as that produced by GCC for miniInterpret; this
-                   # gives GDB some chance of figuring out what happened
-                   $FRAME = "\t.frame\t\$sp,2168,\$31\n\t.mask\t0x90000000,-4\n\t.fmask\t0x00000000,0\n";
-                   $p =~ s/^\t\.(frame).*\n/__FRAME__/g;
-                   $p =~ s/^\t\.(mask|fmask).*\n//g;
-                   $p =~ s/^\t\.cprestore.*\n/\t\.cprestore 416\n/; # 16 + 100 4-byte args
-                   $p =~ s/^\tsubu\t\$sp,\$sp,\d+\n//;
-                   $p =~ s/^\tsw\t\$31,\d+\(\$sp\)\n//;
-                   $p =~ s/^\tsw\t\$fp,\d+\(\$sp\)\n//;
-                   $p =~ s/^\tsw\t\$28,\d+\(\$sp\)\n//;
-                   $p =~ s/__FRAME__/$FRAME/;
-               } elsif ($TargetPlatform =~ /^powerpc-|^rs6000/) {
-                   $p =~ s/^\tmflr 0\n//;
-                   $p =~ s/^\tstm \d+,-\d+\(1\)\n//;
-                   $p =~ s/^\tstw? 0,\d+\(1\)\n//g;
-                   $p =~ s/^\tstw? 1,\d+\(1\)\n//g; #mc
-                   $p =~ s/^\tlw?z 0,0\(1\)\n//g;   #mc
-                   $p =~ s/^\tstw?u 1,-\d+\(1\)\n//; 
-                   $p =~ s/^\tstw? \d+,-\d+\(1\)\n//g; 
-                   $p =~ s/^\tstfd \d+,-\d+\(1\)\n//g; 
-               } else {
-                   print STDERR "$Pgm: unknown prologue mangling? $TargetPlatform\n";
-               }
-
-               # HWL HACK: dont die, just print a warning
-               #print stderr  "HWL: this should die! Prologue junk?: $p\n" if $p =~ /^\t[^\.]/
-               #    && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
-               die "Prologue junk?: $p\n" if $p =~ /^\t[^\.]/
-                   && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
-
-               # glue together what's left
-               $c = $p . $r;
-               $c =~ s/\n\t\n/\n/; # junk blank line
-           }
-       }
-
-       if ( $TargetPlatform =~ /^mips-/ ) {
-           # MIPS: first, this basic sequence may occur "--- END ---" or not
-           $c =~ s/^\tlw\t\$31,\d+\(\$sp\)\n\taddu\t\$sp,\$sp,\d+\n\tj\t\$31\n\t\.end/\t\.end/;
-       }
-
-       # toss all epilogue stuff; again, paranoidly
-       if ( $c =~ /--- END ---/ ) {
-           if (($r, $e) = split(/--- END ---/, $c)) {
-               if ($TargetPlatform =~ /^i386-/) {
-                   $e =~ s/^\tret\n//;
-                   $e =~ s/^\tpopl \%edi\n//;
-                   $e =~ s/^\tpopl \%esi\n//;
-                   $e =~ s/^\tpopl \%ecx\n//;
-                   $e =~ s/^\taddl \$\d+,\%esp\n//;
-                   $e =~ s/^\tsubl \$-\d+,\%esp\n//;
-               } elsif ($TargetPlatform =~ /^m68k-/) {
-                   $e =~ s/^\tunlk a6\n//;
-                   $e =~ s/^\trts\n//;
-               } elsif ($TargetPlatform =~ /^mips-/) {
-                   $e =~ s/^\tlw\t\$31,\d+\(\$sp\)\n//;
-                   $e =~ s/^\tlw\t\$fp,\d+\(\$sp\)\n//;
-                   $e =~ s/^\taddu\t\$sp,\$sp,\d+\n//;
-                   $e =~ s/^\tj\t\$31\n//;
-               } elsif ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
-                   $e =~ s/^\taddi 1,1,\d+\n//;
-                   $e =~ s/^\tcal 1,\d+\(1\)\n//;
-                   $e =~ s/^\tlw?z? \d+,\d+\(1\)\n//; 
-                   $e =~ s/^\tmtlr 0\n//;
-                   $e =~ s/^\tbl?r\n//;
-               } else {
-                   print STDERR "$Pgm: unknown epilogue mangling? $TargetPlatform\n";
-               }
-               # HWL HACK: dont die, just print a warning
-               #print stderr "HWL: this should die! Epilogue junk?: $e\n" if $e =~ /^\t[^\.]/
-               #    && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
-               die "Epilogue junk?: $e\n" if $e =~ /^\t[^\.\n]/
-                   && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
-
-               # glue together what's left
-               $c = $r . $e;
-               $c =~ s/\n\t\n/\n/; # junk blank line
-           }
-       }
-
-       # On SPARCs, we don't do --- BEGIN/END ---, we just
-       # toss the register-windowing save/restore/ret* instructions
-       # directly:
-       if ( $TargetPlatform =~ /^sparc-/ ) {
-           $c =~ s/^\t(save.*|restore|ret|retl)\n//g;
-           # throw away PROLOGUE comments
-           $c =~ s/^\t!#PROLOGUE# 0\n\t!#PROLOGUE# 1\n//;
-       }
-
-       # On Alphas, the prologue mangling is done a little later (below)
-
-       # toss all calls to __DISCARD__
-       $c =~ s/^\t(call|jbsr|jal)\s+$TUS[@]?__DISCARD__\n//go;
-
-       # MIPS: that may leave some gratuitous asm macros around
-       # (no harm done; but we get rid of them to be tidier)
-       $c =~ s/^\t\.set\tnoreorder\n\t\.set\tnomacro\n\taddu\t(\S+)\n\t\.set\tmacro\n\t\.set\treorder\n/\taddu\t$1\n/
-           if $TargetPlatform =~ /^mips-/;
-
-       # toss stack adjustment after DoSparks
-       $c =~ s/^(\tjbsr _DoSparks\n)\taddqw #8,sp/$1/g
-               if $TargetPlatform =~ /^m68k-/; # this looks old...
-
-       if ( $TargetPlatform =~ /^alpha-/ &&
-          ! $magic_rdata_seen &&
-          $c =~ /^\s*\.rdata\n\t\.quad 0\n\t\.align \d\n/ ) {
-           $c =~ s/^\s*\.rdata\n\t\.quad 0\n\t\.align (\d)\n/\.rdata\n\t\.align $1\n/;
-           $magic_rdata_seen = 1;
-       }
-
-       # pick some end-things and move them to the next chunk
-
-       # pin a funny end-thing on (for easier matching):
-       $c .= 'FUNNY#END#THING';
-
-       while ( $c =~ /$TMOVEDIRVS[@]?FUNNY#END#THING/o ) {  # [@]? is a silly hack to avoid having to use curlies for T_PRE_APP
-                                                          # (this SEGVs perl4 on alphas, you see)
-
-           $to_move = $1;
-
-           # on x86 we try not to copy any directives into a literal
-           # chunk, rather we keep looking for the next real chunk.  This
-           # is because we get things like
-           #
-           #    .globl blah_closure
-           #    .LC32
-           #           .string "..."
-           #    blah_closure:
-           #           ...
-            #
-           if ( $TargetPlatform =~ /^i386/ && $to_move =~ /$TCOPYDIRVS/ ) {
-               $j = $i + 1;
-               while ( $j < $numchks  && $chk[$j] =~ /$T_CONST_LBL/) {
-                       $j++;
-               }
-               if ( $j < $numchks ) {
-                       $chk[$j] = $to_move . $chk[$j];
-               }
-           }
-
-           elsif ( $i < ($numchks - 1)
-             && ( $to_move =~ /$TCOPYDIRVS/
-               || ($TargetPlatform =~ /^hppa/ && $to_move =~ /align/ && $chkcat[$i+1] eq 'literal') )) {
-               $chk[$i + 1] = $to_move . $chk[$i + 1];
-               # otherwise they're tossed
-           }
-
-           $c =~ s/$TMOVEDIRVS[@]?FUNNY#END#THING/FUNNY#END#THING/o; # [@]? is a hack (see above)
-       }
-
-       if ( $TargetPlatform =~ /^alpha-/ && $c =~ /^\t\.ent\s+(\S+)/ ) {
-           $ent = $1;
-           # toss all prologue stuff, except for loading gp, and the ..ng address
-           if (($p, $r) = split(/^\t\.prologue/, $c)) {
-               if (($keep, $junk) = split(/\.\.ng:/, $p)) {
-                   $c = $keep . "..ng:\n";
-               } else {
-                   print STDERR "malformed code block ($ent)?\n"
-               }
-           }
-           $c .= "\t.frame \$30,0,\$26,0\n\t.prologue" . $r;
-       }
-  
-       $c =~ s/FUNNY#END#THING//;
-
-#      print STDERR "\nCHK $i (AFTER) (",$chkcat[$i],"):\n", $c;
-
-       $chk[$i] = $c; # update w/ convenience copy
-    }
-
-    if ( $TargetPlatform =~ /^alpha-/ ) {
-       # print out the header stuff first
-       $chk[0] =~ s/^(\t\.file.*)"(ghc\d+\.c)"/$1"$ifile_root.hc"/;
-       print OUTASM $chk[0];
-
-    } elsif ( $TargetPlatform =~ /^hppa/ ) {
-       print OUTASM $chk[0];
-
-    } elsif ( $TargetPlatform =~ /^mips-/ ) {
-       $chk[0] = "\t\.file\t1 \"$ifile_root.hc\"\n" . $chk[0];
-
-       # get rid of horrible "<dollar>Revision: .*$" strings
-       local(@lines0) = split(/\n/, $chk[0]);
-       local($z) = 0;
-       while ( $z <= $#lines0 ) {
-           if ( $lines0[$z] =~ /^\t\.byte\t0x24,0x52,0x65,0x76,0x69,0x73,0x69,0x6f$/ ) {
-               undef($lines0[$z]);
-               $z++;
-               while ( $z <= $#lines0 ) {
-                   undef($lines0[$z]);
-                   last if $lines0[$z] =~ /[,\t]0x0$/;
-                   $z++;
-               }
-           }
-           $z++;
-       }
-       $chk[0] = join("\n", @lines0);
-       $chk[0] =~ s/\n\n+/\n/;
-       print OUTASM $chk[0];
-    }
-
-    # print out all the literal strings next
-    for ($i = 0; $i < $numchks; $i++) {
-       if ( $chkcat[$i] eq 'literal' ) {
-           print OUTASM $T_HDR_literal, $chk[$i];
-           print OUTASM "; end literal\n" if $TargetPlatform =~ /^hppa/; # for the splitter
-
-           $chkcat[$i] = 'DONE ALREADY';
-       }
-    }
-
-    # on the HPPA, print out all the bss next
-    if ( $TargetPlatform =~ /^hppa/ ) {
-       for ($i = 1; $i < $numchks; $i++) {
-           if ( $chkcat[$i] eq 'bss' ) {
-               print OUTASM "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$BSS\$\n\t.align 4\n";
-               print OUTASM $chk[$i];
-
-               $chkcat[$i] = 'DONE ALREADY';
-           }
-       }
-    }
-
-    for ($i = $FIRST_MANGLABLE; $i < $numchks; $i++) {
-#      print STDERR "$i: cat $chkcat[$i], symb $chksymb[$i]\n";
-
-       next if $chkcat[$i] eq 'DONE ALREADY';
-
-       if ( $chkcat[$i] eq 'misc' ) {
-           if ($chk[$i] ne '') {
-               print OUTASM $T_HDR_misc;
-                if ($TargetPlatform =~ /^powerpc-|^rs6000/) { 
-                   $chksymb[$i] =~ s/://;
-#new                   if ($chksymb[$i] =~ /ret.*upd/ || $KNOWN_FUNNY_THING{$chksymb[$i]}
-#new                    || $chksymb[$i] =~ /^$.{T_US}_(PRIn|PRStart).*${T_POST_LBL}$/o )
-#new                      { print OUTASM "\t\.globl $chksymb[$i]\n"; }
-#                   if ($chksymb[$i] ne '' && $chksymb[$i] !~ /ret_[a-z]/ && $chksymb[$i] !~ /djn_[a-z]/) 
-                   if ($chksymb[$i] ne '')
-                       { print OUTASM "\t\.globl \.$chksymb[$i]\n"; };
-                   if ($chk[$i] =~ /TOC\[tc0\], 0\n/)
-                    { ($p, $r) = split(/TOC\[tc0\], 0\n/, $chk[$i]); $printDS = 1;}
-                   else { $r = $chk[$i]; $printDS = 0; };
-                   $chk[$i] = &mangle_powerpc_tailjump($r);
-                };
-               &print_doctored($chk[$i], 0);
-                if ($TargetPlatform =~ /^powerpc-|^rs6000-/ && $printDS) { 
-#ok                   if ($chksymb[$i] !~ /\__init_Main/) {
-                    print OUTASM "\.csect ${chksymb[$i]}[DS]\n";       
-                    print OUTASM "${p}TOC[tc0], 0\n";
-#ok                   }
-                }
-           }
-
-       } elsif ( $chkcat[$i] eq 'toss' ) {
-           print STDERR "*** NB: TOSSING code for $chksymb[$i] !!! ***\n";
-
-       } elsif ( $chkcat[$i] eq 'data' ) {
-           if ($chk[$i] ne '') {
-               print OUTASM $T_HDR_data;
-               print OUTASM $chk[$i];
-           }
-
-       } elsif ( $chkcat[$i] eq 'consist' ) {
-           if ( $chk[$i] =~ /$T_hsc_cc_PAT/o ) {
-               local($consist) = "$1.$2.$3";
-               $consist =~ s/,/./g;
-               $consist =~ s/\//./g;
-               $consist =~ s/-/_/g;
-               $consist =~ s/[^A-Za-z0-9_.]/ZZ/g; # ToDo: properly?
-               #
-               # Using a cygnus-2.7-96q4 gcc build on hppas, the 
-               # consistency chunk for ghc_cc_ID often (but not always!)
-               # gets lumped with a bunch of .IMPORT directives containing info on
-               # the code or data space nature of external symbols. We can't
-               # toss these, so once the consistency ID has been turned into
-               # a representable symbol, we substitute it for the symbol
-               # that the string was attached to in the first place (ghc_cc_ID.)
-               # (The original string is also substituted away.)
-               #
-               # This change may affect the code output on other platforms in
-               # adverse ways, hence we restrict this hack hppa targets only.
-               #
-               #    -- 2/98 SOF
-               if ( $TargetPlatform =~ /^hppa/ )  {
-                       $chk[$i] =~ s/^$TUS[@]?ghc.*c_ID$TPOSTLBL/$consist/o;
-                       $chk[$i] =~ s/\t$T_hsc_cc_PAT/$T_HDR_misc/o;
-                       $consist = $chk[$i]; #clumsily
-                }
-               print OUTASM $T_HDR_consist, "${consist}${T_POST_LBL}\n";
-
-           } elsif ( $TargetPlatform !~ /^(mips)-/ ) { # we just don't try in those case (ToDo)
-               # on mips: consistency string is just a v
-               # horrible bunch of .bytes,
-               # which I am too lazy to sort out (WDP 95/05)
-
-               print STDERR "Couldn't grok consistency: ", $chk[$i];
-           }
-
-       } elsif ( $chkcat[$i] eq 'splitmarker' ) {
-           # we can just re-constitute this one...
-           # NB: we emit _three_ underscores no matter what,
-           # so ghc-split doesn't have to care.
-           print OUTASM "___stg_split_marker",$chksymb[$i],"${T_POST_LBL}\n";
-
-       } elsif ( $chkcat[$i] eq 'closure'
-              || $chkcat[$i] eq 'srt'
-              || $chkcat[$i] eq 'infotbl'
-              || $chkcat[$i] eq 'slow'
-              || $chkcat[$i] eq 'fast' ) { # do them in that order
-           $symb = $chksymb[$i];
-
-           # CLOSURE
-           if ( defined($closurechk{$symb}) ) {
-               print OUTASM $T_HDR_closure;
-               print OUTASM $chk[$closurechk{$symb}];
-               $chkcat[$closurechk{$symb}] = 'DONE ALREADY';
-           }
-
-           # SRT
-           if ( defined($srtchk{$symb}) ) {
-               print OUTASM $T_HDR_srt;
-               print OUTASM $chk[$srtchk{$symb}];
-               $chkcat[$srtchk{$symb}] = 'DONE ALREADY';
-           }
-
-           # INFO TABLE
-           if ( defined($infochk{$symb}) ) {
-
-               print OUTASM $T_HDR_info;
-                if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
-                 if ( !defined($slowchk{$symb}) && defined($fastchk{$symb}) ) {
-                    $fastname = $chk[$fastchk{$symb}];
-                    $fastname =~ s/([_A-Za-z]*_fast\d+):.*(.*\n)*/\1/;
-                     $chk[$infochk{$symb}] =~ s/\.long StdErrorCode/\.long $fastname/;
-                  }
-                  $chk[$infochk{$symb}] =~ s/\.long ([_A-Za-z]\S+_entry)/\.long \.\1/;
-                  $chk[$infochk{$symb}] =~ s/\.long ([A-Za-z]\S+_upd)/\.long \.\1/;
-                  print OUTASM $chk[$infochk{$symb}];
-                } else {
-                 print OUTASM &rev_tbl($symb, $chk[$infochk{$symb}], 1);
-                }
-               # entry code will be put here!
-
-               $chkcat[$infochk{$symb}] = 'DONE ALREADY';
-           }
-
-           # STD ENTRY POINT
-           if ( defined($slowchk{$symb}) ) {
-
-               # teach it to drop through to the fast entry point:
-               $c = $chk[$slowchk{$symb}];
-
-                if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
-                 ($p, $r) = split(/TOC\[tc0\], 0\n/, $c); 
-                  if ($symb =~ /^[_A-Z]/)
-                 { 
-                   print OUTASM "\t\.globl \.${chksymb[$i]}_entry\n"; 
-                   print OUTASM "\.csect ${symb}_entry[DS]\n";         
-                   print OUTASM "${p}TOC[tc0], 0\n";
-                  }; 
-                  $r =~ s/\.csect \.text\[PR\]\n//; # todo: properly - andre
-                  $c = &mangle_powerpc_tailjump($r);
-                };
-
-               if ( defined($fastchk{$symb}) ) {
-                   if ( $TargetPlatform =~ /^alpha-/ ) {
-                       $c =~ s/^\tjmp \$31,\(\$27\),0\n\t\.align 4\n\t\.end/\t.align 4\n\t.end/;
-                   } elsif ( $TargetPlatform =~ /^hppa/ ) {
-                       $c =~ s/^\s+ldil.*\n\s+ldo.*\n\s+bv.*\n(.*\n)?\s+\.EXIT/$1\t.EXIT/;
-                   } elsif ( $TargetPlatform =~ /^i386-/ ) {
-                       # Reg alloc depending, gcc generated code may jump to the fast entry point via
-                       # a number of registers.
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%edx\n\tjmp \*\%edx\n//;
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%ecx\n\tjmp \*\%ecx\n//;
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%eax\n\tjmp \*\%eax\n//;
-                       # The next two only apply if we're not stealing %esi or %edi.
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%esi\n\tjmp \*\%esi\n// if ($StolenX86Regs < 3);
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%edi\n\tjmp \*\%edi\n// if ($StolenX86Regs < 4);
-                   } elsif ( $TargetPlatform =~ /^mips-/ ) {
-                       $c =~ s/^\tjmp \$31,\(\$27\),0\n\t\.align 4\n\t\.end/\t.align 4\n\t.end/;
-                   } elsif ( $TargetPlatform =~ /^m68k-/ ) {
-                       $c =~ s/^\tjmp ${T_US}${symb}_fast\d+.*\n\tnop\n//;
-                       $c =~ s/^\tjmp ${T_US}${symb}_fast\d+.*\n//;
-                   } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ ) {
-                       $c =~ s/^\tb \.${T_US}${symb}_fast\d+\n//;
-                   } elsif ( $TargetPlatform =~ /^sparc-/ ) {
-                       $c =~ s/^\tcall\s+${T_US}${symb}_fast\d+,.*\n\t\s*nop\n//;
-                       $c =~ s/^\tcall\s+${T_US}${symb}_fast\d+,.*\n(\t\s*[a-z].*\n)/$1/;
-                   } else {
-                       print STDERR "$Pgm: mystery slow-fast dropthrough: $TargetPlatform\n";
-                   }
-               }
-
-               if ( $TargetPlatform !~ /^(alpha-|hppa|mips-)/ ) {
-                   # On alphas, hppa: no very good way to look for "dangling"
-                   # references to fast-entry point.
-                   # (questionable re hppa and mips...)
-                   print STDERR "still has jump to fast entry point:\n$c"
-                       if $c =~ /$TUS[@]?$symb[@]?_fast/; # NB: paranoia
-               }
-
-               print OUTASM $T_HDR_entry;
-
-               &print_doctored($c, 1); # NB: the 1!!!
-
-               $chkcat[$slowchk{$symb}] = 'DONE ALREADY';
-           }
-           
-           # FAST ENTRY POINT
-           if ( defined($fastchk{$symb}) ) {
-               $c = $chk[$fastchk{$symb}];
-               if ( ! defined($slowchk{$symb})
-                  # ToDo: the || clause can go once we're no longer
-                  # concerned about producing exactly the same output as before
-#OLD:             || $TargetPlatform =~ /^(m68k|sparc|i386)-/
-                  ) {
-                   print OUTASM $T_HDR_fast;
-               }
-                  if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
-                    local(@lbls) = split(/:/, $c);
-                    $fullname = $lbls[0];
-                   $fullname =~ s/$T_MOVE_DIRVS//g;
-                    if ( $fullname =~ /^[A-Z]/)
-                       { print OUTASM "\t\.globl \.${fullname}\n";
-                    } else {
-#                       print OUTASM "\t\.lglobl \.${fullname}\n"; #todo: rm - andre
-                    };
-                    $c =~ s/((.*\n)*)\t.long \S+, TOC\[tc0\], 0\n\.csect \.text\[PR\]\n((.*\n)*)/\1\3/;
-                    $c = &mangle_powerpc_tailjump($c);
-                  };
-               &print_doctored($c, 0);
-               $chkcat[$fastchk{$symb}] = 'DONE ALREADY';
-           }
-
-       } elsif ( $chkcat[$i] eq 'vector'
-              || $chkcat[$i] eq 'direct' ) { # do them in that order
-           $symb = $chksymb[$i];
-
-           # VECTOR TABLE
-           if ( defined($vectorchk{$symb}) ) {
-               print OUTASM $T_HDR_vector;
-                if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
-                  if ( $symb =~ /^[A-Z]/) {
-                     print OUTASM "\t\.globl \.${symb}_vtbl\n";
-                    print OUTASM "\t\.globl ${symb}_vtbl\n";
-                  };
-                 $chk[$vectorchk{$symb}] =~ s/\.long (\S+)/\.long \.\1/g;
-                 print OUTASM ".${symb}_vtbl:\n";
-                 print OUTASM $chk[$vectorchk{$symb}];
-               } else {
-                 print OUTASM &rev_tbl($symb, $chk[$vectorchk{$symb}], 0);
-               }
-               # direct return code will be put here!
-               $chkcat[$vectorchk{$symb}] = 'DONE ALREADY';
-
-           } elsif ( $TargetPlatform =~ /^alpha-/ ) {
-               # Alphas: the commented nop is for the splitter, to ensure
-               # that no module ends with a label as the very last
-               # thing.  (The linker will adjust the label to point
-               # to the first code word of the next module linked in,
-               # even if alignment constraints cause the label to move!)
-
-               print OUTASM "\t# nop\n";
-           }
-           
-       } elsif ( $chkcat[$i] eq 'toc' ) {
-            # silly optimisation to print tocs, since they come in groups...
-           print OUTASM $T_HDR_toc;
-            local($j)  = $i;
-            while ($chkcat[$j] eq 'toc')
-              { if (   $chk[$j] !~ /\.tc UpdatePAP\[TC\]/ # not needed: always turned into a jump.
-                   ) 
-                {
-                  print OUTASM $chk[$j];
-                }
-                $chkcat[$j] = 'DONE ALREADY';
-                $j++;
-           }
-           
-       } else {
-           &tidy_up_and_die(1,"$Pgm: unknown chkcat (ghc-asm: $TargetPlatform)\n$chkcat[$i]\n$chk[$i]\n");
-       }
-    }
-
-    print OUTASM $EXTERN_DECLS if $TargetPlatform =~ /^mips-/;
-
-    if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
-         print OUTASM ".csect .text[PR]\n_section_.text:\n.csect .data[RW]\n\t.long _section_.text\n"
-    };
-
-    # finished
-    close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
-    close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
-}
-\end{code}
-
-\begin{code}
-sub mash_hppa_prologue { # OK, epilogue, too
-    local($_) = @_;
-
-    # toss all prologue stuff
-    s/^\s+\.ENTRY[^\0]*--- BEGIN ---/\t.ENTRY/;
-
-    # Lie about our .CALLINFO
-    s/^\s+\.CALLINFO.*$/\t.CALLINFO NO_CALLS,NO_UNWIND/;
-
-    # Get rid of P'
-
-    s/LP'/L'/g;
-    s/RP'/R'/g;
-
-    # toss all epilogue stuff
-    s/^\s+--- END ---[^\0]*\.EXIT/\t.EXIT/;
-
-    # Sorry; we moved the _info stuff to the code segment.
-    s/_info,DATA/_info,CODE/g;
-
-    return($_);
-}
-\end{code}
-
-\begin{code}
-sub print_doctored {
-    local($_, $need_fallthru_patch) = @_;
-
-    if ( $TargetPlatform !~ /^i386-/ 
-      || ! /^\t[a-z]/  # no instructions in here, apparently
-      || /^${T_US}__init_[A-Za-z0-9_]+${T_POST_LBL}/) {
-       print OUTASM $_;
-       return;
-    }
-    # OK, must do some x86 **HACKING**
-
-    local($entry_patch)        = '';
-    local($exit_patch) = '';
-
-    # gotta watch out for weird instructions that
-    # invisibly smash various regs:
-    #   rep*   %ecx used for counting
-    #   scas*  %edi used for destination index
-    #   cmps*  %e[sd]i used for indices
-    #   loop*  %ecx used for counting
-    #
-    # SIGH.
-
-    # We cater for:
-    #  * use of STG reg [ nn(%ebx) ] where no machine reg avail
-    #
-    #  * GCC used an "STG reg" for its own purposes
-    #
-    #  * some secret uses of machine reg, requiring STG reg
-    #    to be saved/restored
-
-    # The most dangerous "GCC uses" of an "STG reg" are when
-    # the reg holds the target of a jmp -- it's tricky to
-    # insert the patch-up code before we get to the target!
-    # So here we change the jmps:
-
-    # --------------------------------------------------------
-    # it can happen that we have jumps of the form...
-    #   jmp *<something involving %esp>
-    # or
-    #   jmp <something involving another naughty register...>
-    #
-    # a reasonably-common case is:
-    #
-    #   movl $_blah,<bad-reg>
-    #   jmp  *<bad-reg>
-    #
-
-# the short form may tickle perl bug:
-#    s/^\tmovl \$${T_US}(.*),(\%e[abcd]x)\n\tjmp \*$2/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%eax\n\tjmp \*\%eax/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%ebx\n\tjmp \*\%ebx/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%ecx\n\tjmp \*\%ecx/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%edx\n\tjmp \*\%edx/\tjmp $T_US$1/g;
-
-    if ($StolenX86Regs <= 2 ) { # YURGH! spurious uses of esi?
-       s/^\tmovl (.*),\%esi\n\tjmp \*%esi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
-       s/^\tjmp \*(-?\d*)\((.*\%esi.*)\)\n/\tmovl $2,\%eax\n\tjmp \*$1\(\%eax\)\n/g;
-       s/^\tjmp \*\%esi\n/\tmovl \%esi,\%eax\n\tjmp \*\%eax\n/g;
-       die "$Pgm: (mangler) still have jump involving \%esi!\n$_"
-           if /(jmp|call) .*\%esi/;
-    }
-    if ($StolenX86Regs <= 3 ) { # spurious uses of edi?
-       s/^\tmovl (.*),\%edi\n\tjmp \*%edi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
-       s/^\tjmp \*(-?\d*\(.*\%edi.*\))\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
-       s/^\tjmp \*\%edi\n/\tmovl \%edi,\%eax\n\tjmp \*\%eax\n/g;
-       die "$Pgm: (mangler) still have jump involving \%edi!\n$_"
-           if /(jmp|call) .*\%edi/;
-    }
-
-    # OK, now we can decide what our patch-up code is going to
-    # be:
-
-    # Offsets into register table - you'd better update these magic
-    # numbers should you change its contents!
-    # local($OFFSET_R1)=0;  No offset for R1 in new RTS.
-    local($OFFSET_Hp)=92;
-
-       # Note funky ".=" stuff; we're *adding* to these _patch guys
-    if ( $StolenX86Regs <= 2
-        && ( /[^0-9]\(\%ebx\)/ || /\%esi/ || /^\tcmps/ ) ) { # R1 (esi)
-       $entry_patch .= "\tmovl \%esi,(\%ebx)\n";
-       $exit_patch  .= "\tmovl (\%ebx),\%esi\n";
-
-       # nothing for call_{entry,exit} because %esi is callee-save
-    }
-    if ( $StolenX86Regs <= 3
-        && ( /${OFFSET_Hp}\(\%ebx\)/ || /\%edi/ || /^\t(scas|cmps)/ ) ) { # Hp (edi)
-       $entry_patch .= "\tmovl \%edi,${OFFSET_Hp}(\%ebx)\n";
-       $exit_patch  .= "\tmovl ${OFFSET_Hp}(\%ebx),\%edi\n";
-
-       # nothing for call_{entry,exit} because %edi is callee-save
-    }
-
-    # --------------------------------------------------------
-    # next, here we go with non-%esp patching!
-    #
-    s/^(\t[a-z])/$entry_patch$1/; # before first instruction
-
-# Before calling GC we must set up the exit condition before the call
-# and entry condition when we come back
-
-    # fix _all_ non-local jumps:
-
-    s/^\tjmp \*${T_X86_PRE_LLBL_PAT}/\tJMP___SL/go;
-    s/^\tjmp ${T_X86_PRE_LLBL_PAT}/\tJMP___L/go;
-
-    s/^(\tjmp .*\n)/$exit_patch$1/g; # here's the fix...
-
-    s/^\tJMP___SL/\tjmp \*${T_X86_PRE_LLBL}/go;
-    s/^\tJMP___L/\tjmp ${T_X86_PRE_LLBL}/go;
-
-    if ($StolenX86Regs == 2 ) {
-       die "ARGH! Jump uses \%esi or \%edi with -monly-2-regs:\n$_" 
-           if /^\t(jmp|call) .*\%e(si|di)/;
-    } elsif ($StolenX86Regs == 3 ) {
-       die "ARGH! Jump uses \%edi with -monly-3-regs:\n$_" 
-           if /^\t(jmp|call) .*\%edi/;
-    }
-
-    # --------------------------------------------------------
-    # that's it -- print it
-    #
-    #die "Funny jumps?\n$_" if /${T_X86_BADJMP}/o; # paranoia
-
-    print OUTASM $_;
-
-    if ( $need_fallthru_patch ) { # exit patch for end of slow entry code
-       print OUTASM $exit_patch;
-       # ToDo: make it not print if there is a "jmp" at the end
-    }
-}
-\end{code}
-
-\begin{code}
-sub init_FUNNY_THINGS {
-    %KNOWN_FUNNY_THING = (
-       # example
-       # "${T_US}stg_.*{T_POST_LBL}", 1,  
-    );
-}
-\end{code}
-
-The following table reversal is used for both info tables and return
-vectors.  In both cases, we remove the first entry from the table,
-reverse the table, put the label at the end, and paste some code
-(that which is normally referred to by the first entry in the table)
-right after the table itself.  (The code pasting is done elsewhere.)
-
-\begin{code}
-sub rev_tbl {
-    local($symb, $tbl, $discard1) = @_;
-
-    local($before) = '';
-    local($label) = '';
-    local(@imports) = (); # hppa only
-    local(@words) = ();
-    local($after) = '';
-    local(@lines) = split(/\n/, $tbl);
-    local($i, $j); #local ($i, $extra, $words_to_pad, $j);
-
-    # see comment in mangleAsm as to why this silliness is needed.
-    local($TDOTWORD) = ${T_DOT_WORD};
-    local($TDOTGLOBAL) = ${T_DOT_GLOBAL};
-    local($TUS) = ${T_US};
-    local($TPOSTLBL) = ${T_POST_LBL};
-
-    # Deal with the header...
-    for ($i = 0; $i <= $#lines && $lines[$i] !~ /^\t?$TDOTWORD\s+/o; $i++) {
-       $label .= $lines[$i] . "\n",
-           next if $lines[$i] =~ /^[A-Za-z0-9_]+_info$TPOSTLBL[@]?$/o
-                || $lines[$i] =~ /$TDOTGLOBAL/o
-                || $lines[$i] =~ /^$TUS[@]?\S+_vtbl$TPOSTLBL[@]?$/o;
-
-       $before .= $lines[$i] . "\n"; # otherwise...
-    }
-
-    # Grab the table data...
-    if ( $TargetPlatform !~ /^hppa/ ) {
-       for ( ; $i <= $#lines && $lines[$i] =~ /^\t?$TDOTWORD\s+/o; $i++) {
-           push(@words, $lines[$i]);
-       }
-    } else { # hppa weirdness
-       for ( ; $i <= $#lines && $lines[$i] =~ /^\s+($TDOTWORD|\.IMPORT)/; $i++) {
-           if ($lines[$i] =~ /^\s+\.IMPORT/) {
-               push(@imports, $lines[$i]);
-           } else {
-               # We don't use HP's ``function pointers''
-               # We just use labels in code space, like normal people
-               $lines[$i] =~ s/P%//;
-               push(@words, $lines[$i]);
-           }
-       }
-    }
-
-    # now throw away the first word (SRT) iff it is empty.
-    # The .zero business is for Linux/ELF.
-    # The .skip business is for Sparc/Solaris/ELF.
-    # The .blockz business is for HPPA.
-    if ($discard1 && $words[0] =~ /^\t?($TDOTWORD\s+0|\.zero\s+4|\.skip\s+4|\.blockz\s+4)/) {
-       shift(@words)
-    }
-
-# Padding removed to reduce code size and improve performance on Pentiums.
-# Simon M. 13/4/96
-    # for 486-cache-friendliness, we want our tables aligned
-    # on 16-byte boundaries (.align 4).  Let's pad:
-#    $extra = ($#words + 1) % 4;
-#    $words_to_pad = ($extra == 0) ? 0 : 4 - $extra;
-#    for ($j = 0; $j < $words_to_pad; $j++) { push(@words, "\t${T_DOT_WORD} 0"); }
-
-    for (; $i <= $#lines; $i++) {
-       $after .= $lines[$i] . "\n";
-    }
-
-    # Alphas:If we have anonymous text (not part of a procedure), the
-    # linker may complain about missing exception information.  Bleh.
-    if ( $TargetPlatform =~ /^alpha-/ && $label =~ /^([A-Za-z0-9_]+):$/) {
-       $before = "\t.ent $1\n" . $before;
-       $after .= "\t.end $1\n";
-    }
-
-    $tbl = $before
-        . (($TargetPlatform !~ /^hppa/) ? '' : join("\n", @imports) . "\n")
-        . join("\n", @words) . "\n"
-        . $label . $after;
-
-#   print STDERR "before=$before\n";
-#   print STDERR "label=$label\n";
-#   print STDERR "words=",(reverse @words),"\n";
-#   print STDERR "after=$after\n";
-
-    $tbl;
-}
-\end{code}
-
-The HP is a major nuisance.  The threaded code mangler moved info
-tables from data space to code space, but unthreaded code in the RTS
-still has references to info tables in data space.  Since the HP
-linker is very precise about where symbols live, we need to patch the
-references in the unthreaded RTS as well.
-
-\begin{code}
-sub mini_mangle_asm_hppa {
-    local($in_asmf, $out_asmf) = @_;
-
-    open(INASM, "< $in_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
-    open(OUTASM,"> $out_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
-
-    while (<INASM>) {
-       s/_info,DATA/_info,CODE/;   # Move _info references to code space
-       s/P%_PR/_PR/;
-       print OUTASM;
-    }
-
-    # finished:
-    close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
-    close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
-}
-
-\end{code}
-\begin{code}
-sub mini_mangle_asm_powerpc {
-    local($in_asmf, $out_asmf) = @_;
-
-    open(INASM, "< $in_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
-    open(OUTASM,"> $out_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
-
-    while (<INASM>) {
-       s/long _PRStart/long ._PRStart/;
-       s/long _PRIn_/long ._PRIn_/;
-       s/long _Dummy_(\S+)_entry/long ._Dummy_\1_entry/;
-       s/long _PRMarking_MarkNextRoot\[DS\]/long ._PRMarking_MarkNextRoot/;
-       s/long _PRMarking_MarkNextCAF\[DS\]/long ._PRMarking_MarkNextCAF/;
-       s/long _PRMarking_MarkNextAStack\[DS\]/long ._PRMarking_MarkNextAStack/;
-       s/long _PRMarking_MarkNextBStack\[DS\]/long ._PRMarking_MarkNextBStack/;
-        s/\.tc EnterNodeCode\[TC]\,EnterNodeCode\[DS\]/\.tc EnterNodeCode\[TC]\,.EnterNodeCode/; # CONC
-        s/\.tc CheckHeapCode\[TC]\,CheckHeapCode\[DS\]/\.tc CheckHeapCode\[TC]\,.CheckHeapCode/; # CONC
-       print OUTASM;
-    }
-
-    # finished:
-    close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
-    close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
-}
-
-sub mangle_powerpc_tailjump {
-    local($c) = @_;
-    local($maybe_more) = 1;
-    while (($c =~ /\tlw?z? \d+,LC\.\.\d+\(2\)\n\tmtctr \d+\n\tbctr\n/) && $maybe_more) 
-      { $maybe_more = 0;
-        $lcsymb = $c;
-        $lcsymb =~ s/(.*\n)*\tlw?z? \d+,LC\.\.(\d+)\(2\)\n\tmtctr \d+\n\tbctr\n(.*\n)*/\2/;
-# the checks for r1 and r2 are mostly paranoia...
-        $r1 = $c;
-        $r1 =~ s/(.*\n)*\tlw?z? (\d+),LC\.\.\d+\(2\)\n\tmtctr \d+\n\tbctr\n(.*\n)*/\2/;
-        $r2 = $c;
-        $r2 =~ s/(.*\n)*\tlw?z? \d+,LC\.\.(\d+)\(2\)\n\tmtctr (\d+)\n\tbctr\n(.*\n)*/\3/;
-        if (r1 == r2)
-          { $maybe_more = 1;
-            $c =~ s/((.*\n)*)\tlw?z? \d+,LC\.\.\d+\(2\)\n\tmtctr \d+\n\tbctr\n((.*\n)*)/\1\tb $tocequiv{$lcsymb}\n\3/;
-          }
-      };
-    $c;
-}
-
-# make "require"r happy...
-1;
-\end{code}
diff --git a/ghc/driver/ghc-consist.lprl b/ghc/driver/ghc-consist.lprl
deleted file mode 100644 (file)
index 535e7ec..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-%************************************************************************
-%*                                                                     *
-\section[Driver-consistency-chk]{@chk_consistency_info@: Check an executable for consistency}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub chk_consistency_info {
-    local($executable) = @_;
-    
-    local($major_version, $minor_version);
-    local($phase, $infile, $opts);
-
-    # append .exe if it's not there under cygwin32
-    $executable = "${executable}.exe" if $TargetPlatform eq 'i386-unknown-cygwin32' &&
-                                        $executable !~ /\...*$/ ; 
-
-    print STDERR "Checking consistency of: $executable\n" if $Verbose;
-
-    &tidy_up_and_die(1, "Panic: no such executable: $executable\n")
-       if ( ! -x $executable ) && ( ! -B $executable );
-    # perl apparently determines whether something is executable
-    # by looking at the file suffix under win32/cygwin32 !?!
-    # Hence, we try binary files if (! -x) fails.
-
-    # by this point, consistency strings (with commas) have become
-    # local symbols (with .'s)
-    $HsC_consist_options =~ s/,/./g;
-    $Cc_consist_options  =~ s/,/./g;
-
-    # now run `nm' and check all the version info
-    open(CONSIST, "$Nm -p $executable |") || &tidy_up_and_die(1,"$Pgm: can't run: $Nm\n");
-    while (<CONSIST>) {
-       chop;
-       next if ! /^[\da-fA-F]+\s+[tn]\s+(hsc|cc)\./;
-
-       if (/^[\da-fA-F]+\s+[tn]\s+(hsc|cc)\.(\S+)\.(\d+)\.(\d+)\.(.*)/) {
-           $phase = $1; $infile = $2;
-           $major_version = $3; $minor_version = $4;
-           $opts = $5;
-           if ($phase eq 'hsc') {
-               $Status++,
-               print STDERR "$Pgm: consistency error: major version not $HsC_major_version:\n$_\n"
-                   if $major_version != $HsC_major_version;
-               print STDERR "$Pgm: consistency warning: minor version not $HsC_minor_version:\n$_\n"
-                   if $minor_version != $HsC_minor_version;
-               $Status++,
-               print STDERR "$Pgm: consistency error: not options $opts -- $HsC_consist_options:\n$_\n"
-                   if $opts ne $HsC_consist_options;
-
-           } else { # phase is cc ...
-               $Status++,
-               print STDERR "$Pgm: consistency error: major version not $Cc_major_version:\n$_\n"
-                   if $major_version != $Cc_major_version;
-               print STDERR "$Pgm: consistency warning: minor version not $Cc_minor_version:\n$_\n"
-                   if $minor_version != $Cc_minor_version;
-
-               $Status++,
-               print STDERR "$Pgm: consistency error: not options $Cc_consist_options:\n$_\n"
-                   if $opts ne $Cc_consist_options;
-           }
-       } else {
-           print STDERR "$Pgm: consistency-checking: unrecognised `what' line:\n$_\n";
-       }
-    }
-    close(CONSIST) || &tidy_up_and_die(1,"Failed in running $Nm (consistency checking)\n");
-}
-
-# make "require"r happy...
-1;
-\end{code}
diff --git a/ghc/driver/ghc-split.lprl b/ghc/driver/ghc-split.lprl
deleted file mode 100644 (file)
index 5e4d0bc..0000000
+++ /dev/null
@@ -1,436 +0,0 @@
-%************************************************************************
-%*                                                                     *
-\section[Driver-obj-splitting]{Splitting into many \tr{.o} files (for libraries)}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub split_asm_file {
-    local($asm_file) = @_;
-
-    open(TMPI, "< $asm_file") || &tidy_up_and_die(1,"$Pgm: failed to open `$asm_file' (to read)\n");
-
-    &collectExports_hppa() if $TargetPlatform =~ /^hppa/;
-    &collectExports_mips() if $TargetPlatform =~ /^mips/;
-
-    $octr = 0; # output file counter
-    $* = 1;    # multi-line matches are OK
-
-    %LocalConstant = (); # we have to subvert C compiler's commoning-up of constants...
-
-    $s_stuff = &ReadTMPIUpToAMarker( '', $octr );
-    # that first stuff is a prologue for all .s outputs
-    $prologue_stuff = &process_asm_block ( $s_stuff );
-    # $_ already has some of the next stuff in it...
-
-#   &tidy_up_and_die(1,"$Pgm: no split markers in .s file!\n")
-#      if $prologue_stuff eq $s_stuff;
-
-    # lie about where this stuff came from
-    $prologue_stuff =~ s|"/tmp/ghc\d+\.c"|"$ifile_root\.hc"|g;
-
-    while ( $_ ne '' ) { # not EOF
-       $octr++;
-
-       # grab and de-mangle a section of the .s file...
-       $s_stuff = &ReadTMPIUpToAMarker ( $_, $octr );
-       $this_piece = &process_asm_block ( $s_stuff );
-
-       # output to a file of its own
-       # open a new output file...
-       $ofname = "${Tmp_prefix}__${octr}.s";
-       open(OUTF, "> $ofname") || die "$Pgm: can't open output file: $ofname\n";
-
-       print OUTF $prologue_stuff;
-       print OUTF $this_piece;
-
-       close(OUTF)
-         || &tidy_up_and_die(1,"$Pgm:Failed writing ${Tmp_prefix}__${octr}.s\n");
-    }
-
-    $NoOfSplitFiles = $octr;
-
-    close(TMPI) || &tidy_up_and_die(1,"Failed reading $asm_file\n");
-}
-
-sub collectExports_hppa { # Note: HP-PA only
-
-    %LocalExport = (); # NB: global table
-
-    while(<TMPI>) {
-       if (/^\s+\.EXPORT\s+([^,]+),.*\n/) {
-           local($label) = $1;
-           local($body)  = "\t.IMPORT $label";
-           if (/,DATA/) { 
-               $body .= ",DATA\n"; 
-           } else { 
-               $body .= ",CODE\n"; 
-           }
-           $label =~ s/\$/\\\$/g;
-           $LocalExport{$label} = $body;
-       }
-    }
-
-    seek(TMPI, 0, 0);
-}
-
-sub collectExports_mips { # Note: MIPS only
-    # (not really sure this is necessary [WDP 95/05])
-
-    $UNDEFINED_FUNS = ''; # NB: global table
-
-    while(<TMPI>) {
-       $UNDEFINED_FUNS .= $_ if /^\t\.globl\s+\S+ \.\S+\n/;
-       # just save 'em all
-    }
-
-    seek(TMPI, 0, 0);
-}
-
-sub ReadTMPIUpToAMarker {
-    local($str, $count) = @_; # already read bits
-
-    
-    for ( $_ = <TMPI>; $_ ne '' && ! /_?__stg_split_marker/; $_ = <TMPI> ) {
-       $str .= $_;
-    }
-    # if not EOF, then creep forward until next "real" line
-    # (throwing everything away).
-    # that first "real" line will stay in $_.
-
-    # This loop is intended to pick up the body of the split_marker function
-    # Note that the assembler mangler will already have eliminated this code
-    # if it's been invoked (which it probably has).
-
-    while ($_ ne '' && (/_?__stg_split_marker/
-                    || /^L[^C].*:$/
-                    || /^\.stab/
-                    || /\t\.proc/
-                    || /\t\.stabd/
-                    || /\t\.even/
-                    || /\tunlk a6/
-                    || /^\t!#PROLOGUE/
-                    || /\t\.prologue/
-                    || /\t\.frame/
-                     # || /\t\.end/ NOT!  Let the split_marker regexp catch it
-                     # || /\t\.ent/ NOT!  Let the split_marker regexp catch it
-                    || /^\s+(save|retl?|restore|nop)/)) {
-       $_ = <TMPI>;
-    }
-
-    print STDERR "### BLOCK:$count:\n$str" if $Dump_asm_splitting_info;
-
-    # return str
-    $str;
-}
-\end{code}
-
-We must (a)~strip the marker off the block, (b)~record any literal C
-constants that are defined here, and (c)~inject copies of any C constants
-that are used-but-not-defined here.
-
-\begin{code}
-sub process_asm_block {
-    local($str) = @_;
-
-    return(&process_asm_block_m68k($str))  if $TargetPlatform =~ /^m68k-/;
-    return(&process_asm_block_sparc($str)) if $TargetPlatform =~ /^sparc-/;
-    return(&process_asm_block_iX86($str))  if $TargetPlatform =~ /^i[34]86-/;
-    return(&process_asm_block_alpha($str)) if $TargetPlatform =~ /^alpha-/;
-    return(&process_asm_block_hppa($str))  if $TargetPlatform =~ /^hppa/;
-    return(&process_asm_block_mips($str))   if $TargetPlatform =~ /^mips-/;
-    return(&process_asm_block_powerpc($str))   if $TargetPlatform =~ /^powerpc-|^rs6000-/;
-
-    # otherwise...
-    &tidy_up_and_die(1,"$Pgm: no process_asm_block for $TargetPlatform\n");
-}
-
-sub process_asm_block_sparc {
-    local($str) = @_;
-
-    # strip the marker
-    if ( $OptimiseC ) {
-       $str =~ s/_?__stg_split_marker.*:\n//;
-    } else {
-       $str =~ s/(\.text\n\t\.align .\n)\t\.global\s+.*_?__stg_split_marker.*\n\t\.proc.*\n/$1/;
-       $str =~ s/(\t\.align .\n)\t\.global\s+.*_?__stg_split_marker.*\n\t\.proc.*\n/$1/;
-    }
-
-    # make sure the *.hc filename gets saved; not just ghc*.c (temp name)
-    $str =~ s/^\.stabs "(ghc\d+\.c)"/.stabs "$ifile_root.hc"/g; # HACK HACK
-
-    # remove/record any literal constants defined here
-    while ( $str =~ /(\t\.align .\n\.?(L?LC\d+):\n(\t\.asci[iz].*\n)+)/ ) {
-       local($label) = $2;
-       local($body)  = $1;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = $body;
-       
-       $str =~ s/\t\.align .\n\.?LL?C\d+:\n(\t\.asci[iz].*\n)+//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\b$k\b/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-   print STDERR "### STRIPPED BLOCK (sparc):\n$str" if $Dump_asm_splitting_info;
-
-   $str;
-}
-
-sub process_asm_block_m68k {
-    local($str) = @_;
-
-    # strip the marker
-
-    $str =~ s/(\.text\n\t\.even\n)\t\.globl\s+.*_?__stg_split_marker.*\n/$1/;
-    $str =~ s/(\t\.even\n)\t\.globl\s+.*_?__stg_split_marker.*\n/$1/;
-
-    # it seems prudent to stick on one of these:
-    $str = "\.text\n\t.even\n" . $str;
-
-    # remove/record any literal constants defined here
-    while ( $str =~ /((LC\d+):\n\t\.ascii.*\n)/ ) {
-       local($label) = $2;
-       local($body)  = $1;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = $body;
-       
-       $str =~ s/LC\d+:\n\t\.ascii.*\n//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\b$k\b/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-   print STDERR "### STRIPPED BLOCK (m68k):\n$str" if $Dump_asm_splitting_info;
-
-   $str;
-}
-
-sub process_asm_block_alpha {
-    local($str) = @_;
-
-    # strip the marker
-    if ( $OptimiseC ) {
-       $str =~ s/_?__stg_split_marker.*:\n//;
-    } else {
-       $str =~ s/(\t\.align .\n)\t\.globl\s+.*_?__stg_split_marker.*\n\t\.ent.*\n/$1/;
-    }
-
-    # remove/record any literal constants defined here
-    while ( $str =~ /(\.rdata\n\t\.align \d\n)?(\$(C\d+):\n\t\..*\n)/ ) {
-       local($label) = $3;
-       local($body)  = $2;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = ".rdata\n\t.align 3\n" . $body . "\t.text\n";
-       
-       $str =~ s/(\.rdata\n\t\.align \d\n)?\$C\d+:\n\t\..*\n//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\$\b$k\b/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-    # Slide the dummy direct return code into the vtbl .ent/.end block,
-    # to keep the label fixed if it's the last thing in a module, and
-    # to avoid having any anonymous text that the linker will complain about
-    $str =~ s/(\t\.end [A-Za-z0-9_]+)\n\t# nop/\tnop\n$1/g;
-
-    print STDERR "### STRIPPED BLOCK (alpha):\n$str" if $Dump_asm_splitting_info;
-
-    $str;
-}
-
-sub process_asm_block_iX86 {
-    local($str) = @_;
-
-    # strip the marker
-
-    $str =~ s/(\.text\n\t\.align .(,0x90)?\n)\.globl\s+.*_?__stg_split_marker.*\n/$1/;
-    $str =~ s/(\t\.align .(,0x90)?\n)\.globl\s+.*_?__stg_split_marker.*\n/$1/;
-
-    # it seems prudent to stick on one of these:
-    $str = "\.text\n\t.align 4\n" . $str;
-
-    # remove/record any literal constants defined here
-    while ( ($str =~ /(\.?(LC\d+):\n\t\.(ascii|string).*\n)/ )) {
-       local($label) = $2;
-       local($body)  = $1;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = $body;
-       
-       $str =~ s/\.?LC\d+:\n\t\.(ascii|string).*\n//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\b$k\b/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-   print STDERR "### STRIPPED BLOCK (iX86):\n$str" if $Dump_asm_splitting_info;
-
-   $str;
-}
-\end{code}
-
-\begin{code}
-sub process_asm_block_hppa {
-    local($str) = @_;
-
-    # strip the marker
-    $str =~ s/___stg_split_marker.*\n//;
-
-    # remove/record any imports defined here
-    while ( $str =~ /^(\s+\.IMPORT\s.*\n)/ ) {
-       $Imports .= $1;
-
-       $str =~ s/^\s+\.IMPORT.*\n//;
-    }
-
-    # remove/record any literal constants defined here
-    while ( $str =~ /^(\s+\.align.*\n(L\$C\d+)\n(\s.*\n)+); end literal\n/ ) {
-       local($label) = $2;
-       local($body)  = $1;
-       $label =~ s/\$/\\\$/g;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n\n" . $body;
-       
-       $str =~ s/^\s+\.SPACE \$TEXT\$\n\s+\.SUBSPA \$LIT\$\s+\.align.*\nL\$C\d+\n(\s.*\n)+; end literal\n//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\b$k\b/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-    # inject required imports for local exports in other chunks
-    foreach $k (keys %LocalExport) {
-       if ( $str =~ /\b$k\b/ && ! /EXPORT\s+$k\b/ ) {
-           $str = $LocalExport{$k} . $str;
-       }
-    }
-
-    # inject collected imports
-
-    $str = $Imports . $str;
-
-    print STDERR "### STRIPPED BLOCK (hppa):\n$str" if $Dump_asm_splitting_info;
-
-    $str;
-}
-\end{code}
-
-\begin{code}
-sub process_asm_block_mips {
-    local($str) = @_;
-
-    # strip the marker
-    if ( $OptimiseC ) {
-       $str =~ s/_?__stg_split_marker.*:\n//;
-    } else {
-       $str =~ s/(\t\.align .\n)\t\.globl\s+.*_?__stg_split_marker.*\n\t\.ent.*\n/$1/;
-    }
-
-    # remove/record any literal constants defined here
-    while ( $str =~ /(\t\.rdata\n\t\.align \d\n)?(\$(LC\d+):\n(\t\.byte\t.*\n)+)/ ) {
-       local($label) = $3;
-       local($body)  = $2;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = "\t.rdata\n\t.align 2\n" . $body . "\t.text\n";
-       
-       $str =~ s/(\t\.rdata\n\t\.align \d\n)?\$LC\d+:\n(\t\.byte\t.*\n)+//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\$\b$k\b/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-    # Slide the dummy direct return code into the vtbl .ent/.end block,
-    # to keep the label fixed if it's the last thing in a module, and
-    # to avoid having any anonymous text that the linker will complain about
-    $str =~ s/(\t\.end [A-Za-z0-9_]+)\n\t# nop/\tnop\n$1/g;
-
-    $str .= $UNDEFINED_FUNS; # pin on gratuitiously-large amount of info
-
-    print STDERR "### STRIPPED BLOCK (mips):\n$str" if $Dump_asm_splitting_info;
-
-    $str;
-}
-\end{code}
-
-\begin{code}
-sub process_asm_block_powerpc {
-    local($str) = @_;
-
-    # strip the marker
-    $str =~ s/___stg_split_marker.*\n//;
-    $str =~ s/___stg_split_marker.*\n//; # yes, twice.
-
-    # remove/record any literal constants defined here
-    while ( $str =~ /^(.csect .data[RW]\n\s+\.align.*\n(LC\.\.\d+):\n(\s\.byte .*\n)+)/ ) {
-       local($label) = $2;
-       local($body)  = $1;
-
-       &tidy_up_and_die(1,"Local constant label $label already defined!\n")
-           if $LocalConstant{$label};
-
-       $LocalConstant{$label} = $body;
-       
-       $str =~ s/^.csect .data[RW]\n\s+\.align.*\nLC\.\.\d+:\n(\s\.byte .*\n)+//;
-    }
-
-    # inject definitions for any local constants now used herein
-    foreach $k (keys %LocalConstant) {
-       if ( $str =~ /\b$k(\b|\[)/ ) {
-           $str = $LocalConstant{$k} . $str;
-       }
-    }
-
-    print STDERR "### STRIPPED BLOCK (powerpc/rs6000):\n$str" if $Dump_asm_splitting_info;
-
-    $str = ".toc\n" . $str;
-
-    $str;
-}
-\end{code}
-
-\begin{code}
-# make "require"r happy...
-1;
-\end{code}
-
diff --git a/ghc/driver/ghc.lprl b/ghc/driver/ghc.lprl
deleted file mode 100644 (file)
index 0568a0d..0000000
+++ /dev/null
@@ -1,3494 +0,0 @@
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1997
-%
-
-This is the driver script for the Glasgow Haskell compilation system.
-It is written in \tr{perl}.  The first section includes a long
-``usage'' message that describes how the driver is supposed to work.
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-usage]{Usage message}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-use 5;   # require Perl version 5 or later.
-
-($Pgm = $0) =~ s|.*/||;
-$ShortUsage  =  "\nUsage: For basic information, try the `-help' option.\n";
-$LongUsage = "\n" . <<EOUSAGE;
-Use of the Glorious Haskell Compilation System driver:
-
-    $Pgm [command-line-options-and-input-files]
-
-------------------------------------------------------------------------
-This driver ($Pgm) guides each input file through (some of the)
-possible phases of a compilation:
-
-    - unlit:   extract code from a "literate program"
-    - hscpp:   run code through the C pre-processor (if -cpp flag given)
-    - hsc:     run the Haskell compiler proper
-    - gcc:     run the C compiler (if compiling via C)
-    - as:      run the assembler
-    - ld:      run the linker
-
-For each input file, the phase to START with is determined by the
-file's suffix:
-    - .lhs     literate Haskell: unlit
-    - .hs      illiterate Haskell: hsc
-    - .hc      C from the Haskell compiler: gcc
-    - .c       C not from the Haskell compiler: gcc
-    - .s       assembly language: as
-    - other    passed directly to the linker: ld
-
-If no files are given on the command line, input is taken from
-standard input, and processing is as for an .hs file.  (All output is
-to stdout or stderr, however).
-
-The phase at which to STOP processing is determined by a command-line
-option:
-    -E         stop after generating preprocessed, de-litted Haskell (used in conjunction with -cpp)
-    -C         stop after generating C (.hc output)
-    -S         stop after generating assembler (.s output)
-    -c         stop after generating object files (.o output)
-
-Other commonly-used options are:
-
-    -O         An `optimising' package of compiler flags, for faster code
-
-    -prof      Compile for cost-centre profiling
-               (add -auto for automagic cost-centres on top-level functions)
-
-    -fglasgow-exts  Allow Glasgow extensions (unboxed types, etc.)
-
-    -H14m      Increase compiler's heap size
-
-    -M          Output the Makefile rules recording the
-                dependencies of a list of Haskell files.
-               (ghc driver script calls upon the help of a
-                 compatible mkdependHS script to do the actual
-                processing)
-
-The User's Guide has more information about GHC's *many* options.
-
-Given the above, here are some TYPICAL invocations of $Pgm:
-
-    # compile a Haskell module to a .o file, optimising:
-    % $Pgm -c -O Foo.hs
-    # link three .o files into an executable called "test":
-    % $Pgm -o test Foo.o Bar.o Baz.o
-    # compile a Haskell module to C (a .hc file), using a bigger heap:
-    % $Pgm -C -H16m Foo.hs
-    # compile Haskell-produced C (.hc) to assembly language:
-    % $Pgm -S Foo.hc
-------------------------------------------------------------------------
-EOUSAGE
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-init]{Initialisation}
-%*                                                                     *
-%************************************************************************
-
-The driver script need to be told where to find these executables, so
-in the course of building the driver `executable', make-variables holding
-these are prepended to the de-litted version of this file. The variables are:
-
-\begin{verbatim}
-INSTALLING
-
-HOSTPLATFORM TARGETPLATFORM
-
-ProjectName ProjectVersion ProjectVersionInt
-
-HscMajorVersion HscMinorVersion CcMajorVersion CcMinorVersion
-
-TOP_PWD
-
-bindir libdir libexecdir datadir
-
-CURRENT_DIR TMPDIR
-
-GHC_LIB_DIR GHC_RUNTIME_DIR GHC_INCLUDE_DIR
-
-GHC_OPT_HILEV_ASM GhcWithNativeCodeGen
-
-GHC_UNLIT GHC_HSCPP GHC_MKDEPENDHS GHC_HSC GHC_SYSMAN
-
-CP RM CONTEXT_DIFF
-
-WAY_*_NAME WAY_*_REAL_OPTS
-
-LeadingUnderscore
-
-GhcWithRegisterised
-
-\end{verbatim}
-
-Establish what executables to run for the various phases, what the
-default options are for those phases, and other similar boring stuff.
-
-\begin{code}
-select(STDERR); $| = 1; select(STDOUT); # no STDERR buffering, please.
-
-$TargetPlatform = $TARGETPLATFORM;
-
-$TopPwd                   = "${TOP_PWD}";
-$InstBinDirGhc     = "${bindir}";
-$InstLibDirGhc     = "${libdir}";
-#
-# Normally the same as InstLibDirGhc, but we accommodate
-# for it being separate.
-#
-$InstLibExecDirGhc = "${libexecdir}";
-$InstDataDirGhc    = "${datadir}";
-
-$Status  = 0; # just used for exit() status
-$Verbose = '';
-
-# set up signal handler
-sub quit_upon_signal { &tidy_up_and_die(1, ''); }
-$SIG{'INT'}  = 'quit_upon_signal';
-$SIG{'QUIT'} = 'quit_upon_signal';
-
-# where to get "require"d .prl files at runtime (poor man's dynamic loading)
-#   (use LIB, not DATA, because we can't be sure of arch-independence)
-@INC = ( ( $INSTALLING ) ? $InstLibDirGhc
-                          : "$TopPwd/${CURRENT_DIR}" );
-
-if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
-    # Try to find a $Tmp_prefix which isn't being used...
-    $tmp = $$;
-    do {
-      $Tmp_prefix = ($ENV{'TMPDIR'} . "/ghc$tmp");
-      $tmp++;
-    } while ( -e "$Tmp_prefix.hc" ||
-             -e "$Tmp_Prefix.s"  || 
-             -e "$Tmp_Prefix.hi" );
-} else {
-    print STDERR "TMPDIR has not been set to anything useful!\n" if (${TMPDIR} eq '');
-    $Tmp_prefix ="${TMPDIR}/ghc$$"; # TMPDIR set via Makefile when booting..
-    $ENV{'TMPDIR'} = ${TMPDIR}; # set the env var as well
-}
-
-# Some shells run into real trouble when command line and environment
-# gets big (e.g., cmd lines of >4K to /bin/sh causes havoc on our 
-# Solaris-2.5.1 boxes - even though sysconf(_SC_ARG_MAX) reports 1M ...).
-# To work around any such */bin/sh* problems, we will scribble such
-# awfully long command lines into a temp file and exec that temp file
-# with $(REAL_SHELL) (don't use the SHELL variable directly as this
-# will normally get you the wrong thing when the driver is invoked
-# from within `make'). If the REAL_SHELL variable isn't set, you'll
-# get SHELL. This is all a terrible hack. (in case you hadn't reached
-# the same conclusion by now :-)
-#
-# TBC..
-#
-if ( ! $ENV{'REAL_SHELL'} ) {
-    $ENV{'REAL_SHELL'} = $ENV{'SHELL'};
-}
-
-@Files_to_tidy = (); # files we nuke in the case of abnormal termination
-
-$Unlit = ( $INSTALLING ) ? "$InstLibExecDirGhc/unlit"
-                        : "$TopPwd/${CURRENT_DIR}/${GHC_UNLIT}";
-
-$Cp   = $CP;
-$Rm   = $RM;
-$Diff = $CONTEXT_DIFF;
-$Cat  = 'cat';
-$Cmp  = 'cmp';
-$Time = '';
-
-$HsCpp  = # but this is re-set to "cat" (after options) if -cpp not seen
-          ( $INSTALLING ) ? "$InstLibExecDirGhc/hscpp"
-                          : "$TopPwd/${CURRENT_DIR}/${GHC_HSCPP}";
-
-@HsCpp_flags   = ();
-$HsC    = ( $INSTALLING ) ? "$InstLibExecDirGhc/hsc"
-                          : "$TopPwd/${CURRENT_DIR}/${GHC_HSC}";
-
-# For PVM fiends only
-$SysMan         = ( $INSTALLING ) ? "$InstLibExecDirGhc/SysMan"
-                          : "$TopPwd/${CURRENT_DIR}/${GHC_SYSMAN}";
-
-@Unlit_flags   = ();
-
-#
-# HsC_rts_flags: if we want to talk to the LML runtime system
-# NB: we don't use powers-of-2 sizes, because this may do
-#   terrible things to cache behavior.
-#
-$Specific_heap_size = 6 * 1000 * 1000;
-$Specific_stk_size  = 1000 * 1000;
-$Scale_sizes_by     = 1.0;
-
-\end{code}
-
-The variables set by @setupOptFlags@ represent parts of the
--O/-O2/etc ``templates,'' which are filled in later, using these.
-These are the default values, which may be changed by user flags.
-
-\begin{code}
-sub setupOptFlags {
-   $Oopt_MaxSimplifierIterations  = '-fmax-simplifier-iterations4';
-   $Oopt_FinalStgProfilingMassage = '';
-   $Oopt_StgStats                = '';
-   $Oopt_DoSpecialise            = '-fspecialise';
-   $Oopt_FoldrBuild              = 0; # *Off* by default!
-   $Oopt_UsageSPInf               = ''; # Off by default
-} # end of setupOptFlags
-
-# Assign defaults to these right away.
-&setupOptFlags();
-\end{code}
-
-Things to do with C compilers/etc:
-
-(added -Wimplicit: implicit prototypes cause very hard-to-find
-problems, so I'm turing on the warnings -- SDM 4/5/98)
-
-\begin{code}
-$CcRegd                = $GHC_OPT_HILEV_ASM;
-@CcBoth_flags  = ('-S','-Wimplicit');   # flags for *any* C compilation
-@CcInjects     = ("#include \"Stg.h\"\n", "#include \"HsStd.h\"\n");
-
-# GCC flags: 
-#    those for all files, 
-#    those only for .c files;
-#    those only for .hc files
-
-@CcRegd_flags    = ();
-@CcRegd_flags_c         = ();
-@CcRegd_flags_hc = ();
-
-$As             = ''; # "assembler" is normally GCC
-@As_flags       = ();
-
-$Lnkr           = ''; # "linker" is normally GCC
-@Ld_flags       = ();
-@Dll_flags      = ();
-
-# 'nm' is used for consistency checking (ToDo: mk-world-ify)
-# ToDo: check the OS or something ("alpha" is surely not the crucial question)
-$Nm = ($TargetPlatform =~ /^alpha-/) ? 'nm -B' : 'nm';
-\end{code}
-
-Warning packages that are controlled by -W and -Wall.  The 'standard'
-warnings that you get all the time are
-       
-       -fwarn-overlapping-patterns
-       -fwarn-missing-methods
-       -fwarn-missing-fields
-       -fwarn-deprecations
-       -fwarn-duplicate-exports
-       -fwarn-hi-shadowing
-
-these are turned off by -Wnot.
-
-\begin{code}
-@StandardWarnings = ('-fwarn-overlapping-patterns', 
-                    '-fwarn-missing-methods',
-                    '-fwarn-missing-fields',
-                    '-fwarn-deprecations',
-# DISABLE DUE TO DUPLICATE INCLUDE PATHS (ToDo): '-fwarn-hi-shadowing',
-                    '-fwarn-duplicate-exports');
-@MinusWOpts              = (@StandardWarnings, 
-                    '-fwarn-unused-binds',
-                    '-fwarn-unused-matches',
-                    '-fwarn-incomplete-patterns', 
-                    '-fwarn-unused-imports');
-@MinusWallOpts           = (@MinusWOpts, 
-                    '-fwarn-type-defaults',
-                    '-fwarn-name-shadowing',
-                    '-fwarn-missing-signatures');
-\end{code}
-
-What options \tr{-user-setup-a} turn into (user-defined ``packages''
-
-of options).  Note that a particular user-setup implies a particular
-Prelude ({\em including} its interface file(s)).
-\begin{code}
-$BuildTag      = ''; # default is sequential build w/ Appel-style GC
-
-%BuildDescr    = (# system ways begin
-                   '',     'Normal Sequential',
-                  '_p',    "Profiling",
-                  '_t',    "Ticky-ticky Profiling",
-                  '_u',    "Unregisterised",
-                  '_s',    "SMP",
-                  '_mp',   "Parallel",
-                  '_mg',   "Gransim",
-                  # system ways end
-                  '_a',    "$WAY_a_NAME",
-                  '_b',    "$WAY_b_NAME",
-                  '_c',    "$WAY_c_NAME",
-                  '_d',    "$WAY_d_NAME",
-                  '_e',    "$WAY_e_NAME",
-                  '_f',    "$WAY_f_NAME",
-                  '_g',    "$WAY_g_NAME",
-                  '_h',    "$WAY_h_NAME",
-                  '_i',    "$WAY_i_NAME",
-                  '_j',    "$WAY_j_NAME",
-                  '_k',    "$WAY_k_NAME",
-                  '_l',    "$WAY_l_NAME",
-                  '_m',    "$WAY_m_NAME",
-                  '_n',    "$WAY_n_NAME",
-                  '_o',    "$WAY_o_NAME",
-                  '_A',    "$WAY_A_NAME",
-                  '_B',    "$WAY_B_NAME" );
-
-# these are options that are "fed back" through the option processing loop
-#
-%SetupOpts = 
-       (
-       '_a', "$WAY_a_REAL_OPTS",
-       '_b', "$WAY_b_REAL_OPTS",
-       '_c', "$WAY_c_REAL_OPTS",
-       '_d', "$WAY_d_REAL_OPTS",
-       '_e', "$WAY_e_REAL_OPTS",
-       '_f', "$WAY_f_REAL_OPTS",
-       '_g', "$WAY_g_REAL_OPTS",
-       '_h', "$WAY_h_REAL_OPTS",
-       '_i', "$WAY_i_REAL_OPTS",
-       '_j', "$WAY_j_REAL_OPTS",
-       '_k', "$WAY_k_REAL_OPTS",
-       '_l', "$WAY_l_REAL_OPTS",
-       '_m', "$WAY_m_REAL_OPTS",
-       '_n', "$WAY_n_REAL_OPTS",
-       '_o', "$WAY_o_REAL_OPTS",
-       '_A', "$WAY_A_REAL_OPTS",
-       '_B', "$WAY_B_REAL_OPTS",
-
-       # system ways
-       '_p',  "-fscc-profiling -DPROFILING -optc-DPROFILING",
-       '_t',  "-fticky-ticky -DTICKY_TICKY -optc-DTICKY_TICKY",
-       '_u',  "-optc-DNO_REGS -optc-DUSE_MINIINTERPRETER -fno-asm-mangling -funregisterised",
-       '_s',  "-fsmp -optc-pthread -optl-pthread -optc-DSMP",
-       '_mp', "-fparallel -D__PARALLEL_HASKELL__ -optc-DPAR",
-       '_mg', "-fgransim -D__GRANSIM__ -optc-DGRAN");
-
-# where to look for interface files (system hi's, i.e., prelude and syslibs)
-@SysImport_dir = ( $INSTALLING )
-                   ? ( "$InstLibDirGhc/imports/std" )
-                   : ( "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std" );
-
-# We need to look in ghc/ and glaExts/ when searching for implicitly needed .hi files, but 
-# we should really *not* look there for explicitly imported modules.
-
-$Haskell1Version = 5; # i.e., Haskell 1.4
-@Cpp_define     = ();
-
-# Cpp symbols defined when we're processing Haskell source.
-
-@HsSourceCppOpts = 
-       ( "-D__HASKELL__=98"
-       , "-D__HASKELL1__=$Haskell1Version"
-       , "-D__GLASGOW_HASKELL__=$ProjectVersionInt"
-       , "-D__HASKELL98__"
-       , "-D__CONCURRENT_HASKELL__"
-       );
-
-
-@SysLibrary_dir = ( ( $INSTALLING )    #-syslib things supplied by the system
-                   ? $InstLibDirGhc
-                   : ( "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR"
-                     , "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/gmp"
-                     , "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std"
-                     , "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std/cbits"
-                     )
-                 );
-
-# make depend for Haskell
-$MkDependHS
-       = ( $INSTALLING ) ? "$InstLibExecDirGhc/mkdependHS"
-                         : "$TopPwd/$CURRENT_DIR/$GHC_MKDEPENDHS";
-# Fill in later
-@MkDependHS_flags = ();
-
-# do_link flag should not be reset while rescanning the cmd-line.
-$Do_lnkr    = 1;
-$Specific_output_dir = '';     # set by -odir <dir>
-$Specific_output_file = '';    # set by -o <file>; "-" for stdout
-\end{code}
-
-Function to initialise the per-compilation-unit globals that
-are used to guide and control the invocation of the different phases.
-
-\begin{code} 
-sub initDriverGlobals {
-
-# reset the following options:
-# RTS flags to use while compiling
-@HsC_rts_flags      = ();
-@HsC_flags     = ();
-@HsC_antiflags  = ();
-\end{code}
-
-The optimisations/etc to be done by the compiler are {\em normally}
-expressed with a \tr{-O} (or \tr{-O2}) flag, or by its absence.
-
-\begin{code}
-$OptLevel      = 0; # no -O == 0; -O == 1; -O2 == 2; -Ofile == 3
-$MinusO2ForC   = 0; # set to 1 if -O2 should be given to C compiler
-$StolenX86Regs = 4; # **HACK*** of the very worst sort
-$CoreLint      = '';
-$USPLint       = '';
-$StgLint       = '';
-
-# The SplitMarker is the string/character used to mark end of element
-# in import lists.
-$SplitMarker    = ':';
-@Import_dir    = ('.'); #-i things
-@Include_dir   = ('.'); #-I things; other default(s) stuck on AFTER option processing
-
-@UserLibrary_dir= ();  #-L things;...
-@UserLibrary           = ();   #-l things asked for by the user
-
-@SysLibrary = (); # will be built up as we go along
-\end{code}
-
-We are given a list of files with various presumably-known suffixes
-(unknown-suffix files go straight to the linker).  For each file, we
-begin by assuming that we'll run every phase over it.  However: (1)
-global flags (\tr{-c}, \tr{-S}, etc.) tell us not to run any phase
-past a certain point; and (2) the file's suffix tells us what phase to
-start with.  Linking is weird and kept track of separately.
-
-Here are the initial defaults applied to all files:
-\begin{code}
-$Cpp_flag_set = 0;       # (hack)
-$Only_preprocess_C = 0;          # pretty hackish
-$Only_preprocess_hc = 0;  # ditto
-$Only_generate_deps = 0;  # ""
-$Only_generate_dll  = 0;
-$PostprocessCcOutput = 0;
-
-# Win32 only:
-#    static = 0 => produce code for DLLs (when compiling & linking.)
-$Static = 1;
-$Static = 0 if ($EnableWin32DLLs eq 'YES');
-
-# Output language
-$HaveNativeCodeGen = $GhcWithNativeCodeGen;
-$HscLang = 'C';        # 'C'    ==> .hc output; 
-                       # 'asm'  ==> .s output; 
-                       # 'java' ==> .java output
-                       # 'none' ==> no code output
-$HscLang = 'asm'
-    if ($HaveNativeCodeGen eq 'YES') && $TargetPlatform =~ /^(i386)-/;
-
-$ProduceHi    = '-hifile=';
-$HiOnStdout   = 0;
-$HiWith       = '';
-$HiDiff_flag  = '';
-$Keep_HiDiffs = 0;
-
-$CollectingGCstats = 0;
-$CollectGhcTimings = 0;
-$DEBUGging = '';       # -DDEBUG and all that it entails (um... not really)
-$PROFing = '';         # set to p or e if profiling
-$PROFauto = '';                # set to relevant hsc flag if -auto or -auto-all
-$PROFcaf  = '';                # set to relevant hsc flag if -caf-all
-$PROFdict = '';                # set to relevant hsc flag if -auto-dicts
-$PROFignore_scc = '';  # set to relevant parser flag if explicit sccs ignored
-$UNPROFscc_auto = '';  # set to relevant hsc flag if forcing auto sccs without profiling
-$TICKYing = '';        # set to t if compiling for ticky-ticky profiling
-$PARing = '';          # set to p if compiling for PAR
-$GRANing = '';         # set to g if compiling for GRAN
-$UNREGing = ($GhcWithRegisterised eq 'YES') ? '' : 'u';
-$Specific_hi_file = '';                # set by -ohi <file>; "-" for stdout
-$Specific_dump_file = '';      # set by -odump <file>; "-" for stdout
-$Using_dump_file = 0;
-$Isuffix    = '';
-$Osuffix    = '';      # default: use the normal suffix for that kind of output
-$HiSuffix   = 'hi';
-$HiSuffix_prelude = '';
-$CompilingPrelude=0;
-$Do_recomp_chkr = 1;   # Use the recompilation checker by default
-$Do_cc     = -1;   # a MAGIC indeterminate value; will be set to 1 or 0.
-$Do_as     = 1;
-
-$Keep_hc_file_too = 0;
-$Keep_s_file_too = 0;
-$UseGhcInternals = 0; # if 1, may use GHC* modules
-$SplitObjFiles = 0;
-$DoAsmMangling = 1; # on by default, off by -fno-asm-mangling
-$NoOfSplitFiles = 0;
-$Dump_parser_output = 0;
-$Dump_raw_asm = 0;
-$Dump_asm_splitting_info = 0;
-$NoImplicitPrelude = 0;
-# 1 => don't tell the linker to hoist in PrelMain.Main, as an 
-# external main is provided instead.
-$NoHaskellMain=0;
-
-# Hash to keep track of 
-%Syslibs_added = ();
-
-} # end of initDriverGlobals (Sigh)
-
-# we split the argv passed to the driver into three:
-
-# the list of files
-@Input_file = ();
-
-# and files to be linked...
-@Link_file  = ();
-
-# and whatever else
-@Cmd_opts  = ();
-
-# cmd line options prefixing the unit we're compiling
-@File_options = ();
-
-\end{code}
-
-We inject consistency-checking information into \tr{.hc} files (both
-when created by the Haskell compiler and when compiled by the C
-compiler), so that we can check that an executable is made from
-consistently-built pieces.  (The check is normally done just after
-linking.)  The checking is done by introducing/munging
-\tr{what(1)}-style strings.  Anyway, here are the relevant global
-variables and their defaults:
-\begin{code}
-$LinkChk = 0;  # set to 0 if the link check should *not* be done
-
-# major & minor version numbers; major numbers must always agree;
-# minor disagreements yield a warning.
-$HsC_major_version = $HscMajorVersion;
-$HsC_minor_version = $HscMinorVersion;
-$Cc_major_version  = $CcMajorVersion;
-$Cc_minor_version  = $CcMinorVersion;
-
-# options: these must always agree
-$HsC_consist_options = '';    # we record, in this order:
-                             #     Build tag; debugging?
-$Cc_consist_options  = '';    # we record, in this order:
-                             #     Build tag; debugging?
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-parse-argv]{Munge the command-line options}
-%*                                                                     *
-%************************************************************************
-
-Now slurp through the arguments.
-\begin{code}
-
-&initDriverGlobals();
-&splitCmdLine(@ARGV);
-# Run through the cmd-line first time.
-&processArgs(@Cmd_opts);
-
-# Check to see if driver is only in the business
-# to generate dependencies
-if (  $Status == 0 && $Only_generate_deps ) {
-
-    push (@MkDependHS_flags, "-o$Osuffix") if $Osuffix;
-    # They're not (currently) needed, but we need to quote any -#include options
-    foreach (@Cmd_opts) {
-       s/-#include.*$/'$&'/g;
-    };
-    local($to_do) = "$MkDependHS @MkDependHS_flags @HsSourceCppOpts -- @Cmd_opts -- @Input_file" ;
-    &run_something($to_do, 'Haskell dependencies');
-    exit $Status;
-}
-
-# ..or just to construct a (Haskell) DLL.
-if (  $Status == 0 && $Only_generate_dll && $EnableWin32DLLs ) {
-
-    &createWin32DLL();
-    exit $Status;
-}
-
-# if there are several input files,
-# we don't allow \tr{-o <file>} or \tr{-ohi <file>} options...
-# (except if linking, of course)
-
-if ($#Input_file > 0 && ( ! $Do_lnkr )) {
-    if ( ($Specific_output_file ne '' && $Specific_output_file ne '-')
-      || ($Specific_hi_file ne ''     && $Specific_hi_file ne '-') ) {
-       print STDERR "$Pgm: You can't use -o or -ohi options if you have multiple input files.\n";
-       print STDERR "\tPerhaps the -odir option will do what you want.\n";
-       $Status++;
-    }
-}
-
-# check for various pathological -o and -odir combinations...
-if ($Specific_output_dir ne '' && $Specific_output_file ne '') {
-    if ($Specific_output_file eq '-') {
-       print STDERR "$Pgm: can't set output directory with -ohi AND have output to stdout\n";
-       $Status++;
-    } else { # amalgamate...
-       $Specific_output_file = "$Specific_output_dir/$Specific_output_file";
-       # ToDo: check we haven't got a junk name now...
-       $Specific_output_dir  = ''; # reset
-    }
-}
-
-# crash and burn if there were errors
-if ( $Status > 0 ) {
-    print STDERR $ShortUsage;
-    exit $Status;
-}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-post-argv-mangling]{Setup after reading options}
-%*                                                                     *
-%************************************************************************
-
-%************************************************************************
-%*                                                                     *
-\subsection{Set up for optimisation level (\tr{-O} or whatever)}
-%*                                                                     *
-%************************************************************************
-
-We come now to the default ``wads of options'' that are turned on by
-\tr{-O0} (do min optimisation), \tr{-O} (ordinary optimisation),
-\tr{-O2} (aggressive optimisation), or no O-ish flag (compile speed is
-more important).
-
-The user can also specify his/her own list of options in a file; in
-that case, the work is already done (see stuff about @minusO3@,
-earlier...).
-
-GHC allows very precise control of what happens during a compilation.
-Core-to-Core and STG-to-STG passes can be run in any order, as many
-times as you like.  Individual transformations can be turned on or
-disabled.
-
-Sadly, however, there are some interdependencies \& Things You Must
-Not Do.  Here is the list.
-
-CORE-TO-CORE PASSES:
-\begin{description}
-\item[\tr{-fspecialise}:]
-The specialiser must have dependency-analysed input; but if you run
-the simplifier to do this, you must not let it toss away unused
-bindings!  (The typechecker conveys some specialisation info via
-``unused'' bindings...)
-
-\item[\tr{-ffloat-inwards}:]
-Floating inwards should be done before strictness analysis, because
-the latter will give better results.
-
-\item[\tr{-fstatic-args}:]
-The static-arguments-transformation pass {\em must} have the
-simplifier run right after it.
-
-\item[\tr{-fcalc-inlinings[12]}:]
-Not required, but there may be slight gains by re-simplifying after
-this is done.  (You could then \tr{-fcalc-inlinings} again, just for
-fun.)
-
-\item[\tr{-ffull-laziness}:]
-The (outwards-)let-floater should be the {\em last} Core-to-Core pass
-that's run.  (Um, well, howzabout the simplifier just once more...)
-\end{description}
-
-\begin{code}
-
-sub setupOptimiseFlags {
-
-       # this pass-ordering sequence was agreed by Simon and Andr\'e
-       # (WDP 94/07, 94/11).
-
-   @HsC_minusNoO_flags 
-    = (        
-       '-fsimplify',
-         '[', 
-               $Oopt_MaxSimplifierIterations,
-         ']',
-
-       $Oopt_AddAutoSccs,
-       $Oopt_FinalStgProfilingMassage
-      );
-
-   @HsC_minusO_flags # NOTE: used for *both* -O and -O2 (some conditional bits)
-    = (
-       '-ffoldr-build-on',
-
-        '-fdo-eta-reduction',
-       '-fdo-lambda-eta-expansion',
-       '-fcase-of-case',
-       '-fcase-merge',
-       '-flet-to-case',
-
-       # initial simplify: mk specialiser happy: minimum effort please
-
-       '-fsimplify',
-         '[', 
-               '-finline-phase0',      # Don't inline anything till full laziness has bitten
-                                       # In particular, inlining wrappers inhibits floating
-                                       # e.g. ...(case f x of ...)...
-                                       #  ==> ...(case (case x of I# x# -> fw x#) of ...)...
-                                       #  ==> ...(case x of I# x# -> case fw x# of ...)...
-                                       # and now the redex (f x) isn't floatable any more
-
-               '-fno-rules',           # Similarly, don't apply any rules until after full laziness
-                                       # Notably, list fusion can prevent floating.
-
-               '-fno-case-of-case',    # Don't do case-of-case transformations.
-                                       # This makes full laziness work better
-
-               '-fmax-simplifier-iterations2',
-         ']',
-
-       # Specialisation is best done before full laziness
-       # so that overloaded functions have all their dictionary lambdas manifest
-       ($Oopt_DoSpecialise) ? ( $Oopt_DoSpecialise, ) : (),
-       '-ffloat-outwards',
-       '-ffloat-inwards',
-
-       '-fsimplify',
-         '[', 
-               '-finline-phase1',
-               # Want to run with inline phase 1 after the specialiser to give
-               # maximum chance for fusion to work before we inline build/augment
-               # in phase 2.  This made a difference in 'ansi' where an overloaded
-               # function wasn't inlined till too late.
-               $Oopt_MaxSimplifierIterations,  
-         ']',
-
-        $Oopt_UsageSPInf, # infer usage information here in case we need it later.
-                          # (add more of these where you need them --KSW 1999-04)
-
-       '-fsimplify',
-         '[', 
-               # Need inline-phase2 here so that build/augment get 
-               # inlined.  I found that spectral/hartel/genfft lost some useful
-               # strictness in the function sumcode' if augment is not inlined
-               # before strictness analysis runs
-
-               '-finline-phase2',
-               '-fmax-simplifier-iterations2',
-         ']',
-
-
-       '-fsimplify',
-         '[', 
-               '-fmax-simplifier-iterations2',
-               # No -finline-phase: allow all Ids to be inlined now
-               # This gets foldr inlined before strictness analysis
-         ']',
-
-       '-fstrictness',
-       '-fcpr-analyse',
-       '-fworker-wrapper',
-
-       '-fsimplify',
-         '[', 
-               $Oopt_MaxSimplifierIterations,  
-               # No -finline-phase: allow all Ids to be inlined now
-         ']',
-
-       '-ffloat-outwards',     # nofib/spectral/hartel/wang doubles in speed if you
-                               # do full laziness late in the day.  It only happens
-                               # after fusion and other stuff, so the early pass doesn't
-                               # catch it.  For the record, the redex is 
-                               #       f_el22 (f_el21 r_midblock)
-
-# Leave out lambda lifting for now
-#      '-fsimplify',   # Tidy up results of full laziness
-#        '[', 
-#              '-fmax-simplifier-iterations2',
-#        ']',
-#      '-ffloat-outwards-full',        
-
-       # We want CSE to follow the final full-laziness pass, because it may
-       # succeed in commoning up things floated out by full laziness.
-       #
-       # CSE must immediately follow a simplification pass, because it relies
-       # on the no-shadowing invariant.  See comments at the top of CSE.lhs
-       # So it must NOT follow float-inwards, which can give rise to shadowing,
-       # even if its input doesn't have shadows.  Hence putting it between
-       # the two passes.
-       '-fcse',        
-                       
-
-       '-ffloat-inwards',
-
-# Case-liberation for -O2.  This should be after
-# strictness analysis and the simplification which follows it.
-
-#      ( ($OptLevel != 2)
-#        ? ''
-#      : "-fliberate-case -fsimplify [ $Oopt_FB_Support -ffloat-lets-exposing-whnf -ffloat-primops-ok -fcase-of-case -fdo-case-elim -fcase-merge -fdo-lambda-eta-expansion -freuse-con -flet-to-case $Oopt_MaxSimplifierIterations $Oopt_ShowSimplifierProgress ]" ),
-
-#      '-fliberate-case',
-
-# Final clean-up simplification:
-
-       '-fsimplify',
-         '[', 
-               $Oopt_MaxSimplifierIterations,  
-               # No -finline-phase: allow all Ids to be inlined now
-         ']',
-
-      #        '-fstatic-args',
-
-      # stg2stg passes
-#      '-flambda-lift',
-       $Oopt_FinalStgProfilingMassage,
-       $Oopt_StgStats,
-
-      # flags for stg2stg
-       '-flet-no-escape',
-
-      # SPECIAL FLAGS for -O2
-       ($OptLevel == 2) ? (
-           # none at the present time
-       ) : (),
-      );
-
-\end{code}
-
-Sort out what we're going to do about optimising.  First, the @hsc@
-flags and regular @cc@ flags to worry about:
-\begin{code}
-if ( $OptLevel <= 0 ) {
-
-    # for this level, we tell the parser -fignore-interface-pragmas
-    push(@HsC_flags, '-fignore-interface-pragmas');
-    # and tell the compiler not to produce them
-    push(@HsC_flags, '-fomit-interface-pragmas');
-
-    &add_Hsc_flags( @HsC_minusNoO_flags );
-    push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O');        # not optional!
-
-} elsif ( $OptLevel == 1 || $OptLevel == 2 ) {
-
-    &add_Hsc_flags( @HsC_minusO_flags );
-    push(@CcBoth_flags, ($MinusO2ForC || $OptLevel == 2) ? '-O2' : '-O'); # not optional!
-    # -O? to GCC is not optional! -O2 probably isn't worth it generally,
-    # but it *is* useful in compiling the garbage collector.
-
-} else { # -Ofile, then...
-
-    &add_Hsc_flags( @HsC_minusO3_flags );
-    push(@HsC_flags, $Oopt_FinalStgProfilingMassage) if $Oopt_FinalStgProfilingMassage;
-
-    push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O');        # possibly to be elaborated...
-}
-
-} # setupOptimiseFlags
-
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Check for consistency, etc.}
-%*                                                                     *
-%************************************************************************
-
-Sort out @$BuildTag@, @$PROFing@, @$PARing@,
-@$GRANing@, @$TICKYing@, @UNREGing@:
-\begin{code}
-sub setupBuildFlags {
-
-   # PROFILING stuff after argv mangling:
-   if ( ! $PROFing ) {
-     # add -auto sccs even if not profiling !
-     push(@HsC_flags, $UNPROFscc_auto) if $UNPROFscc_auto;
-
-   } else {
-      push(@HsC_flags, $PROFauto) if $PROFauto;
-      push(@HsC_flags, $PROFcaf)  if $PROFcaf;
-      push(@HsC_flags, $PROFdict) if $PROFdict;
-
-      $Oopt_FinalStgProfilingMassage = '-fmassage-stg-for-profiling';
-
-      # Ignore user sccs when auto annotating, but warn when doing so.
-      $PROFignore_scc = '-W' if $PROFauto; 
-  }
-  #if ( $BuildTag ne '' ) {
-  #    local($b) = $BuildDescr{$BuildTag};
-  #    if ($PARing    eq 'p') { print STDERR "$Pgm: Can't mix $b with -parallel.\n"; exit 1; }
-  #    if ($GRANing   eq 'g') { print STDERR "$Pgm: Can't mix $b with -gransim.\n"; exit 1; }
-  #    if ($TICKYing  eq 't') { print STDERR "$Pgm: Can't mix $b with -ticky.\n"; exit 1; }
-
-  #    # ok to have a user-way profiling build
-  #    # eval the profiling opts ... but leave user-way BuildTag 
-  #    if ($PROFing   eq 'p') { &processArgs(split(' ', $SetupOpts{'_p'})); } # eval($EvaldSetupOpts{'_p'}); }
-
-  if ( $PROFing eq 'p' ) {
-      if ($PARing   eq 'p') { print STDERR "$Pgm: Can't do profiling with -parallel.\n"; exit 1; }
-      if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't do profiling with -gransim.\n"; exit 1; }
-      if ($TICKYing eq 't') { print STDERR "$Pgm: Can't do profiling with -ticky.\n"; exit 1; }
-      $BuildTag = '_p' ;
-
-  } elsif ( $PARing eq 'p' ) {
-      if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't mix -parallel with -gransim.\n"; exit 1; }
-      if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -parallel with -ticky.\n"; exit 1; }
-      $BuildTag = '_mp';
-
-      if ( $Do_lnkr && ( ! $ENV{'PVM_ROOT'} || ! $ENV{'PVM_ARCH'} )) {
-         print STDERR "$Pgm: both your PVM_ROOT and PVM_ARCH environment variables must be set for linking under -parallel.\n";
-         exit(1);
-      }
-
-  } elsif ( $SMPing eq 's') {
-      $BuildTag = '_s';
-
-  } elsif ( $GRANing eq 'g' ) {
-      if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -gransim with -ticky.\n"; exit 1; }
-      $BuildTag = '_mg';
-
-  } elsif ( $TICKYing eq 't' ) {
-      $BuildTag = '_t';
-
-  } elsif ( $UNREGing eq 'u' ) {
-      if ($GhcWithRegisterised eq 'YES') {
-        $BuildTag = '_u';
-      }
-  }
-\end{code}
-
-After the sanity checks, add flags to the necessary parts of the driver pipeline:
-
-\begin{code}
-  if ( $BuildTag ne '' ) { # something other than normal sequential...
-
-      local($Tag) = "${BuildTag}";
-      $Tag =~ s/_//;   # move the underscore to the back
-
-      $HscLang = 'C';  # must go via C
-      &processArgs(split(' ', $SetupOpts{$BuildTag}));
-#      eval($EvaldSetupOpts{$BuildTag});
-  }
-\end{code}
-
-Decide what the consistency-checking options are in force for this run:
-\begin{code}
-
-  $HsC_consist_options = "${BuildTag},${DEBUGging}";
-  $Cc_consist_options  = "${BuildTag},${DEBUGging}";
-
-  #
-  # Funny place to put it, but why not.
-  #
-  if ( $HiSuffix_prelude eq '' ) {
-
-       if ($CompilingPrelude) {
-         $HiSuffix_prelude = "$HiSuffix" if $CompilingPrelude;
-       } else {
-         local($Tag) = "${BuildTag}";
-  
-         $Tag =~ s/_//;
-         $Tag =  "${Tag}_" if $Tag ne '';
-         $HiSuffix_prelude="${Tag}hi";
-       }
-  }
-} # setupBuildFlags
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Add on machine-specific C-compiler flags}
-%*                                                                     *
-%************************************************************************
-
-Shove on magical machine-specific options.  We use \tr{unshift} to
-stick them on the {\em front} of the arrays, so that ``later''
-user-specified flags can clobber them (e.g., \tr{-U__STG_REV_TBLS__}).
-
-Note: a few ``always apply'' flags were set at the very beginning.
-
-\begin{code}
-sub setupMachOpts {
-
-  if ($TargetPlatform =~ /^alpha-/) {
-      unshift(@CcBoth_flags,  ('-static'));
-
-  } elsif ($TargetPlatform =~ /^hppa/) {
-      unshift(@CcBoth_flags,  ('-static'));
-      #
-      # We don't put in '-mlong-calls', because it's only
-      # needed for very big modules (sigh), and we don't want
-      # to hobble ourselves further on all the other modules
-      # (most of them).
-      #  
-      # [Dated comment (gcc-2.6.x?), -mlong-calls is no longer
-      #  a supported gcc HPPA flag]
-      unshift(@CcBoth_flags,  ('-D_HPUX_SOURCE'));
-        # ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
-        # (very nice, but too bad the HP /usr/include files don't agree.)
-
-  } elsif ($TargetPlatform =~ /^i386-/) {
-      # -fno-defer-pop : basically the same game as for m68k
-      #
-      # -fomit-frame-pointer : *must* in .hc files; because we're stealing
-      #         the fp (%ebp) for our register maps.
-
-      unshift(@CcRegd_flags_hc, '-fno-defer-pop');
-      unshift(@CcRegd_flags_hc, '-fomit-frame-pointer');
-      unshift(@CcRegd_flags,    "-DSTOLEN_X86_REGS=$StolenX86Regs");
-      
-      unshift(@CcBoth_flags,  ('-DDONT_WANT_WIN32_DLL_SUPPORT')) if ($Static);
-
-  } elsif ($TargetPlatform =~ /^m68k-/) {
-      # -fno-defer-pop : for the .hc files, we want all the pushing/
-      #    popping of args to routines to be explicit; if we let things
-      #    be deferred 'til after an STGJUMP, imminent death is certain!
-      #
-      # -fomit-frame-pointer : *don't*
-      #           It's better to have a6 completely tied up being a frame pointer
-      #           rather than let GCC pick random things to do with it.
-      #           (If we want to steal a6, then we would try to do things
-      #           as on iX86, where we *do* steal the frame pointer [%ebp].)
-
-      unshift(@CcRegd_flags_hc, '-fno-defer-pop');
-      unshift(@CcRegd_flags,    '-fno-omit-frame-pointer');
-       # maybe gives reg alloc a better time
-       # also: -fno-defer-pop is not sufficiently well-behaved without it
-
-  } elsif ($TargetPlatform =~ /^mips-/) {
-      unshift(@CcBoth_flags,  ('-static'));
-
-  } elsif ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
-      unshift(@CcBoth_flags,  ('-static')); # always easier to start with
-      unshift(@CcRegd_flags, ('-finhibit-size-directive')); # avoids traceback tables
-  } elsif ($TargetPlatform =~ /^sparc-/) {
-  }
-} # end of setupMachOpts
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Set up for warnings}
-%*                                                                     *
-%************************************************************************
-
-Several warnings are turned on by default.  These are supposed to be
-the 'I'm pretty sure you've made a mistake here' kind of warnings.
-The rest are turned on by the -W and -Wall options, or individually
-via their -fwarn and -fno-warn flags.
-
-\begin{code}
-sub setupWarningFlags {
-&add_Hsc_flags( @StandardWarnings );
-}
-\end{code}
-
-Same unshifting magic, but for special linker flags.
-
-The configure script determines whether the object file symbol tables
-have a leading underscore, and sets @LeadingUnderscore@ accordingly.
-(The driver script `sees' the setting of the @LeadingUnderscore@
-by having the Makefile prepend it).
-
-\begin{code}
-sub setupLinkOpts {
-  local($uscore) = ( ${LeadingUnderscore} eq 'YES' ) ? '_' : '';
-
-  unshift(@Ld_flags,
-        (($Ld_main) ? ( '-u', "${uscore}Main_" . $Ld_main . '_closure' ) : ()));
-
-  # things that are referenced by the RTS - make sure that we pull 'em in
-  unshift(@Ld_flags,
-         ( '-u', "${uscore}PrelBase_Izh_static_info"
-          ,'-u', "${uscore}PrelBase_Czh_static_info"
-          ,'-u', "${uscore}PrelFloat_Fzh_static_info"
-          ,'-u', "${uscore}PrelFloat_Dzh_static_info"
-          ,'-u', "${uscore}PrelAddr_Azh_static_info"
-          ,'-u', "${uscore}PrelAddr_Wzh_static_info"
-          ,'-u', "${uscore}PrelAddr_I64zh_static_info"
-          ,'-u', "${uscore}PrelAddr_W64zh_static_info"
-          ,'-u', "${uscore}PrelStable_StablePtr_static_info"
-         ,'-u', "${uscore}PrelBase_Izh_con_info"
-          ,'-u', "${uscore}PrelBase_Czh_con_info"
-          ,'-u', "${uscore}PrelFloat_Fzh_con_info"
-          ,'-u', "${uscore}PrelFloat_Dzh_con_info"
-          ,'-u', "${uscore}PrelAddr_Azh_con_info"
-          ,'-u', "${uscore}PrelAddr_Wzh_con_info"
-          ,'-u', "${uscore}PrelAddr_I64zh_con_info"
-          ,'-u', "${uscore}PrelAddr_W64zh_con_info"
-          ,'-u', "${uscore}PrelStable_StablePtr_con_info"
-          ,'-u', "${uscore}PrelBase_False_closure"
-          ,'-u', "${uscore}PrelBase_True_closure"
-          ,'-u', "${uscore}PrelPack_unpackCString_closure"
-          ,'-u', "${uscore}PrelException_stackOverflow_closure"
-          ,'-u', "${uscore}PrelException_heapOverflow_closure"
-          ,'-u', "${uscore}PrelException_NonTermination_closure"
-          ,'-u', "${uscore}PrelException_PutFullMVar_closure"
-          ,'-u', "${uscore}PrelException_BlockedOnDeadMVar_closure"
-          ,'-u', "${uscore}PrelWeak_runFinalizzerBatch_closure"
-          ,'-u', "${uscore}__init_Prelude"
-          ,'-u', "${uscore}__init_PrelMain"
-       ));
-  if (!$NoHaskellMain) {
-   unshift (@Ld_flags,'-u', "${uscore}PrelMain_mainIO_closure");
-  }
-  if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
-    # sometimes we have lots of toc entries...
-    #  unshift(@Ld_flags, ('-Xlinker -bbigtoc -Xlinker -bnoquiet')); 
-    unshift(@Ld_flags, ('-Xlinker -bbigtoc')); 
-  }
-  if ($TargetPlatform =~ /^hppa/) {
-    unshift(@Ld_flags, ('-Xlinker +vnocompatwarnings'));
-  }
-
-} # end of setupLinkOpts
-
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Set up include paths and system-library enslurpment}
-%*                                                                     *
-%************************************************************************
-
-Now that we know what garbage-collector, etc., are required, we can
-finalise our list of libraries to slurp through, and generally Get
-Ready for Business.
-
-\begin{code}
-sub setupIncPaths {
-  # default includes must be added AFTER option processing
-  if ( ! $INSTALLING ) {
-      push (@Include_dir, "$TopPwd/${CURRENT_DIR}/${GHC_INCLUDE_DIR}");
-  } else {
-      push (@Include_dir, "$InstLibDirGhc/includes");
-  }
-} # end of setupIncPaths
-\end{code}
-
-\begin{code}
-sub setupSyslibs {
-  push(@SysLibrary, ( '-lHSstd', '-lHSstd_cbits' )); # basic I/O and prelude stuff
-
-  local($f);
-  foreach $f (@SysLibrary) {
-      next if $f =~ /_cbits/;
-      $f .= $BuildTag if $f =~ /^-lHS/;
-  }
-
-  # Push library HSrts, plus boring clib bit
-  push(@SysLibrary, "-lHSrts${BuildTag}");
-
-  #
-  # RTS compiled with cygwin32, uses the WinMM API
-  # to implement the itimers, since cygwin.dll does not
-  # support it. Only reqd. for `ways' that use itimers.
-  #
-  push(@SysLibrary, '-lwinmm')   if ($TargetPlatform =~ /-(mingw32|cygwin32)$/);
-   # Note: currently only tested with mingw, may cause conflicts when linking
-   #       with libcygwin.a
-  push(@SysLibrary, '-lwsock32') if ($TargetPlatform =~ /-(mingw32|cygwin32)$/);
-
-  # Push the pvm libraries
-  if ($BuildTag eq '_mp') {
-      $pvmlib = "$ENV{'PVM_ROOT'}/lib/$ENV{'PVM_ARCH'}";
-      push(@SysLibrary, "-L$pvmlib", '-lgpvm3', '-lpvm3');
-      if ( $ENV{'PVM_ARCH'} eq 'SUNMP' ) {
-          push(@SysLibrary, '-lthread', '-lsocket', '-lnsl');
-      } elsif ( $ENV{'PVM_ARCH'} eq 'SUN4SOL2' ) {
-          push(@SysLibrary, '-lsocket', '-lnsl');
-      }
-  }
-
-# Push the GNU multi-precision arith lib; and the math library
-
-# If this machine has GMP already installed, then we'll get the installed
-# lib here, because presumably the one in the tree won't have been built.
-
-if ($LibGmp eq 'not-installed') {
-  push(@SysLibrary, "-lgmp");
-} else {
-  push(@SysLibrary, "-l$LibGmp");
-}
-
-push(@SysLibrary, '-lm') if !( $TargetPlatform =~ /^.*(cygwin32|mingw32)$/ );
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Check that this system was built to do what we are asking}
-%*                                                                     *
-%************************************************************************
-
-Before continuing we check that the appropriate build is available.
-
-\begin{code}
-#die "$Pgm: no BuildAvail?? $BuildTag\n" if $BuildDescr{$BuildTag} eq '' ; # sanity
-
-if ( $BuildDescr{$BuildTag} eq '' ) {
-    print STDERR "$Pgm: a `", $BuildDescr{$BuildTag},
-       "' \"build\" is not available with your GHC setup.\n";
-    print STDERR "(It was not configured for it at your site.)\n";
-    print STDERR $ShortUsage;
-    exit 1;
-}
-
-} # end of setupSyslibs
-
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Final miscellaneous setup bits before we start going}
-%*                                                                     *
-%************************************************************************
-
-Record largest specific heapsize, if any.
-\begin{code}
-sub setupHeapStackSize {
-   $Specific_heap_size = $Specific_heap_size * $Scale_sizes_by;
-   push(@HsC_rts_flags, '-H'.$Specific_heap_size);
-   $Specific_stk_size = $Specific_stk_size * $Scale_sizes_by;
-   push(@HsC_rts_flags, "-K$Specific_stk_size");
-}
-\end{code}
-
-If no input or link files seen, then we let 'em feed in stdin; this is
-mainly for debugging.
-
-\begin{code}
-
-if ($#Input_file < 0 && $#Link_file < 0) {
-    @Input_file = ( '-' );
-
-    open(INF, "> $Tmp_prefix.hs") || &tidy_up_and_die(1,"Can't open $Tmp_prefix.hs\n");
-    print STDERR "Enter your Haskell program, end with ^D (on a line of its own):\n" if -t;
-    while (<STDIN>) { print INF $_; }
-    close(INF) || &tidy_up_and_die(1,"Failed writing to $Tmp_prefix.hs\n");
-}
-
-\end{code}
-
-Tell the world who we are, if they asked.
-\begin{code}
-print STDERR "${ProjectName}, version ${ProjectVersion}\n" if $Verbose;
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-main-loop]{Main loop: Process input files, and link if required}
-%*                                                                     *
-%************************************************************************
-
-Process the input files; don't continue with linking if there are
-problems (global variable @$Status@ non-zero).
-\begin{code}
-foreach $ifile (@Input_file) {
-    &ProcessInputFile($ifile);
-}
-
-# don't link if there were errors...
-if ( $Status > 0 ) { 
-    print STDERR $ShortUsage;
-    &tidy_up();
-    exit $Status;
-}
-
-# Link if appropriate.
-&runLinker() if $Do_lnkr;
-
-# that...  that's all, folks!
-&tidy_up();
-exit $Status; # will still be 0 if all went well
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-do-one-file]{How to process a single input file}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub ProcessInputFile {
-    local($ifile) = @_;          # input file name
-    local($ifile_root);          # root of or basename of input file
-    local($ofile_target); # ultimate output file we hope to produce
-                         # from input file (need to know for recomp
-                         # checking purposes)
-    local($hifile_target);# ditto (but .hi file)
-    local($ofile_c_stub_target); 
-    local($ofile_h_stub_target); 
-\end{code}
-
-Handle the weirdity of input from stdin.
-\begin{code}
-    if ($ifile ne '-') {
-       ($ifile_root  = $ifile) =~ s/\.[^\.\/]+$//;
-       $ofile_target = # may be reset later...
-                       ($Specific_output_file ne '' && ! $Do_lnkr)
-                       ? $Specific_output_file
-                       : &odir_ify($ifile_root, 'o');
-       $hifile_target= ($Specific_hi_file ne '')
-                       ? $Specific_hi_file
-                       : "$ifile_root.$HiSuffix"; # ToDo: odirify?
-                       # NB: may change if $ifile_root isn't module name (??)
-       ($ofile_c_stub_target = $ifile) =~s/\.[^\.\/]+$/_stub.c/;
-       ($ofile_h_stub_target = $ifile) =~s/\.[^\.\/]+$/_stub.h/;
-    } else {
-       $ifile = "$Tmp_prefix.hs"; # we know that's where we put the input
-       $ifile_root   = '_stdin';
-       $ofile_target = '_stdout'; # gratuitous?
-       $hifile_target= '_stdout'; # ditto?
-    }
-\end{code}
-
-We need to decide what phases of the compilation system we will run
-over this file.  The defaults are the ones established when processing
-flags.  (That established what the last phase run for all files is.)
-
-We do the pre-recompilation-checker phases here; the rest later.
-\begin{code}
-\end{code}
-
-Look at the suffix and decide what initial phases of compilation may
-be dropped off for this file.  Also the rather boring business of
-which files are coming-in/going-out.
-
-Again, we'll do the post-recompilation-checker parts of this later.
-\begin{code}
-    local($do_lit2pgm) = ($ifile =~ /\.lhs$/) ? 1 : 0;
-    local($do_hscpp)   = 1; # but "hscpp" might really be "cat"
-    local($do_hsc)     = 1;
-
-    # names of the files to stuff between phases
-    # defaults are temporaries
-    local($in_lit2pgm)   = $ifile;
-    local($lit2pgm_hscpp) = "$Tmp_prefix.lpp";
-    local($hscpp_hsc)    = "$Tmp_prefix.cpp";
-    local($hsc_hi)       = "$Tmp_prefix.hi";
-    local($cc_as_o)      = "${Tmp_prefix}_o.s"; # temporary for raw .s file if opt C
-    local($cc_as)        = "$Tmp_prefix.s";     # mangled or hsc-produced .s code
-    local($as_out)       = $ofile_target;
-
-    local($is_hc_file) = 1; #Is the C code .hc or .c? Assume .hc for now
-
-    # OK, let's strip off some literate junk..
-    if ($do_lit2pgm) {
-        &runLit2pgm($in_lit2pgm, $lit2pgm_hscpp)
-    } else {
-        $lit2pgm_hscpp = $ifile;
-    }
-
-    #
-    @File_options = ();
-
-    # Scan the top of the de-litted file for {-# OPTIONS #-} pragmas
-    &check_for_source_options($lit2pgm_hscpp,$ifile);
-
-    # Options found in the source file take a back seat, i.e., we scan
-    # them first. Only process the command line again if source file
-    # contained anything of interest *or* there's more than one
-    # input file (we have to reset the options).
-    #
-    if ( $#Input_file >= 0 || $#File_options >= 0) {
-        #@File_options = (@File_options, @Cmd_opts);
-
-        # Now process the command line
-        &initDriverGlobals();
-        &processArgs((@File_options,@Cmd_opts));
-       print STDERR "\nEffective command line: " .
-                    join(' ',(@File_options,@Cmd_opts)) . "\n" if $Verbose;
-    }
-    #
-    # Having got the effective command line scanned, set up
-    # the various options in prep for some real work.
-    #
-    # check the sanity of the BuildTag we're about to use,
-    # and if needs be, add some more flags and setup to
-    # the different phases.
-    #
-    &setupBuildFlags();
-    &setupOptimiseFlags();
-    &setupMachOpts();
-    &setupIncPaths();
-    &setupWarningFlags();
-    &setupHeapStackSize();
-
-    #
-    # These two variables need to be set after the
-    # command-line has been processed and the build options
-    # have be seen set up. This is because command-line options
-    # can control whether to compile vias C or not.
-    # 
-    local($do_cc)      = ( $Do_cc != -1) # i.e., it was set explicitly
-                         ? $Do_cc
-                         : ( ($HscLang eq 'C') ? 1 : 0 );
-    local($do_as)      = $Do_as;
-
-    local($hsc_out_suffix) = ( $HscLang eq 'C' )    ? "hc" : 
-                            ( $HscLang eq 'asm' )  ? "s" : 
-                            ( $HscLang eq 'java' ) ? "java" : 
-                               "" ;
-    
-    local($hsc_out)       = "$Tmp_prefix.$hsc_out_suffix" ;
-    local($hsc_out_c_stub) = "${Tmp_prefix}_stb.c";
-    local($hsc_out_h_stub) = "${Tmp_prefix}_stb.h";
-
-    if ($Only_preprocess_hc) { # stop after having run $Cc -E
-       $do_as=0;
-    }
-    if ($Only_preprocess_C)     { # stop after having run $hscpp
-       $do_hsc=0; $do_cc = 0; $do_as=0;
-    } elsif ($ifile =~ /.lhs$/ || $ifile =~ /.hs$/ ) {
-       ;
-    } elsif ($ifile =~ /\.hc$/ || $ifile =~ /_hc$/ ) { # || $ifile =~ /\.$Isuffix$/o) # ToDo: better
-       $do_hscpp = 0; $do_hsc = 0; $do_cc = 1;
-       $hsc_out = $ifile;
-       $hsc_out_c_stub = '';
-       $hsc_out_h_stub = '';
-    } elsif ($ifile =~ /\.c$/) {
-       $do_hscpp = 0; $do_hsc = 0; $do_cc = 1;
-       $hsc_out = $ifile; $is_hc_file = 0;
-       $hsc_out_c_stub = '';
-       $hsc_out_h_stub = '';
-    } elsif ($ifile =~ /\.[sS]$/) {
-       $do_hscpp = 0; $do_hsc = 0; $do_cc = 0;
-       $cc_as = $ifile;    
-    } else { # don't know what it is, but nothing to do herein...
-       $do_hscpp = 0; $do_hsc = 0; $do_cc = 0; $do_as = 0;
-    }
-
-    # hack to avoid running hscpp
-    $HsCpp = $Cat if ! $Cpp_flag_set;
-
-    &runHscpp($in_lit2pgm, $lit2pgm_hscpp, $hscpp_hsc) if $do_hscpp;
-
-\end{code}
-
-We now think about whether to run hsc/cc or not (when hsc produces .s
-stuff, it effectively takes the place of both phases).
-To get the output file name right: for each phase that we are {\em
-not} going to run, set its input (i.e., the output of its preceding
-phase) to @"$ifile_root.<suffix>"@.
-
-\begin{code}
-    local($going_interactive) = $HscLang eq 'none' || $ifile_root eq '_stdin';
-
-    #
-    # Warning issued if -keep-hc-file-too is used without
-    # -fvia-C (or the equivalent)
-    #
-    if ( $HscLang ne 'C' && $Keep_hc_file_too ) {
-       print STDERR "$Pgm: warning: Native code generator to be used, -keep-hc-file-too will be ignored\n";
-    }
-
-    if (! $do_cc && ! $do_as) { # stopping after hsc
-       $hsc_out = ($Specific_output_file ne '')
-                ? $Specific_output_file
-                : &odir_ify($ifile_root, $hsc_out_suffix);
-
-       $ofile_target = $hsc_out; # reset
-    }
-
-    if (! $do_as) { # stopping after gcc (or hsc)
-       $cc_as = ($Specific_output_file ne '')
-                ? $Specific_output_file
-                : &odir_ify($ifile_root, ( $Only_preprocess_hc ) ? 'i' : 's');
-
-       $ofile_target = $cc_as; # reset
-    }
-
-\end{code}
-
-
-Now the Haskell compiler, C compiler, and assembler
-
-\begin{code}
-   if ($do_hsc) {
-       &runHscAndProcessInterfaces( $ifile, $hscpp_hsc, $ifile_root, 
-                                    $ofile_target, $hifile_target,
-                                    $going_interactive);
-    }
-
-    if (-f $hsc_out_h_stub) {
-       &run_something("cp $hsc_out_h_stub $ofile_h_stub_target", 'Copy foreign export header file');
-    }
-
-    if (-f $hsc_out_c_stub) {
-       #
-       # Bring the C stub protos into scope when compiling the .hc file.
-       #
-       push (@CcInjects, "#include \"${hsc_out_h_stub}\"\n");
-       # Hack - ensure that the stub .h file is included in the OPTIONS section
-       #        if the .hc file is saved.
-       push (@File_options, "-#include \"${ofile_h_stub_target}\"\n");
-    }
-
-    if ($do_cc) {
-       &runGcc    ($is_hc_file, $hsc_out, $cc_as_o);
-       &runMangler($is_hc_file, $cc_as_o, $cc_as, $ifile_root) if ! $Only_preprocess_hc;
-    }
-
-    &split_asm_file($cc_as)  if $do_as && $SplitObjFiles;
-
-    # save a copy of the .s file..
-    &saveIntermediate($ifile_root , "s" , $cc_as) if ($do_as && $Keep_s_file_too);
-    &runAs($as_out, $ifile_root) if $do_as;
-
-    if (-f $hsc_out_c_stub) {
-       &run_something("rm -f $ofile_c_stub_target && echo '#include \"${ofile_h_stub_target}\"' > $ofile_c_stub_target && cat $hsc_out_c_stub >> $ofile_c_stub_target", 'Copy foreign export C stubs');
-       local ($hsc_out_s_stub);
-       local ($hsc_out_o_stub);
-       ($ofile_s_stub_target = $ofile_c_stub_target) =~ s/\.(.*)$/\.s/;
-       ($ofile_o_stub_target = $ofile_c_stub_target) =~ s/\.(.*)$//;
-
-        $ofile_o_stub_target = &osuf_ify($ofile_o_stub_target, "o");
-       if ($do_cc || $do_as) {  # might be using NCG, so check $do_as
-         &runGcc    (0, $ofile_c_stub_target, $ofile_s_stub_target);
-          &runAs     ($ofile_o_stub_target, $ofile_s_stub_target);
-       }
-    }
-
-\end{code}
-
-Finally, decide what to queue up for linker input.
-\begin{code}
-    # tentatively assume we will eventually produce linker input:
-    push(@Link_file, &odir_ify($ifile_root, 'o'));
-
-#ToDo:    local($or_isuf) = ($Isuffix eq '') ? '' : "|$Isuffix";
-
-    if ( $ifile !~ /\.(lhs|hs|hc|c|s|a|S)$/ && $ifile !~ /_hc$/ ) {
-        # There's sometimes confusion regarding .hi files; users
-       # supplying them on the command line.
-        if ( $ifile =~ /\.hi$/ ) {
-           print STDERR "$Pgm: warning: found `$ifile' on command line; interface files should not be supplied here - ignoring it.\n";
-        } else {
-          print STDERR "$Pgm: don't recognise suffix on `$ifile'; passing it through to linker\n";
-        }
-       # oops; we tentatively pushed the wrong thing; fix & do the right thing
-       pop(@Link_file); push(@Link_file, $ifile);
-    }
-
-
-} # end of ProcessInputFile
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-run-phases]{Routines to run the various phases}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub runLit2pgm {
-    local($in_lit2pgm, $lit2pgm_hscpp) = @_;
-
-    local($to_do) = "";
-
-    # Only add #line pragma if we're going to need it.
-    $to_do  = "echo '#line 1 \"$in_lit2pgm\"' > $lit2pgm_hscpp && " if ($Cpp_flag_set);
-    $to_do .= "$Unlit @Unlit_flags $in_lit2pgm -  >> $lit2pgm_hscpp";
-     
-    push(@Files_to_tidy, $lit2pgm_hscpp );
-
-    &run_something($to_do, 'literate pre-processor');
-}
-\end{code}
-
-\begin{code}
-sub runHscpp {
-    local($in_lit2pgm, $lit2pgm_hscpp, $hscpp_hsc) = @_;
-
-    local($to_do) = "";
-
-    # Strictly speaking, echoing of the following line pragma is only required
-    # on non-delit'ed input, as we've already added it during de-lit. However,
-    # hscpp will then add a {-# LINE 1 "$lit2pgm_hsc" -} to the top of the file,
-    # which is not very informative (but harmless). Hence, we uniformly have
-    # {-# LINE 1 "$in_lit2pgm" #-} as the first line to all cpp'ed hsc input.
-    #
-    $to_do = "echo '{-# LINE 1 \"$in_lit2pgm\" -}' > $hscpp_hsc && ";
-
-    if ($HsCpp eq $Cat) {
-       $to_do .= "$HsCpp $lit2pgm_hscpp >> $hscpp_hsc";
-       push(@Files_to_tidy, $hscpp_hsc );
-       &run_something($to_do, 'Ineffective C pre-processor');
-    } else {
-       local($includes) = '-I' . join(' -I',@Include_dir);
-       $to_do .= "$HsCpp $Verbose @HsCpp_flags @HsSourceCppOpts $includes $lit2pgm_hscpp >> $hscpp_hsc";
-       push(@Files_to_tidy, $hscpp_hsc );
-       &run_something($to_do, 'Haskellised C pre-processor');
-    }
-   
-    if ( $Only_preprocess_C ) {
-       $to_do = "$Cat $hscpp_hsc";
-       &run_something($to_do, '');
-    }
-
-}
-\end{code}
-
-
-\begin{code}
-sub runHscAndProcessInterfaces {
-    local($ifile, $hscpp_hsc, $ifile_root, 
-          $ofile_target, $hifile_target,
-         $going_interactive) = @_;
-
-       # $ifile                is the original input file
-       # $hscpp_hsc            post-unlit, post-cpp, etc., input file
-       # $ifile_root           input filename minus suffix
-       # $ofile_target         the output file that we ultimately hope to produce
-       # $hifile_target        the .hi file ... (ditto)
-       
-    local($source_unchanged) = 1;
-
-    # Check if the source file is up to date relative to the target; in
-    # that case we say "source is unchanged" and let the compiler bail out
-    # early if the import usage information allows it.
-
-    ($i_dev,$i_ino,$i_mode,$i_nlink,$i_uid,$i_gid,$i_rdev,$i_size,
-     $i_atime,$i_mtime,$i_ctime,$i_blksize,$i_blocks) = stat($ifile);
-
-    # The informational messages below are now conditional on -v being set -- SOF
-    if ( $ofile_target ne "_stdin.s" && ! -f $ofile_target ) {
-        print STDERR "$Pgm:compile:Output file $ofile_target doesn't exist\n" if $Verbose;
-       $source_unchanged = 0;
-    }
-
-    ($o_dev,$o_ino,$o_mode,$o_nlink,$o_uid,$o_gid,$o_rdev,$o_size,
-     $o_atime,$o_mtime,$o_ctime,$o_blksize,$o_blocks) = stat(_); # stat info from -f test
-
-    if ( $hifile_target ne "_stdout" && ! -f $hifile_target ) {
-        print STDERR "$Pgm:compile:Interface file $hifile_target doesn't exist\n" if $Verbose;
-       $source_unchanged = 0;
-    }
-
-    ($hi_dev,$hi_ino,$hi_mode,$hi_nlink,$hi_uid,$hi_gid,$hi_rdev,$hi_size,
-     $hi_atime,$hi_mtime,$hi_ctime,$hi_blksize,$hi_blocks) = stat(_); # stat info from -f test
-
-    if ( $ofile_target ne "_stdin.s" && $i_mtime > $o_mtime) {
-       print STDERR "$Pgm:recompile:Input file $ifile newer than $ofile_target\n" if $Verbose;
-       $source_unchanged = 0;
-    }
-
-    # Tell the compiler which version we're using
-    push(@HsC_flags, "-fhi-version=${ProjectVersionInt}");
-
-    # So if source_unchanged is still "1", we pass on the good news to the compiler
-    # The -recomp flag can disable this, forcing recompilation
-    if ($Do_recomp_chkr && $source_unchanged) {
-       push(@HsC_flags, '-fsource-unchanged'); 
-    }  
-
-    # Indicate whether we're static or not.
-    # This will only ever 
-    push(@HsC_flags, '-static') if $Static;
-
-    # Run the compiler
-
-    &runHsc($ifile_root, $hsc_out, $hsc_hi, $hsc_out_c_stub, $hsc_out_h_stub, $going_interactive);
-
-   # See if it bailed out early, saying nothing needed doing.  
-   # We work this out by seeing if it created an output .hi file
-
-    if ( ! -f $hsc_out ) {
-       # Doesn't exist, so we bailed out early.
-       # Tell the C compiler and assembler not to run
-       $do_cc = 0; $do_as = 0;
-
-       # Update dependency info, by touching the object file
-       # This records in the file system that the work of
-       # recompiling this module has been done
-       #
-       &run_something("touch $ofile_target",
-                      "Touch $ofile_target,  to propagate dependencies") if $HscLang ne 'none';
-
-    } else {   
-
-     # Didn't bail out early (new .hi file) so we thunder on
-    
-       # If non-interactive, heave in the consistency info at the end
-       # NB: pretty hackish (depends on how $output is set)
-       if ( ! $going_interactive ) {
-           if ( $HscLang eq 'C' ) {
-                $to_do = "echo 'static char ghc_hsc_ID[] = \"\@(#)hsc $ifile\t$HsC_major_version.$HsC_minor_version,$HsC_consist_options\";' >> $hsc_out";
-    
-               &run_something($to_do, 'Pin on Haskell consistency info');      
-           } elsif ( $HscLang eq 'asm' ) {
-               local($consist) = "hsc.$ifile.$HsC_major_version.$HsC_minor_version.$HsC_consist_options";
-               $consist =~ s/,/./g;
-               $consist =~ s/\//./g;
-               $consist =~ s/-/_/g;
-               $consist =~ s/[^A-Za-z0-9_.]/ZZ/g; # ToDo: properly?
-               $to_do = "echo '\n\t.text\n$consist:' >> $hsc_out";
-               &run_something($to_do, 'Pin on Haskell consistency info');      
-           }
-           # no consistency info for Java output files
-       }   
-
-
-       # Interface-handling is important enough to live off by itself
-       if ( -f $hsc_hi ) {
-               # print STDERR "Aha! A new hi file\n" ;
-               &run_something( "mv $hsc_hi $hifile_target", "Copy hi file" ) ;
-       } else {
-               # print STDERR "Oh ho! Hi file unchanged\n" ;
-       }
-
-
-       # save a copy of the .hc file, even if we are carrying on...
-       if ($HscLang eq 'C' && $do_cc && $Keep_hc_file_too) {
-            &saveIntermediate($ifile_root , "hc" , $hsc_out);
-       }
-
-    }
-}
-\end{code}
-
-
-\begin{code}
-sub runHsc {
-    local($ifile_root, $hsc_out, $hsc_hi, $hsc_out_c_stub, $hsc_out_h_stub, $going_interactive) = @_;
-
-    &makeHiMap() unless $HiMapDone;
-    push(@HsC_flags, "\"-himap=$HiIncludeString\"");
-    push(@HsC_flags, "\"-himap-sep=${SplitMarker}\"");
-
-    # here, we may produce .hc/.s and/or .hi files
-    local($output) = '';
-    #@Files_to_tidy = ();
-
-    if ( $going_interactive ) {
-       # don't need .hi unless we're going to show it on stdout:
-       $ProduceHi = '-nohifile=' if ! ($HiOnStdout || $Specific_hi_file ne '' );
-       $do_cc = 0; $do_as = 0; $Do_lnkr = 0; # and we won't go any further...
-    }
-
-    # set up for producing output/.hi; note that flag twiddling
-    # may mean that nothing will actually be produced:
-    $oflags = ( $HscLang eq 'none' ? "" : "-olang=$HscLang -ofile=$hsc_out" ) ;
-    $output = "$ProduceHi$hsc_hi $oflags -F=$hsc_out_c_stub -FH=$hsc_out_h_stub";
-    push(@Files_to_tidy, $hsc_hi, $hsc_out, $hsc_out_c_stub, $hsc_out_h_stub );
-
-    # if we're compiling foo.hs, we want the GC stats to end up in foo.stat
-    if ( $CollectingGCstats ) {
-       push(@HsC_rts_flags, "-S$ifile_root.stat");
-       push(@Files_to_tidy, "$ifile_root.stat");
-    }
-
-    if ( $CollectGhcTimings ) { # assume $RTS_style eq 'ghc'
-       # emit nofibbish time/bytes-alloc stats to stderr;
-       # see later .stat file post-processing
-       print STDERR "warning: both -Rgc-stats and -Rghc-timing used, -Rghc-timing wins." if $CollectingGCstats;
-       push(@HsC_rts_flags, "-S$Tmp_prefix.stat");
-       push(@Files_to_tidy, "$Tmp_prefix.stat");
-    }
-
-    local($dump) = '';
-    if ($Specific_dump_file ne '') {
-       $dump = "2>> $Specific_dump_file";
-       $Using_dump_file = 1;
-    }
-
-    local($to_do);
-    # Win32 only: If the command processor used by system()
-    # exec()s the application as an ordinary Win32 executable,
-    # we're in trouble here, since the command line is likely
-    # to be > 255 chars long. To work around this situation,
-    # $HsC also understands `at-files',  i.e., `@file' on the
-    # command line will cause $HsC to add the contents of `file'
-    # to the command line.
-    #
-    #  [ Note: support for `at-files' is not compiled in by default ]
-    $cmd_line_opts_via_at_file=0;
-    if ($cmd_line_opts_via_at_file) {
-
-      local($to_do_opts) = "$Tmp_prefix.opts";
-      open(OPTS, "> $Tmp_prefix.opts") || &tidy_up_and_die(1,"Can't open $Tmp_prefix.opts\n");
-      print OPTS "$dump @HsC_flags $CoreLint $USPLint $StgLint $Verbose";
-      close(OPTS);
-      $to_do = "$HsC $hscpp_hsc \@$Tmp_prefix.opts $output +RTS @HsC_rts_flags";
-
-    } else {
-
-    $to_do = "$HsC $hscpp_hsc $dump @HsC_flags $CoreLint $USPLint $StgLint $Verbose $output +RTS @HsC_rts_flags";
-    }
-    &run_something($to_do, 'Haskell compiler');
-
-    # finish business w/ nofibbish time/bytes-alloc stats
-    &process_ghc_timings() if $CollectGhcTimings;
-}
-\end{code}
-
-Use \tr{@Import_dir} and \tr{@SysImport_dir} to make a tmp file
-of (module-name, pathname) pairs, one per line, separated by a space.
-\begin{code}
-$HiMapDone = 0;
-$HiIncludeString = ();         # dir1:dir2:dir3, to pass to GHC
-
-sub makeHiMap {
-
-    # collect in %HiMap; write later; also used elsewhere in driver
-
-    local($mod, $path, $d, $e);
-
-    # reset the global variables:
-    $HiMapDone = 0;
-    $HiIncludeString = ();             # dir1:dir2:dir3, to pass to GHC
-    
-    foreach $d ( @Import_dir ) {
-       if ($HiIncludeString) { 
-          $HiIncludeString = "$HiIncludeString${SplitMarker}${d}%.${HiSuffix}";
-       } else { 
-          $HiIncludeString = "$d%.${HiSuffix}"; 
-       }
-
-    }
-
-    foreach $d ( @SysImport_dir ) {
-       if ($HiIncludeString) { 
-           $HiIncludeString = "$HiIncludeString${SplitMarker}${d}%.${HiSuffix_prelude}";
-       } else { 
-           $HiIncludeString = "${d}%.${HiSuffix_prelude}";
-        }
-    }
-
-    $HiMapDone = 1;
-}
-
-\end{code}
-
-Invoke the 'linker' - either the standard linker or the one used to build
-a (Win32) DLL.
-
-\begin{code}
-sub runLinker
-{
-    local($libdirs) = '';
-
-    # append last minute flags linker and consistency flags
-    &setupBuildFlags();
-    &setupSyslibs();
-    &setupLinkOpts();
-
-    # glue them together:
-    push(@UserLibrary_dir, @SysLibrary_dir);
-
-    $libdirs = '-L' . join(' -L',@UserLibrary_dir) if $#UserLibrary_dir >= 0;
-
-    # for a linker, use an explicitly given one, or the going C compiler ...
-    local($lnkr) = ( $Lnkr ) ? $Lnkr : $CcRegd;
-
-    if ( ($Specific_output_file eq '') && 
-         ( ($TargetPlatform eq 'i386-unknown-cygwin32') ||
-          ($TargetPlatform eq 'i386-unknown-mingw32')) ) {
-         $Specific_output_file = 'main.exe';
-         print STDERR "Output file not specified, defaulting to \"main.exe\"\n";
-    }
-
-    local($output) = ($Specific_output_file ne '') ? "-o $Specific_output_file" : '';
-    @Files_to_tidy = ($Specific_output_file ne '') ? $Specific_output_file : 'a.out'; 
-
-    &prepareWin32DllLink(1);
-
-    local($to_do) = "$lnkr $Verbose @Ld_flags $output @Link_file $libdirs @UserLibrary @SysLibrary";
-    &run_something($to_do, 'Linker');
-
-    # finally, check the consistency info in the binary
-    local($executable) = $Files_to_tidy[0];
-    @Files_to_tidy = (); # reset; we don't want to nuke it if it's inconsistent
-
-    if ( $LinkChk ) {
-       # dynamically load consistency-chking code; then do it.
-       require('ghc-consist.prl')
-           || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-consist.prl!\n");
-
-       &chk_consistency_info ( $executable );
-    }
-
-    # if PVM parallel stuff, we do truly weird things.
-    # Essentially: (1) move the executable over to where PVM expects
-    # to find it.  (2) create a script in place of the executable
-    # which will cause the program to be run, via SysMan.
-    if ( $PARing eq 'p' ) {
-       local($pvm_executable) = $executable;
-       local($pvm_executable_base);
-
-       if ( $pvm_executable !~ /^\// ) { # a relative path name: make absolute
-           local($pwd) = `pwd`;
-           chop($pwd);
-           $pwd =~ s/^\/tmp_mnt//;
-           $pvm_executable = "$pwd/$pvm_executable";
-       }
-
-       $pvm_executable =~ s|/|=|g; # make /s into =s
-       $pvm_executable_base = $pvm_executable;
-
-       $pvm_executable = $ENV{'PVM_ROOT'} . '/bin/' . $ENV{'PVM_ARCH'}
-                       . "/$pvm_executable";
-
-       &run_something("$Rm -f $pvm_executable; $Cp -p $executable $pvm_executable && $Rm -f $executable", 'Moving binary to PVM land');
-
-       # OK, now create the magic script for "$executable"
-       open(EXEC, "> $executable") || &tidy_up_and_die(1,"$Pgm: couldn't open $executable to write!\n");
-       print EXEC <<EOSCRIPT1;
-eval 'exec perl -S \$0 \${1+"\$@"}'
-  if \$running_under_some_shell;
-# =!=!=!=!=!=!=!=!=!=!=!
-# This script is automatically generated: DO NOT EDIT!!!
-# Generated by Glasgow Haskell, version ${ProjectVersion}
-# ngoqvam choHbogh vaj' vIHoHnISbej !!!!
-#
-\$pvm_executable      = '$pvm_executable';
-\$pvm_executable_base = '$pvm_executable_base';
-\$SysMan = '$SysMan';
-EOSCRIPT1
-
-       print EXEC <<\EOSCRIPT2;
-# first, some magical shortcuts to run "commands" on the binary
-# (which is hidden)
-if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {
-    local($cmd) = $1;
-    system("$cmd $pvm_executable");
-    exit(0); # all done
-}
-
-# OK, really run it; process the args first
-$ENV{'PE'} = $pvm_executable_base;
-$debug = '';
-$nprocessors = 2; # the default
-@nonPVM_args = ();
-$in_RTS_args = 0;
-
-# ToDo: handle --RTS
-args: while ($a = shift(@ARGV)) {
-    if ( $a eq '+RTS' ) {
-       $in_RTS_args = 1;
-    } elsif ( $a eq '-RTS' ) {
-       $in_RTS_args = 0;
-    }
-    if ( $a eq '-d' && $in_RTS_args ) {
-       $debug = '-';
-    } elsif ( $a =~ /^-qN(\d+)/ && $in_RTS_args ) {
-       $nprocessors = $1;
-    } elsif ( $a =~ /^-qp(\d+)/ && $in_RTS_args ) {
-       $nprocessors = $1;
-    } else {
-       push(@nonPVM_args, $a);
-    }
-}
-
-local($return_val) = 0;
-system("$SysMan $debug $pvm_executable $nprocessors @nonPVM_args");
-$return_val = $?;
-system("mv $ENV{'HOME'}/$pvm_executable_base.???.gr .") if -f "$ENV{'HOME'}/$pvm_executable_base.001.gr";
-exit($return_val);
-EOSCRIPT2
-       close(EXEC) || die "Failed closing $executable\n";
-       chmod 0755, $executable;
-    }
-}
-
-sub createWin32DLL
-{
-    local ($libdirs);
-
-    # append last minute flags linker and consistency flags
-    &setupBuildFlags();
-    &setupSyslibs();
-    &setupLinkOpts();
-
-    # glue them together:
-    push(@UserLibrary_dir, @SysLibrary_dir);
-
-    $libdirs = '-L' . join(' -L',@UserLibrary_dir) if $#UserLibrary_dir >= 0;
-
-    &prepareWin32DllLink(0);
-
-    local ($bld_dll) = "dllwrap";
-
-    local ($output) = ($Specific_output_file ne '') ? "$Specific_output_file" : 'HSdll.dll';
-    local ($output_dir);
-    local ($output_file);
-    local ($output_lib, $output_def);
-
-    ($output_dir = $output) =~ s|(.*/)[^/]+$|$1|;
-    $output_dir = "" if ($output_dir eq $output);
-    ($output_file = $output) =~ s|.*/([^/]+)$|$1|;
-
-    ($output_lib = $output_file) =~ s|(.+)\.[^\.]*$|${output_dir}lib$1_imp.a|;
-    ($output_def = $output_file) =~ s|(.+)\.[^\.]*$|${output_dir}$1.def|;
-
-    push (@Dll_flags, "-mno-cygwin --target=i386-mingw32") if ($TargetPlatform =~ /^.*mingw32$/);
-    push (@Dll_flags, "--output-lib $output_lib");
-    # If the "--def " option hasn't been supplied, assume everything 
-    # is going to be exported via the DLL.."
-    if (!grep(/--def/, @Dll_flags)) {
-      push (@Dll_flags, "--export-all --output-def $output_def");
-    }
-
-    local($to_do) = "$bld_dll @Dll_flags -o $output @Link_file $libdirs @UserLibrary @SysLibrary";
-    # Make sure the user sees this piece of magic.
-    print STDERR "$to_do\n" if (!$Verbose);
-    &run_something($to_do, 'DLL creator');
-}
-
-sub prepareWin32DllLink
-{
-    local($linking_main) = @_;
-
-    #
-    # Win32 DLLs - link with import libraries, not the real archives.
-    # 
-    if ( $TargetPlatform =~ /-mingw32$/ ) {
-       if (!$Static) {
-        #
-        # If the libraries have the form libHSfoo.a, we
-        # transform that into libHSfoo_imp.a - the import
-        # library of the DLL.
-        # 
-         foreach $a ( @SysLibrary ) {
-           $a = "${a}_imp" if ($a =~ /^-lHS/);
-         }
-         foreach $a ( @UserLibrary ) {
-           $a = "${a}_imp" if ($a =~ /^-lHS/);
-         }
-         push(@Link_file, ( $INSTALLING ) ? "$InstLibDirGhc/Main.dll_o"
-                                         : "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/Main.dll_o") if $linking_main;
-         push(@Link_file, ( $INSTALLING ) ? "$InstLibDirGhc/PrelMain.dll_o"
-                                         : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std/PrelMain.dll_o") if $linking_main;
-       }
-       push(@Ld_flags,  "-mno-cygwin");
-    }
-}
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\section[Driver-misc-utils]{Miscellaneous utilities}
-%*                                                                     *
-%************************************************************************
-
-%************************************************************************
-%*                                                                     *
-\subsection[Driver-odir-ify]{@odir_ify@: Mangle filename if \tr{-odir} set}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub osuf_ify {
-    local($ofile,$def_suffix) = @_;
-
-    return(($Osuffix eq '') ? "$ofile.$def_suffix" : "$ofile.$Osuffix" );
-}
-
-sub odir_ify {
-    local($orig_file, $def_suffix) = @_;
-    if ($Specific_output_dir eq '') {   # do nothing
-       &osuf_ify($orig_file, $def_suffix);
-    } else {
-       local ($orig_file_only);
-       ($orig_file_only = $orig_file) =~ s|.*/||;
-       &osuf_ify("$Specific_output_dir/$orig_file_only",$def_suffix);
-    }
-}
-\end{code}
-
-\begin{code}
-sub runGcc {
-    local($is_hc_file, $hsc_out, $cc_as_o) = @_;
-
-    local($includes) = '-I' . join(' -I', @Include_dir);
-    local($cc);
-    local($s_output);
-    local($c_flags) = "@CcBoth_flags";
-    local($ddebug_flag) = ( $DEBUGging ) ? '-DDEBUG' : '';
-
-    $c_flags .= " -mno-cygwin" if ( $TargetPlatform =~ /-mingw32$/ );
-
-    # "input" files to use that are not in some weird directory;
-    # to help C compilers grok .hc files [ToDo: de-hackify]
-    local($cc_help)   = "ghc$$.c";
-    local($cc_help_s) = "ghc$$.s";
-
-    $cc       = $CcRegd;
-    $s_output = (($is_hc_file && $DoAsmMangling) || $TargetPlatform =~ /^(powerpc|rs6000|hppa)/) ? $cc_as_o : $cc_as;
-    $c_flags .= " @CcRegd_flags";
-    $c_flags .= ($is_hc_file) ? " @CcRegd_flags_hc"  : " @CcRegd_flags_c";
-
-    # C compiler won't like the .hc extension.  So we create
-    # a tmp .c file which #include's the needful.
-    open(TMP, "> $cc_help") || &tidy_up_and_die(1,"$Pgm: failed to open `$cc_help' (to write)\n");
-    if ( $is_hc_file ) {
-       print TMP @CcInjects;
-    } else {
-       # Straight .c files may want to know that they're being used
-       # with a particular version of GHC, so we define __GLASGOW_HASKELL__ for their benefit.
-        print TMP "#define __GLASGOW_HASKELL__ ${ProjectVersionInt}\n";
-    }
-    # heave in the consistency info
-    print TMP "static char ghc_cc_ID[] = \"\@(#)cc $ifile\t$Cc_major_version.$Cc_minor_version,$Cc_consist_options\";\n";
-
-    print TMP "#include \"$hsc_out\"\n";
-    close(TMP) || &tidy_up_and_die(1,"Failed writing to $cc_help\n");
-
-    # Don't redirect stderr into intermediate file if slamming output onto stdout (e.g., with -E)
-    local($fuse_stderr) = "2>&1" if ! $Only_preprocess_hc;
-    local($to_do) = "$cc $Verbose $ddebug_flag $c_flags @Cpp_define $includes $cc_help > $Tmp_prefix.ccout $fuse_stderr && ( if [ $cc_help_s != $s_output ] ; then mv $cc_help_s $s_output ; else exit 0 ; fi )";
-
-    if ( $Only_preprocess_hc ) { # HACK ALERT!
-       $to_do =~ s/ -S\b//g;
-    }
-    push(@Files_to_tidy, $cc_help, $cc_help_s, $s_output );
-    $PostprocessCcOutput = 1 if ! $Only_preprocess_hc; # hack, dear hack...
-    &run_something($to_do, 'C compiler');
-    $PostprocessCcOutput = 0;
-    if ( $Only_preprocess_hc ) {
-       system("$Cat $Tmp_prefix.ccout");
-    }
-    unlink($cc_help, $cc_help_s);
-}
-\end{code}
-
-\begin{code}
-sub runMangler {
-    local($is_hc_file, $cc_as_o, $cc_as, $ifile_root) = @_;
-
-    print STDERR `cat $cc_as_o` if $Dump_raw_asm; # to stderr, before mangling
-
-    if ($is_hc_file && $DoAsmMangling) {
-       # dynamically load assembler-fiddling code, which we are about to use:
-       require('ghc-asm.prl')
-            || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm.prl!\n");
-       # post-process the assembler [.hc files only]
-       &mangle_asm($cc_as_o, $cc_as);
-
-    } elsif ($TargetPlatform =~ /^hppa/) {
-       # minor mangling of non-threaded files for hp-pa only
-       require('ghc-asm.prl')
-       || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm-hppa.prl!\n");
-       &mini_mangle_asm_hppa($cc_as_o, $cc_as);
-
-    } elsif ($TargetPlatform =~ /^powerpc|^rs6000/) {
-       # minor mangling of non-threaded files for powerpcs and rs6000s 
-       require('ghc-asm.prl')
-       || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm-powerpc.prl!\n");
-       &mini_mangle_asm_powerpc($cc_as_o, $cc_as);
-    }
-
-    # save a copy of the .s file, even if we are carrying on...
-    #if ($do_as && $Keep_s_file_too) {
-    #    &saveIntermediate($ifile_root , "s" , $cc_as);
-    #}
-}
-\end{code}
-
-\begin{code}
-sub runAs {
-    local($as_out, $ifile_root) = @_;
-
-    local($asmblr) = ( $As ) ? $As : $CcRegd;
-
-    # need to add the -I flags in case the file is going through cpp (.S files)
-    local($includes) = '-I' . join(' -I', @Include_dir);
-
-   if ( ! $SplitObjFiles || $ifile_root =~ /_stub\.s$/ ) {
-       local($to_do)  = "$asmblr -o $as_out -c @As_flags $includes $cc_as";
-       push(@Files_to_tidy, $as_out );
-       &run_something($to_do, 'Unix assembler');
-
-    } else { # more complicated split-ification...
-
-       # must assemble files $Tmp_prefix__[1 .. $NoOfSplitFiles].s
-
-        # If -odir is used, great, just pin it in front of the
-       # generated split file names. If it hasn't been set, we
-       # snatch it from the ifile_root.
-       #
-       # 
-
-        if ( $Specific_output_dir eq '' ) {
-            $Specific_output_dir = ${ifile_root};
-        }
-
-       for ($f = 1; $f <= $NoOfSplitFiles; $f++ ) {
-           local($split_out) = &odir_ify("${ifile_root}__${f}",'o');
-           local($to_do) = "$asmblr -o $split_out -c @As_flags ${Tmp_prefix}__${f}.s";
-           push(@Files_to_tidy, $split_out );
-
-           &run_something($to_do, 'Unix assembler');
-       }
-    }
-}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection[Driver-run-something]{@run_something@: Run a phase}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub run_something {
-    local($str_to_do, $tidy_name) = @_;
-
-    print STDERR "\n$tidy_name:\n\t" if $Verbose;
-    print STDERR "$str_to_do\n" if $Verbose;
-
-    if ($Using_dump_file) {
-        open(DUMP, ">> $Specific_dump_file")
-           || &tidy_up_and_die(1,"$Pgm: failed to open `$Specific_dump_file'\n");
-       print DUMP "\nCompilation Dump for: $str_to_do\n\n";
-       close(DUMP) 
-           || &tidy_up_and_die(1,"$Pgm: failed closing `$Specific_dump_file'\n");
-    }
-
-    local($return_val) = 0;
-
-    if ( length($str_to_do) > 4000) { 
-      # 4000 - on the random side, just like the *real* ARG_MAX 
-      # for some shells.
-
-      # With some shells, command lines of this length may
-      # very well cause trouble. To safeguard against this, we squirrel the
-      # command into a file and exec that.
-      local ($sh) = $ENV{'REAL_SHELL'};
-      print STDERR "Backup plan A: saving cmd line in ${Tmp_prefix}.sh and executing that with $sh\n" if $Verbose;
-      open (TEMP, "> ${Tmp_prefix}.sh") || 
-               &tidy_up_and_die(1,"$Pgm: failed to open `$Tmp_prefix.sh'\n");
-      print TEMP "$Time $str_to_do\n";
-      close (TEMP) ||
-               &tidy_up_and_die(1,"$Pgm: failed closing `$Tmp_prefix.sh'\n");
-      system("$sh $Tmp_prefix.sh");
-      $return_val = $?;
-      
-      unlink "${Tmp_prefix}.sh";
-    } else {
-      system("$Time $str_to_do");
-      $return_val = $?;
-    }
-
-    if ( $PostprocessCcOutput ) { # hack, continued
-       open(CCOUT, "< $Tmp_prefix.ccout")
-           || &tidy_up_and_die(1,"$Pgm: failed to open `$Tmp_prefix.ccout'\n");
-       while ( <CCOUT> ) {
-           next if /call-clobbered/;
-           next if /control reaches end/;
-           next if /from .*Stg\.h:/;
-           next if /from ghc\d+.c:\d+:/;
-           next if /: At top level:$/;
-           next if /: In function \`.*\':$/;
-           next if /\`ghc_cc_ID\' defined but not used/;
-           print STDERR $_;
-       }
-       close(CCOUT) || &tidy_up_and_die(1,"$Pgm: failed closing `$Tmp_prefix.ccout'\n");
-    }
-
-    local($signal_num)  = $? & 127;
-    local($dumped_core) = $? & 128;
-
-    if ($signal_num != 0) {
-       print STDERR "$tidy_name received signal $signal_num";
-       if ($dumped_core != 0) {
-               print STDERR " (core dumped)";
-       }
-       print STDERR "\n";
-    }
-
-    if ($return_val != 0) {
-        if ($Using_dump_file) {
-           print STDERR "Compilation Errors dumped in $Specific_dump_file\n";
-       }
-       &tidy_up_and_die($return_val, '');
-    }
-
-    $Using_dump_file = 0;
-}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection[Driver-ghc-timing]{Emit nofibbish GHC timings}
-%*                                                                     *
-%************************************************************************
-
-NB: nearly the same as in @runstdtest@ script.
-
-\begin{code}
-sub process_ghc_timings {
-    local($StatsFile) = "$Tmp_prefix.stat";
-    local($SysSpecificTiming) = 'ghc';
-
-    open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
-    local($max_live)    = 0; 
-    local($tot_live)    = 0; # for calculating residency stuff
-    local($tot_samples) = 0;
-
-    while (<STATS>) {
-       if (! /Gen:\s+0/ && ! /Minor/ && /^\s*\d+\s+\d+\s+(\d+)\s+\d+\.\d+/ ) {
-               $max_live = $1 if $max_live < $1;
-               $tot_live += $1;
-               $tot_samples += 1;
-       }
-        $BytesAlloc = $1 if /^\s*([0-9,]+) bytes allocated in the heap/;
-
-       if ( /^\s*([0-9,]+) bytes maximum residency .* (\d+) sample/ ) {
-           $MaxResidency = $1; $ResidencySamples = $2;
-       }
-
-        $GCs = $1 if /^\s*([0-9,]+) (collections? in generation 0|garbage collections? performed)/;
-
-       if ( /^\s+([0-9]+)\s+Mb total memory/ ) {
-           $TotMem = $1;
-        }
-
-       # The presence of -? in the following pattern is only there to
-       # accommodate 0.29 && <= 2.05 RTS'
-       if ( /^\s*INIT\s+time\s*(\d+\.\d\d)s\s*\(\s*-?(\d+\.\d\d)s elapsed\)/ ) {
-           $InitTime = $1; $InitElapsed = $2;
-       } elsif ( /^\s*MUT\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
-           $MutTime = $1; $MutElapsed = $2;
-       } elsif ( /^\s*GC\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
-           $GcTime = $1; $GcElapsed = $2;
-       }
-    }
-    close(STATS) || die "Failed when closing $StatsFile\n";
-    if ( $tot_samples > 0 ) {
-       $ResidencySamples = $tot_samples;
-       $MaxResidency = $max_live;
-       $AvgResidency = int ($tot_live / $tot_samples) ;
-    }
-
-    # warn about what we didn't find
-    print STDERR "Warning: BytesAlloc not found in stats file\n" unless defined($BytesAlloc);
-    print STDERR "Warning: GCs not found in stats file\n" unless defined($GCs);
-    print STDERR "Warning: InitTime not found in stats file\n" unless defined($InitTime);
-    print STDERR "Warning: InitElapsed not found in stats file\n" unless defined($InitElapsed);
-    print STDERR "Warning: MutTime not found in stats file\n" unless defined($MutTime);
-    print STDERR "Warning: MutElapsed not found in stats file\n" unless defined($MutElapsed);
-    print STDERR "Warning: GcTime inot found in stats file\n" unless defined($GcTime);
-    print STDERR "Warning: GcElapsed not found in stats file\n" unless defined($GcElapsed);
-
-    # things we didn't necessarily expect to find
-    $MaxResidency     = 0 unless defined($MaxResidency);
-    $AvgResidency     = 0 unless defined($AvgResidency);
-    $ResidencySamples = 0 unless defined($ResidencySamples);
-
-    # a bit of tidying
-    $BytesAlloc =~ s/,//g;
-    $MaxResidency =~ s/,//g;
-    $GCs =~ s/,//g;
-    $InitTime =~ s/,//g;
-    $InitElapsed =~ s/,//g;
-    $MutTime =~ s/,//g;
-    $MutElapsed =~ s/,//g;
-    $GcTime =~ s/,//g;
-    $GcElapsed =~ s/,//g;
-
-    # print out what we found
-    print STDERR "<<$SysSpecificTiming: ",
-       "$BytesAlloc bytes, $GCs GCs, $AvgResidency/$MaxResidency avg/max bytes residency ($ResidencySamples samples), ${TotMem}M in use, $InitTime INIT ($InitElapsed elapsed), $MutTime MUT ($MutElapsed elapsed), $GcTime GC ($GcElapsed elapsed)",
-       " :$SysSpecificTiming>>\n";
-
-    # OK, party over
-    unlink $StatsFile;
-}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection[Driver-dying]{@tidy_up@ and @tidy_up_and_die@: Dying gracefully}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-sub tidy_up {
-    local($to_do) = "\n$Rm $Tmp_prefix*";
-    if ( $Tmp_prefix !~ /^\s*$/ ) {
-       print STDERR "$to_do\n" if $Verbose;
-       system($to_do);
-    }
-}
-
-sub tidy_up_and_die {
-    local($return_val, $msg) = @_;
-
-    # delete any files to tidy
-    print STDERR "deleting... @Files_to_tidy\n" if $Verbose && $#Files_to_tidy >= 0;
-    unlink @Files_to_tidy if $#Files_to_tidy >= 0;
-
-    &tidy_up();
-    print STDERR $msg;
-    exit (($return_val == 0) ? 0 : 1);
-}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection[Driver-arg-with-arg]{@grab_arg_arg@: Do an argument with an argument}
-%*                                                                     *
-%************************************************************************
-
-Some command-line arguments take an argument, e.g.,
-\tr{-Rmax-heapsize} expects a number to follow.  This can either be
-given a part of the same argument (\tr{-Rmax-heapsize8M}) or as the
-next argument (\tr{-Rmax-heapsize 8M}).  We allow both cases.
-
-Note: no error-checking; \tr{-Rmax-heapsize -Rgc-stats} will silently
-gobble the second argument (and probably set the heapsize to something
-nonsensical).
-\begin{code}
-sub grab_arg_arg {
-    local(*Args, $option, $rest_of_arg) = @_;
-    
-    if ($rest_of_arg ne '') {
-       return($rest_of_arg);
-    } elsif ($#Args >= 0) {
-       local($temp) = $Args[0]; shift(@Args); 
-       return($temp);
-    } else {
-       print STDERR "$Pgm: no argument following $option option\n";
-       $Status++;
-    }
-}
-\end{code}
-
-\begin{code}
-sub isntAntiFlag {
-    local($flag) = @_;
-    local($f);
-
-#Not in HsC_antiflag ## NO!: and not already in HsC_flags
-
-    foreach $f ( @HsC_antiflags ) {
-       return(0) if $flag eq $f;
-    }
-#    foreach $f ( @HsC_flags ) {
-#      return(0) if $flag eq $f;
-#    }
-    return(1);
-}
-
-sub squashHscFlag {  # pretty terrible
-    local($flag) = @_;
-    local($f);
-
-    foreach $f ( @HsC_flags ) {
-       if ($flag eq $f) { $f = ''; }
-    }
-}
-
-sub add_Hsc_flags {
-    local(@flags) = @_;
-    local($f);
-
-    foreach $f ( @flags ) {
-       push( @HsC_flags, $f ) if &isntAntiFlag($f);
-    }
-}
-\end{code}
-
-To add another system library, you'll need to augment the
-Supported_syslibs variable with name and info on your addition
-to the syslib family. The info bit consist of the following:
-
-   - interface file directory
-       see the misc or posix entry for how to distinguish
-       between using installed and build tree directories.
-       
-   - directory location of archives
-       
-   - location of (way-independent) C support libs.
-       not all libraries need this - if you don't, just
-       give the empty string.
-   - list of syslibs you depend on.
-
-   - additional ghc command line flags that should be used.
-   - additional C compiler command line flags that should be used.
-   - link 
-
-
-\begin{code}
-
-sub add_syslib {
-    local($syslib) = @_;
-
-    # Lifting this out of this sub brings it out of scope - why??
-    %Supported_syslibs =
-     ( lang,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/lang"
-              : "$TopPwd/hslibs/lang:$TopPwd/hslibs/lang/monads"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/lang"
-         )
-       , # where to find the cbits archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/lang/cbits"
-         )
-       , '' # Syslib dependencies
-       , '' # extra ghc opts
-       , '' # extra cc opts
-       , '' # extra ld opts
-       ],
-
-       concurrent,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/concurrent"
-              : "$TopPwd/hslibs/concurrent"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/concurrent"
-         )
-       , '' # where to find the cbits archive to use when linking
-       , 'lang' # Syslib dependencies
-       , '' # extra ghc opts
-       , '' # extra cc opts
-       , '' # extra ld opts
-       ],
-
-       data,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/data"
-              : "$TopPwd/hslibs/data:$TopPwd/hslibs/data/edison:$TopPwd/hslibs/data/edison/Assoc:$TopPwd/hslibs/data/edison/Coll:$TopPwd/hslibs/data/edison/Seq"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/data"
-         )
-       , '' # where to find the cbits archive to use when linking
-       , 'lang' # Syslib dependencies
-       , '' # extra ghc opts
-       , '' # extra cc opts
-       , '' # extra ld opts
-       ],
-
-       net,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/net"
-              : "$TopPwd/hslibs/net"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/net"
-         )
-       , # where to find the cbits archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/net/cbits"
-         )
-       , 'lang text' # Syslib dependencies
-       , '' # extra ghc opts
-       , '' # extra cc opts
-       , ( $TargetPlatform =~ /-solaris2$/  ? '-lnsl -lsocket' : '')
-       ],
-
-       posix,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/posix"
-              : "$TopPwd/hslibs/posix"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/posix"
-         )
-       , # where to find the cbits archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/posix/cbits"
-         )
-       , 'lang' # Syslib dependencies
-       , ''     # extra ghc opts
-       , ''     # extra cc opts
-       , ''     # extra ld opts
-       ],
-
-       text,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/text"
-              : "$TopPwd/hslibs/text:$TopPwd/hslibs/text/html:$TopPwd/hslibs/text/haxml/lib:$TopPwd/hslibs/text/parsec"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/text"
-         )
-       , # where to find the cbits archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/text/cbits"
-         )
-       , 'lang data' # Syslib dependencies
-       , '' # extra ghc opts
-       , '' # extra cc opts
-       , '' # extra ld opts
-       ],
-
-       util,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/util"
-              : "$TopPwd/hslibs/util:$TopPwd/hslibs/util/check"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/util"
-         )
-       , # where to find the cbits archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/util/cbits"
-         )
-       , 'lang concurrent' . (( $TargetPlatform =~ /^.*(cygwin32|mingw32)$/ ) ? '' : ' posix' ) # Syslib dependencies
-       , ''     # extra ghc opts
-       , ''     # extra cc opts
-       , "$LibsReadline"     # extra ld opts
-       ],
-
-       win32,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/win32"
-              : "$TopPwd/hslibs/win32/src"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hslibs/win32/src"
-         )
-       , ''
-       , 'lang greencard' # Syslib dependencies
-       , ''     # extra ghc opts
-       , ''     # extra cc opts
-       , '-luser32 -lgdi32'     # extra ld opts
-       ],
-
-       greencard,
-        [  # where to slurp interface files from
-          ( $INSTALLING
-               ? "$InstLibDirGhc/imports/greencard"
-               : "$TopPwd/green-card/lib/ghc"
-          )
-        , # where to find the archive to use when linking
-          ( $INSTALLING
-               ? "$InstLibDirGhc"
-               : "$TopPwd/green-card/lib/ghc"
-          )
-        , ''     # No cbits archive
-        , 'lang' # Syslib dependencies
-        , ''     # extra ghc opts
-        , ''     # extra cc opts
-        , ''     # extra ld opts
-        ],
-
-       com,
-       [  # where to slurp interface files from
-         ( $INSTALLING 
-              ? "$InstLibDirGhc/imports/com"
-              : "$TopPwd/hdirect/lib"
-         )
-       , # where to find the archive to use when linking
-         ( $INSTALLING 
-              ? "$InstLibDirGhc"
-              : "$TopPwd/hdirect/lib"
-         )
-       , ''
-       , 'lang' # Syslib dependencies
-       , ''     # extra ghc opts
-       , ''     # extra cc opts
-       , '-luser32 -lole32 -loleaut32 -ladvapi32'
-                # extra ld opts
-       ]
-    );
-
-    # check if it's supported..
-    
-    if ( !exists $Supported_syslibs{$syslib} ) {
-       print STDERR "$Pgm: no such system library (-syslib): $syslib\n";
-       $Status++;
-       return;
-    }
-
-    # Make sure that header file HsFoo.h is included for syslib foo.
-    if ( !exists $Syslibs_added{$syslib} ) {
-      push(@CcInjects, "#include \"Hs\u$syslib.h\"\n");
-      push(@Include_dir, "$TopPwd/hslibs/$syslib/cbits") unless ( $INSTALLING );
-    }
-
-    # This check is here to avoid syslib loops from
-    # spoiling the party. A side-effect of it is that
-    # it disallows multiple mentions of a syslib on a command-line,
-    # explicit *and* implicit ones (i.e., "-syslib lang -syslib misc"
-    # is not equal to "-syslib lang -syslib misc -syslib lang",
-    # which it needs to be)
-    # 
-    # Since our current collection of syslibs don't have any
-    # loops, this test is disabled.
-    #
-    # ToDo: loop avoidance scheme when the need arises
-    #
-    #return if ( exists $Syslibs_added{$syslib} );
-       
-    $Syslibs_added{$syslib} = 1;
-
-    local ($hi_dirs, $lib_dir, $lib_cbits_dir,
-          $syslib_deps, $syslib_ghc_opts,
-          $syslib_cc_opts, $syslib_ld_opts) = @{ $Supported_syslibs{$syslib} };
-
-    foreach(split(':',$hi_dirs)) {
-       unshift(@SysImport_dir, $_);
-    }
-    push(@SysLibrary_dir, $lib_dir);
-    push(@SysLibrary_dir, $lib_cbits_dir) if ( $lib_cbits_dir ne '');
-
-    push(@SysLibrary, "-lHS$syslib");
-    push(@SysLibrary, "-lHS${syslib}_cbits") if ( $lib_cbits_dir ne '');
-    push(@SysLibrary, $syslib_ld_opts) if ($syslib_ld_opts ne '');   
-
-    # Add on any extra dependencies.
-    foreach $lib (split(' ',$syslib_deps)) {
-      &add_syslib($lib);
-    }
-}
-\end{code}
-
-Source files may have {-# OPTIONS ... #-} pragmas at the top, containing
-command line options we want to append to collection of commands specified
-directly. @check_for_source_options@ looks at the top of a de-lit'ified Haskell
-file for any such pragmas:
-
-\begin{code}
-sub check_for_source_options {
-    local($file,$ifile) = @_;
-    local($comment_start,$comment_end);
-
-    if ($ifile =~ /\.hc$/ || 
-        $ifile =~ /_hc$/  || 
-       $ifile =~ /\.s$/  || 
-       $ifile =~ /_s$/ ) {  # `Real' C intermediate
-       $comment_start = "/\\*";
-       $comment_end   = "\\*/";
-    } else { # Assume it is a file containing Haskell source
-       $comment_start = "{-#";
-       $comment_end   = "#-}";
-    }
-
-    open(FILE,$file) || return(1); # No big loss
-    
-    while (<FILE>) {
-       if ( /^${comment_start} OPTIONS (.*)${comment_end}/ ) {
-           # add the options found at the back of the command line.
-          local(@entries) = split(/\s+/,$1);
-          print STDERR "Found OPTIONS " . join(' ',@entries) . " in $file\n" if $Verbose;
-          push(@File_options, @entries);
-       }
-        elsif ( /^$/ ) { # ignore empty lines
-           ;
-        }
-        elsif ( /^#line.+$/ ) { # ignore comment lines (unused..ToDo: rm )
-           ;
-        }
-        elsif ( /^{-# LINE.+$/ ) { # ignore line pragmas
-           ;
-        }
-        else { # stop looking, something non-empty / not
-              # ${comment_start} OPTIONS .. ${comment_end} encountered.
-           close(FILE);return(0);
-        }
-    }
-    close(FILE);
-    return(0);
-}
-\end{code}
-
-
-We split the initial argv up into three arrays:
-
-  - @Cmd_opts 
-  - @Link_file
-  - @Input_file
-
-the reason for doing so is to be able to deal
-with {-# OPTIONS #-} pragma in source files properly.
-
-\begin{code}
-sub splitCmdLine {
-    local(@args) = @_;
-
-arg: while($_ = $args[0]) {
-    shift(@args);
-    # sigh, we have to deal with these -option arg specially here.
-    /^-(tmpdir|odir|ohi|o|isuf|osuf|hisuf|odump|syslib|package|package-name)$/ && 
-       do { push(@Cmd_opts, $_); push(@Cmd_opts,$args[0]); shift(@args); next arg; };
-    /^--?./  && do { push(@Cmd_opts, $_); next arg; };
-
-    if (/\.([^_]+_)?[oa]$/) {
-       push(@Link_file, $_);
-    } else {
-       push(@Input_file, $_);
-    }
-
-    # input files must exist:
-    if (! -f $_) {
-       print STDERR "$Pgm: input file doesn't exist: $_\n";
-       $Status++;
-    }
-  }
-}    
-
-\end{code}
-
-When saving an intermediate file (.hc or .s) away, we 
-have to prefix any OPTIONS found in the original source file.
-
-\begin{code}
-sub saveIntermediate { 
-  local ($final,$suffix,$tmp)= @_ ;
-  local ($to_do);
-
-  local ($new_suffix);
-
-  # $final  -- root of where to park ${final}.${suffix}
-  # $tmp    -- temporary file where hsc put the intermediate file.
-
-  # HWL: use -odir for .hc and .s files, too
-  if ( $Specific_output_dir ne '' ) {
-    $final = "${Specific_output_dir}/${final}";
-  }    
-  # HWL: use the same suffix as for $Osuffix in generating intermediate file,
-  #      replacing o with hc or s, respectively. 
-  if ( $Osuffix ne '' ) {
-    ($new_suffix = $Osuffix) =~ s/o$/hc/ if $suffix eq "hc";
-    ($new_suffix = $Osuffix) =~ s/o$/s/ if $suffix eq "s";
-    $suffix = $new_suffix;
-    print stderr "HWL says: suffix for intermediate file is $suffix; ${final}.${suffix} overall\n" if $Verbose;
-  }
-
-  # Delete the old file
-  $to_do = "$Rm ${final}.${suffix}"; &run_something($to_do, "Removing old .${suffix} file");
-
-  if ( $#File_options >= 0 ) { # OPTIONS found in Haskell source unit
-    # Add OPTION comment to the top of the generated .${suffix} file
-    open(TEMP, "> ${final}.${suffix}") || &tidy_up_and_die(1,"Can't open ${final}.${suffix}\n");
-    print TEMP "/* OPTIONS " . join(' ',@File_options) . " */\n";
-    close(TEMP);
-    print STDERR "Prepending OPTIONS: " . join(' ',@File_options) . " to ${final}.${suffix}\n" if $Verbose;
-  }
-  $to_do = "$Cat $tmp  >> ${final}.${suffix}";
-  &run_something($to_do, "Saving copy of .${suffix} file");
-
-}
-
-\end{code}
-
-
-Command-line processor
-
-\begin{code}
-sub processArgs {
-    local(@Args) = @_;
-
-# can't use getopt(s); what we want is too complicated
-
-arg: while($_ = $Args[0]) {
-    shift(@Args);
-
-    #---------- help -------------------------------------------------------
-    if (/^-\?$/ || /^--?help$/) { print $LongUsage; exit $Status; }
-
-    #-----------version ----------------------------------------------------
-    /^--version$/   && do { print STDERR "${ProjectName}, version ${ProjectVersion}\n"; exit $Status; };
-
-    #---------- verbosity and such -----------------------------------------
-    /^-v$/         && do { $Verbose = '-v'; $Time = 'time'; next arg; };
-
-    #---------- what phases are to be run ----------------------------------
-    /^-(no-)?recomp/       && do { $Do_recomp_chkr = ($1 eq '') ? 1 : 0; next arg; };
-
-    /^-cpp$/       && do { $Cpp_flag_set = 1; next arg; };
-    # change the global default:
-    # we won't run cat; we'll run the real thing
-       
-    /^-C$/         && do { $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0; $HscLang = 'C';
-                           next arg; };
-    # stop after generating C
-       
-    /^-J$/         && do { $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0; $HscLang = 'java';
-                           next arg; };
-    # stop after generating Java
-       
-    /^-noC$/       && do { $HscLang = 'none'; $ProduceHi = '-nohifile=';
-                           $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0;
-                           next arg; };
-    # leave out actual C generation (debugging) [also turns off interface gen]
-
-
-    /^-hi$/             && do { $HiOnStdout = 1; $ProduceHi = '-hifile='; next arg; };
-    # _do_ generate an interface; usually used as: -noC -hi
-    /^-hi-with-(.*)$/    && do { $HiOnStdout = 1; $HiWith .= " $1" ; $ProduceHi = '-hifile='; next arg; };
-    # limit ourselves to outputting a particular section.
-
-    /^-nohi$/      && do { $ProduceHi = '-nohifile='; next arg; };
-    # don't generate an interface (even if generating C)
-
-    /^-hi-diffs$/             && do { $HiDiff_flag  = 'normal'; next arg; };
-    /^-hi-diffs-with-usages$/ && do { $HiDiff_flag  = 'usages'; next arg; };
-    /^-no-hi-diffs$/          && do { $HiDiff_flag  = '';       next arg; };
-    /^-keep-hi-diffs$/       && do { $Keep_HiDiffs = 1; next arg; };
-
-    # show/disable diffs if the interface file changes
-
-    /^-E$/         && do { push(@CcBoth_flags, '-E');
-                           $Only_preprocess_C = 1;
-                           $Do_as = 0; $Do_lnkr = 0; next arg; };
-    # stop after preprocessing C
-    /^-M$/         && do { $Only_generate_deps = 1; $Do_as = 0; $Do_lnkr = 0; next arg; };
-    # only generate dependency information.
-    /^--mk-dll$/    && do { $Only_generate_dll  = 1; $Do_as = 0; $Do_lnkr = 0; next arg; };
-    # Build a Win32 DLL (where supported).
-    /^-S$/         && do { $Do_as = 0; $Do_lnkr = 0; next arg; };
-    # stop after generating assembler
-       
-    /^-c$/         && do { $Do_lnkr = 0; next arg; };
-    # stop after generating .o files
-
-    /^-link-chk$/    && do { $LinkChk = 1; next arg; };
-    # don't do consistency-checking after a link
-    /^-no-link-chk$/ && do { $LinkChk = 0; next arg; };
-
-    /^-tmpdir$/ && do { $Tmp_prefix = &grab_arg_arg(*Args,'-tmpdir', '');
-                       $Tmp_prefix = "$Tmp_prefix/ghc$$";
-                       $ENV{'TMPDIR'} = $Tmp_prefix; # for those who use it...
-                       next arg; };
-    # use an alternate directory for temp files
-
-    #---------- redirect output --------------------------------------------
-
-    # -o <file>; applies to the last phase, whatever it is
-    # "-o -" sends it to stdout
-    # if <file> has a directory component, that dir must already exist
-
-    /^-odir$/      && do { $Specific_output_dir = &grab_arg_arg(*Args,'-odir', '');
-                           #
-                           # Hack, of the worst sort: don't do validation of
-                           # odir argument if you're using -M (dependency generation).
-                           #
-                           if ( ! $Only_generate_deps && ! -d $Specific_output_dir) {
-                               print STDERR "$Pgm: -odir: no such directory: $Specific_output_dir\n";
-                               $Status++;
-                           }
-                           next arg; };
-
-    /^-o$/         && do { $Specific_output_file = &grab_arg_arg(*Args,'-o', '');
-                           if ($Specific_output_file ne '-'
-                            && $Specific_output_file =~ /(.*)\/[^\/]*$/) {
-                               local($dir_part) = $1;
-                               if (! -d $dir_part) {
-                                   print STDERR "$Pgm: no such directory: $dir_part\n";
-                                   $Status++;
-                               }
-                           }
-                           next arg; };
-
-    # NB: -isuf not documented yet (because it doesn't work yet)
-    /^-isuf$/      && do { $Isuffix  = &grab_arg_arg(*Args,'-isuf', '');
-                           if ($Isuffix =~ /\./ ) {
-                               print STDERR "$Pgm: -isuf suffix shouldn't contain a .\n";
-                               $Status++;
-                           }
-                           next arg; };
-
-    /^-osuf$/      && do { $Osuffix  = &grab_arg_arg(*Args,'-osuf', '');
-                           if ($Osuffix =~ /\./ ) {
-                               print STDERR "$Pgm: -osuf suffix shouldn't contain a .\n";
-                               $Status++;
-                           }
-                           next arg; };
-
-    # -ohi <file>; send the interface to <file>; "-ohi -" to send to stdout
-    /^-ohi$/       && do { $Specific_hi_file = &grab_arg_arg(*Args,'-ohi', '');
-                           if ($Specific_hi_file ne '-'
-                            && $Specific_hi_file =~ /(.*)\/[^\/]*$/) {
-                               local($dir_part) = $1;
-                               if (! -d $dir_part) {
-                                   print STDERR "$Pgm: no such directory: $dir_part\n";
-                                   $Status++;
-                               }
-                           }
-                           $ProduceHi='-hifile=';
-                           next arg; };
-
-    # The suffix to use when looking for interface files
-    /^-hisuf$/     && do { $HiSuffix = &grab_arg_arg(*Args,'-hisuf', '');
-                           if ($HiSuffix =~ /\./ ) {
-                               print STDERR "$Pgm: -hisuf suffix shouldn't contain a .\n";
-                               $Status++;
-                           }
-                           next arg; };
-    /^-odump$/     && do { $Specific_dump_file = &grab_arg_arg(*Args,'-odump', '');
-                           if ($Specific_dump_file =~ /(.*)\/[^\/]*$/) {
-                               local($dir_part) = $1;
-                               if (! -d $dir_part) {
-                                   print STDERR "$Pgm: no such directory: $dir_part\n";
-                                   $Status++;
-                               }
-                           }
-                           next arg; };
-
-    #-------------- scc & Profiling Stuff ----------------------------------
-
-    /^-prof$/ && do { $PROFing = 'p'; next arg; }; # profiling -- details later!
-
-    /^-auto-dicts$/ && do {
-               $PROFdicts = '-fauto-sccs-on-dicts';
-               next arg; };
-    /^-auto-all$/ && do {
-               $PROFauto = '-fauto-sccs-on-all-toplevs';
-               next arg; };
-    /^-auto$/ && do {
-               $PROFauto = '-fauto-sccs-on-exported-toplevs';
-               next arg; };
-
-    /^-caf-all/ && do { # generate individual CAF SCC annotations
-               $PROFcaf = '-fauto-sccs-on-individual-cafs';
-               next arg; };
-
-    /^-ignore-scc$/ && do {
-               # forces ignore of scc annotations even if profiling
-               $PROFignore_scc = '-W';
-               next arg; };
-
-    /^-unprof-scc-auto/ && do {
-               # generate auto SCCs on top level bindings when not profiling.
-               # Used to measure optimisation effects of presence of sccs.
-               $UNPROFscc_auto = ( /-all/ )
-                           ? '-fauto-sccs-on-all-toplevs'
-                           : '-fauto-sccs-on-exported-toplevs';
-               next arg; };
-
-    #--------- ticky/parallel ----------------------------------------------
-    # we sort out the details a bit later on
-
-    /^-gransim$/    && do { $GRANing   = 'g'; &add_syslib('concurrent'); next arg; }; # GranSim
-    /^-ticky$/     && do { $TICKYing  = 't'; next arg; }; # ticky-ticky
-    /^-parallel$/   && do { $PARing    = 'p'; &add_syslib('concurrent'); next arg; }; # parallel Haskell
-    /^-smp$/        && do { $SMPing    = 's'; &add_syslib('concurrent'); next arg; }; # parallel Haskell
-
-    #-------------- "user ways" --------------------------------------------
-
-    (/^-user-setup-([a-oA-Z])$/ ) && 
-           do {
-               /^-user-setup-([a-oA-Z])$/  && do { $BuildTag = "_$1"; };
-
-               local($stuff) = $UserSetupOpts{$BuildTag};
-               local(@opts)  = split(/\s+/, $stuff);
-               
-               # feed relevant ops into the arg-processing loop (if any)
-               unshift(@Args, @opts) if $#opts >= 0;
-
-               next arg; };
-
-    #---------- set search paths for libraries and things ------------------
-
-    # we do -i just like HBC (-i clears the list; -i<colon-separated-items>
-    # prepends the items to the list); -I is for including C .h files.
-
-    /^-i$/         && do { @Import_dir = ();  # import path cleared!
-                           @SysImport_dir = ();
-                           print STDERR "WARNING: import paths cleared by `-i'\n";
-                           next arg; };
-
-    /^-i(.*)/      && do { local(@new_items);
-                           local($arg) = $1;
-    
-                           #
-                           if ( $arg =~ /;/ ) {
-                              $SplitMarker=";";
-                              @new_items = split( /;/, &grab_arg_arg(*Args,'-i', $arg));
-                           } else {
-                              @new_items = split( /:/, &grab_arg_arg(*Args,'-i', $arg));
-                           }
-                           unshift(@Import_dir, @new_items);
-                           next arg; };
-
-    /^-I(.*)/      && do { push(@Include_dir,     &grab_arg_arg(*Args,'-I', $1)); next arg; };
-    /^-L(.*)/      && do { push(@UserLibrary_dir, &grab_arg_arg(*Args,'-L', $1)); next arg; };
-    /^-l(.*)/      && do { push(@UserLibrary,'-l'.&grab_arg_arg(*Args,'-l', $1)); next arg; };
-
-       # DEPRECATED: use -package instead
-    /^-syslib(.*)/  && do { local($syslib) = &grab_arg_arg(*Args,'-syslib',$1);
-                           &add_syslib($syslib);
-                           next arg; };
-
-    /^-package-name(.*)/ && do 
-                          { local($package) = &grab_arg_arg(*Args,'-package-name',$1);
-                            push(@HsC_flags,"-inpackage=$package"); 
-                            next arg; 
-                          };
-
-    /^-package(.*)/ && do { local($package) = &grab_arg_arg(*Args,'-package',$1);
-                           &add_syslib($package);
-                           next arg; };
-
-    #=======================================================================
-    # various flags that we can harmlessly send to one program or another
-    # (we will later "reclaim" some of the compiler ones now sent to gcc)
-    #=======================================================================
-
-    #---------- this driver itself (ghc) -----------------------------------
-    # these change what executable is run for each phase:
-    /^-pgmL(.*)$/   && do { $Unlit      = $1; next arg; };
-    /^-pgmP(.*)$/   && do { $HsCpp      = $1; next arg; };
-    /^-pgmC(.*)$/   && do { $HsC        = $1; next arg; };
-    /^-pgmcO?(.*)$/ && do { $CcRegd     = $1; next arg; }; # the O? for back compat
-    /^-pgma(.*)$/   && do { $As         = $1; next arg; };
-    /^-pgml(.*)$/   && do { $Lnkr       = $1; next arg; };
-    /^-pgmdep(.*)$/ && do { $MkDependHS = $1; next arg; };
-
-    #---------- the get-anything-through opts (all pgms) -------------------
-    # these allow arbitrary option-strings to go to any phase:
-    /^-optL(.*)$/   && do { push(@Unlit_flags,      $1); next arg; };
-    /^-optP(.*)$/   && do { push(@HsCpp_flags,      $1); next arg; };
-    /^-optCrts(.*)$/&& do { push(@HsC_rts_flags,    $1); next arg; };
-    /^-optC(.*)$/   && do { push(@HsC_flags,        $1); next arg; };
-    /^-optcpp(.*)$/ && do { push(@Cpp_define,       $1); $Only_preprocess_hc = ($1 eq "-E"); next arg; };
-    /^-optc(.*)$/   && do { push(@CcBoth_flags,     $1); next arg; };
-    /^-opta(.*)$/   && do { push(@As_flags,         $1); next arg; };
-    /^-optl(.*)$/   && do { push(@Ld_flags,         $1); next arg; };
-    /^-optdll(.*)$/ && do { push(@Dll_flags,        $1); next arg; };
-    /^-optdep(.*)$/ && do { push(@MkDependHS_flags, $1); next arg; };
-
-    #---------- Haskell C pre-processor (hscpp) ----------------------------
-    /^-D(.*)/      && do { push(@HsCpp_flags, "'-D".&grab_arg_arg(*Args,'-D',$1)."'"); next arg; };
-    /^-U(.*)/      && do { push(@HsCpp_flags, "'-U".&grab_arg_arg(*Args,'-U',$1)."'"); next arg; };
-
-    #---------- post-Haskell "assembler"------------------------------------
-    /^-ddump-raw-asm$/           && do { $Dump_raw_asm        = 1; next arg; };
-    /^-ddump-asm-splitting-info$/ && do { $Dump_asm_splitting_info = 1; next arg; };
-
-    #---------- Haskell compiler (hsc) -------------------------------------
-
-    /^-keep-hc-files?-too$/    && do { $Keep_hc_file_too = 1; next arg; };
-    /^-keep-s-files?-too$/     && do { $Keep_s_file_too = 1;  next arg; };
-
-    /^-fignore-interface-pragmas$/ && do { push(@HsC_flags, $_); next arg; };
-    /^-fignore-asserts$/           && do { push(@HsC_flags, $_); next arg; };
-
-    /^-fno-implicit-prelude$/      && do { $NoImplicitPrelude= 1; push(@HsC_flags, $_); next arg; };
-
-     #
-     # have the compiler proper generate concurrent code,
-     # really only used when you want to configure your own
-     # special user compilation way.
-     #
-     # (ditto for -fgransim, fscc-profiling, -fparallel and -fticky-ticky)
-     #
-    /^-fscc-profiling$/   && do { push(@HsC_flags,$_); next arg; };
-    /^-fticky-ticky$/     && do { push(@HsC_flags,$_); next arg; };
-    /^-fgransim$/        && do { push(@HsC_flags,$_); next arg; };
-    /^-fparallel$/        && do { push(@HsC_flags,$_); next arg; };
-    /^-fsmp$/             && do { push(@HsC_flags,$_); next arg; };
-
-    /^-split-objs$/    && do {
-                       if ( $TargetPlatform !~ /^(alpha|hppa1\.1|i386|m68k|mips|powerpc|rs6000|sparc)-/ ) {
-                           $SplitObjFiles = 0;
-                           print STDERR "WARNING: don't know how to split objects on this platform: $TargetPlatform\n`-split-objs' option ignored\n";
-                       } else {
-                           $SplitObjFiles = 1;
-                           $HscLang = 'C';
-
-                           push(@HsC_flags, "-fglobalise-toplev-names"); 
-                           push(@CcBoth_flags, '-DUSE_SPLIT_MARKERS');
-
-                           require('ghc-split.prl')
-                            || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-split.prl!\n");
-                       }
-                       next arg; };
-
-    /^-unreg$/             && do { $UNREGing = 'u'; next arg; };
-    /^-funregisterised$/    && do { push(@HsC_flags, $_); next arg; };
-    /^-fno-asm-mangling$/   && do { $DoAsmMangling = 0; next arg; };
-
-    /^-fallow-overlapping-instances$/ && do { push(@HsC_flags, $_); next arg; };
-    /^-fallow-undecidable-instances$/ && do { push(@HsC_flags, $_); next arg; };
-    /^-fhistory-size.*$/             && do { push(@HsC_flags, $_); next arg; };
-    /^-fdicts-strict$/                       && do { push(@HsC_flags, $_); next arg; };
-
-    /^-fglasgow-exts$/
-               && do { push(@HsC_flags, $_);
-
-                       # -fglasgow-exts implies -package lang
-                       &add_syslib('lang');
-
-                       next arg; };
-
-       # for compiling lib/std we can't add the implicit package lang,
-       # because it isn't built yet.
-    /^-fglasgow-exts-no-lang$/
-               && do { push(@HsC_flags, "-fglasgow-exts"); next arg; };
-
-    /^-fspeciali[sz]e$/
-               && do { $Oopt_DoSpecialise = '-fspecialise'; next arg; };
-    /^-fno-speciali[sz]e$/
-               && do { $Oopt_DoSpecialise = ''; next arg; };
-
-    /^-fusagesp$/
-                && do {  $Oopt_UsageSPInf = '-fusagesp';
-                         push (@HsC_flags, '-fusagesp-on'); next arg; };
-
-# Now the foldr/build options, which are *on* by default (for -O).
-
-    /^-ffoldr-build$/
-                   && do { $Oopt_FoldrBuild = 1; 
-                           #print "Yes F/B\n";
-                           next arg; };
-
-    /^-fno-foldr-build$/
-                   && do { $Oopt_FoldrBuild = 0; 
-                           next arg; };
-
-    # --------------- Renamer -------------
-
-
-    /^-fno-prune-tydecls$/     && do { push(@HsC_flags, $_); next arg; };
-    /^-fno-prune-instdecls$/     && do { push(@HsC_flags, $_); next arg; };
-
-    # ---------------
-
-    /^-fasm-(.*)$/     && do { $HscLang = 'asm'; next arg; }; # force using nativeGen
-    /^-fvia-[cC]$/     && do { $HscLang = 'C';   next arg; }; # force using C compiler
-
-    # ---------------
-
-    /^-funfolding-.*$/
-                   && do { push(@HsC_flags, $_); next arg };
-
-    /^-fliberate-case-.*$/
-                   && do { push(@HsC_flags, $_); next arg };
-
-    /^-funfold-casms-in-hi-file$/
-                   && do { push(@HsC_flags, $_); next arg };
-
-    /^(-fmax-simplifier-iterations)(.*)$/
-                   && do { $Oopt_MaxSimplifierIterations = $1 . &grab_arg_arg(*Args,$1, $2);
-                           next arg; };
-
-    /^-fno-pre-inlining$/
-                   && do { push(@HsC_flags, $_); next arg };
-
-    /^-fno-let-from-(case|app|strict-let)$/ # experimental, really (WDP 95/10)
-                   && do { push(@HsC_flags, $_); next arg; };
-
-    /^-funbox-strict-fields$/
-                  && do { push(@HsC_flags, $_); next arg; };
-
-    # --------------- Warnings etc. ------
-
-    /^-fwarn-(.*)$/ && do { if (!grep(/$1/,@MinusWallOpts)) {
-                               print STDERR "$Pgm: unrecognised warning option: $_\n";
-                               $Status++;
-                           } else {                            
-                               push(@HsC_flags, $_); 
-                           }
-                           next arg; };
-
-    /^-fno-(.*)$/   && do { push(@HsC_antiflags, "-f$1");
-                           &squashHscFlag("-f$1");
-                           next arg; };
-
-    /^-W$/         && do { push(@HsC_flags, @MinusWOpts); next arg; };
-    /^-Wall$/      && do { push(@HsC_flags, @MinusWallOpts); next arg; };
-    /^(-Wnot|w)$/   && do { foreach (@Hsc_flags) {
-                               /^-fwarn-(.*)$/ && do { $_=''; };
-                           };
-                           push(@HsC_antiflags, @StandardWarnings);
-                           next arg; };
-
-    # --------------- fun stuff ----------------
-
-    /^-freport-compile$/ && do { push(@HsC_flags, $_); next arg; };
-
-    # --------------- platform specific flags (for gcc mostly) ----------------
-
-    /^-mlong-calls$/ && do { # for GCC for HP-PA boxes,
-                             # for 2.6.x..?, does not apply for 2.7.2
-                            # any longer.
-                           unshift(@CcBoth_flags, ( $_ ));
-                           next arg; };
-
-    /^-m(v8|sparclite|cypress|supersparc|cpu=(cypress|supersparc))$/
-                    && do { # for GCC for SPARCs
-                           unshift(@CcBoth_flags, ( $_ ));
-                           next arg; };
-
-    /^-monly-([432])-regs/ && do { # for iX86 boxes only; no effect otherwise
-                           $StolenX86Regs = $1;
-                           next arg; };
-
-    #*************** ... and lots of debugging ones (form: -d* )
-
-    # -d(no-)core-lint is done this way so it is turn-off-able.
-    /^-dcore-lint/       && do { $CoreLint = '-dcore-lint'; next arg; };
-    /^-dno-core-lint/    && do { $CoreLint = '';           next arg; };
-    # Ditto for USP lint
-    /^-dusagesp-lint/    && do { $USPLint = '-dusagesp-lint'; next arg; };
-    /^-dno-usagesp-lint/ && do { $USPLint = '';               next arg; };
-    # Ditto for STG lint
-    /^-dstg-lint/       && do { $StgLint = '-dstg-lint'; next arg; };
-    /^-dno-stg-lint/    && do { $StgLint = '';           next arg; };
-
-    /^-d(dump|ppr)-/         && do { push(@HsC_flags, $_); next arg; };
-    /^-dverbose-(simpl|stg)/ && do { push(@HsC_flags, $_); next arg; };
-    /^-dshow-passes/        && do { push(@HsC_flags, $_); next arg; };
-    /^-dshow-rn-stats/      && do { push(@HsC_flags, $_); next arg; };
-    /^-dshow-rn-trace/      && do { push(@HsC_flags, $_); next arg; };
-    /^-dsource-stats/        && do { push(@HsC_flags, $_); next arg; };
-    /^-dsimplifier-stats/    && do { push(@HsC_flags, $_); next arg; };
-    /^-dstg-stats/          && do { $Oopt_StgStats = $_; next arg; };
-
-    #*************** ... and now all these -R* ones for its runtime system...
-
-    /^-Rscale-sizes?(.*)/ && do {
-       $Scale_sizes_by = &grab_arg_arg(*Args,'-Rscale-sizes', $1);
-       next arg; };
-
-    /^(-H|-Rmax-heapsize)(.*)/ && do {
-       local($heap_size) = &grab_arg_arg(*Args,$1, $2);
-       if ($heap_size =~ /(\d+)[Kk]$/) {
-           $heap_size = $1 * 1000;
-       } elsif ($heap_size =~ /(\d+)[Mm]$/) {
-           $heap_size = $1 * 1000 * 1000;
-       } elsif ($heap_size =~ /(\d+)[Gg]$/) {
-           $heap_size = $1 * 1000 * 1000 * 1000;
-       }
-       if ($heap_size <= 0) {
-           print STDERR "$Pgm: resetting heap-size to zero!!! $heap_size\n";
-           $Specific_heap_size = 0;
-       
-       # if several heap sizes given, take the largest...
-       } elsif ($heap_size >= $Specific_heap_size) {
-           $Specific_heap_size = $heap_size;
-       } else {
-           print STDERR "$Pgm: ignoring heap-size-setting option ($_)...not the largest seen\n" if $Verbose;
-       }
-       next arg; };
-
-    /^(-K|Rmax-(stk|stack)size)(.*)/ && do {
-        local($flag) = $1;
-       local($stk_size) = &grab_arg_arg(*Args,'-Rmax-stksize', $3);
-       if ($stk_size =~ /(\d+)[Kk]$/) {
-           $stk_size = $1 * 1000;
-       } elsif ($stk_size =~ /(\d+)[Mm]$/) {
-           $stk_size = $1 * 1000 * 1000;
-       } elsif ($stk_size =~ /(\d+)[Gg]$/) {
-           $stk_size = $1 * 1000 * 1000 * 1000;
-       }
-       if ($stk_size <= 0) {
-           print STDERR "$Pgm: resetting stack-size to zero!!! $stk_size\n";
-           $Specific_stk_size = 0;
-
-       # if several stack sizes given, take the largest...
-       } elsif ($stk_size >= $Specific_stk_size) {
-           $Specific_stk_size = $stk_size;
-       } else {
-           print STDERR "$Pgm: ignoring stack-size-setting option ($flag $stk_size)...not the largest seen\n" if $Verbose;
-       }
-       next arg; };
-
-    /^-Rgc-stats$/ && do {  $CollectingGCstats++;
-                           # the two RTSs do this diff ways; we will try to compensate
-                           next arg; };
-
-    /^-Rghc-timing/ && do { $CollectGhcTimings = 1; next arg; };
-
-    #---------- C high-level assembler (gcc) -------------------------------
-    /^-(Wall|ansi|pedantic)$/ && do { push(@CcBoth_flags, $_); next arg; };
-
-    # -dgcc-lint is a useful way of making GCC very fussy.
-    # From alan@spri.levels.unisa.edu.au (Alan Modra).
-    /^-dgcc-lint$/ && do { push(@CcBoth_flags, '-Wall -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wnested-externs'); next arg; };
-    # An alternate set, from mark@sgcs.com (Mark W. Snitily)
-    # -Wall -Wstrict-prototypes -Wmissing-prototypes -Wcast-align -Wshadow
-
-    # inject "#include <wurble>" into the compiler's C output!
-
-    /^-#include(.*)/   && do {
-       local($to_include) = &grab_arg_arg(*Args,'-#include', $1);
-       push(@CcInjects, "#include $to_include\n");
-       next arg; };
-
-    #---------- Linker (gcc, really) ---------------------------------------
-
-    /^-static$/                && do { $Static=1; push(@Ld_flags, $_); next arg; };
-    /^-no-hs-main$/    && do { $NoHaskellMain=1; next arg;    };
-
-    #---------- mixed cc and linker magic ----------------------------------
-    # this optimisation stuff is finally sorted out later on...
-
-    /^-O2-for-C$/ && do { $MinusO2ForC = 1; next arg; };
-
-    /^-O[1-2]?$/ && do {
-               local($opt_lev) = ( /^-O2$/ ) ? 2 : 1; # max 'em
-               $OptLevel = ( $opt_lev > $OptLevel ) ? $opt_lev : $OptLevel;
-
-               $HscLang = 'C';  # force use of C compiler
-               next arg; };
-
-    /^-Onot$/  && do { $OptLevel = 0; next arg; }; # # set it to <no opt>
-
-    /^-Ofile(.*)/ && do {
-               $OptLevel = 3;
-               local($ofile) = &grab_arg_arg(*Args,'-Ofile', $1);
-               @HsC_minusO3_flags = ();
-
-               open(OFILE, "< $ofile") || die "Can't open $ofile!\n";
-               while (<OFILE>) {
-                   chop;
-                   s/\#.*//;       # death to comments
-                   s/[ \t]+//g;    # death to whitespace
-                   next if /^$/;   # ditto, blank lines
-                   s/([()*{}])/\\$1/g;    # protect shell metacharacters
-                   if ( /^C:(.*)/ ) {
-                       push(@CcBoth_flags, $1);
-                   } else {
-                       push(@HsC_minusO3_flags, $_);
-                   }
-               }
-               close(OFILE);
-               next arg; };
-
-    /^-debug$/ && do { # all this does is mark a .hc/.o as "debugging"
-                       # in the consistency info
-                       $DEBUGging = 'd';
-                       next arg; };
-
-    #---------- linking .a file --------------------------------------------
-
-    /^-Main(.*)/ && do {
-               # specifies main or mainPrimIO to be linked
-               $Ld_main = $1;
-               next arg; }; 
-
-    #---------- catch unrecognized flags -----------------------------------
-
-    /^-./ && do {
-       print STDERR "$Pgm: unrecognised option: $_\n";
-       $Status++;
-       next arg; };
-
-}
-
-} # end of processArgs
-
-\end{code}
diff --git a/ghc/driver/mangler/Makefile b/ghc/driver/mangler/Makefile
new file mode 100644 (file)
index 0000000..3140c42
--- /dev/null
@@ -0,0 +1,16 @@
+#-----------------------------------------------------------------------------
+# $Id: Makefile,v 1.1 2000/06/13 16:07:20 simonmar Exp $
+
+TOP=../..
+include $(TOP)/mk/boilerplate.mk
+
+SCRIPT_PROG    = ghc-asm
+SCRIPT_OBJS     = ghc-asm.prl
+
+INTERP=perl
+
+SCRIPT_SUBST_VARS := TARGETPLATFORM
+
+INSTALL_LIBEXEC_SCRIPTS += $(SCRIPT_PROG)
+
+include $(TOP)/mk/target.mk
index 3515512..29a6894 100644 (file)
@@ -42,6 +42,28 @@ for the same reason.  Advantage: No more ridiculous call sequences.
 
 %************************************************************************
 %*                                                                     *
+\subsection{Top-level code}
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
+$TargetPlatform = $TARGETPLATFORM;
+
+($Pgm = $0) =~ s|.*/||;
+$ifile = $ARGV[0];
+$ofile = $ARGV[1];
+
+if ( $TargetPlatform =~ /^i386-/ ) {
+    $StolenX86Regs = $ARGV[2];
+}
+
+&mangle_asm($ifile,$ofile);
+
+exit(0);
+\end{code}
+
+%************************************************************************
+%*                                                                     *
 \subsection{Constants for various architectures}
 %*                                                                     *
 %************************************************************************
@@ -54,7 +76,6 @@ sub init_TARGET_STUFF {
 
     $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
     $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_DO_GC       = 'PerformGC_wrapper';
     $T_PRE_APP     = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^\$C(\d+):$'; # regexp for what such a lbl looks like
     $T_POST_LBL            = ':';
@@ -70,6 +91,7 @@ sub init_TARGET_STUFF {
     $T_HDR_data            = "\.data\n\t\.align 3\n";
     $T_HDR_consist  = "\.text\n";
     $T_HDR_closure  = "\.data\n\t\.align 3\n";
+    $T_HDR_srt      = "\.text\n\t\.align 3\n";
     $T_HDR_info            = "\.text\n\t\.align 3\n";
     $T_HDR_entry    = "\.text\n\t\.align 3\n";
     $T_HDR_fast            = "\.text\n\t\.align 3\n";
@@ -81,7 +103,6 @@ sub init_TARGET_STUFF {
 
     $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
     $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_DO_GC       = 'PerformGC_wrapper';
     $T_PRE_APP     = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^L\$C(\d+)$'; # regexp for what such a lbl looks like
     $T_POST_LBL            = '';
@@ -90,13 +111,14 @@ sub init_TARGET_STUFF {
     $T_COPY_DIRVS   = '^\s+\.(IMPORT|EXPORT)';
 
     $T_hsc_cc_PAT   = '\.STRING.*\)(hsc|cc) (.*)\\\\x09(.*)\\\\x00"';
-    $T_DOT_WORD            = '\.word';
+    $T_DOT_WORD            = '\.(blockz|word|half|byte)';
     $T_DOT_GLOBAL   = '^\s+\.EXPORT';
     $T_HDR_literal  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
     $T_HDR_misc            = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
     $T_HDR_data            = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
     $T_HDR_consist  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
     $T_HDR_closure  = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
+    $T_HDR_srt      = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
     $T_HDR_info            = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
     $T_HDR_entry    = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
     $T_HDR_fast            = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
@@ -104,12 +126,11 @@ sub init_TARGET_STUFF {
     $T_HDR_direct   = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
 
     #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^i386-.*-(linuxaout|freebsd|nextstep3|cygwin32)/ ) {
+    } elsif ( $TargetPlatform =~ /^i386-.*-(linuxaout|freebsd2|netbsd|nextstep3|cygwin32|mingw32)$/ ) {
                                # NeXT added but not tested. CaS
 
     $T_STABBY      = 1; # 1 iff .stab things (usually if a.out format)
     $T_US          = '_'; # _ if symbols have an underscore on the front
-    $T_DO_GC       = '_PerformGC_wrapper';
     $T_PRE_APP     = '^#'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^LC(\d+):$';
     $T_POST_LBL            = ':';
@@ -120,13 +141,15 @@ sub init_TARGET_STUFF {
     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.stab[^n].*|\.type\s+.*|\.size\s+.*)\n)';
     $T_COPY_DIRVS   = '\.(globl|stab)';
     $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
-    $T_DOT_WORD            = '\.long';
+    $T_DOT_WORD            = '\.(long|word|value|byte|space)';
     $T_DOT_GLOBAL   = '\.globl';
     $T_HDR_literal  = "\.text\n\t\.align 2\n";
     $T_HDR_misc            = "\.text\n\t\.align 2,0x90\n";
     $T_HDR_data            = "\.data\n\t\.align 2\n";
     $T_HDR_consist  = "\.text\n";
     $T_HDR_closure  = "\.data\n\t\.align 2\n";
+    $T_HDR_closure  = "\.data\n\t\.align 2\n\t.long 0\n" if ( $TargetPlatform =~ /.*-mingw32$/ );
+    $T_HDR_srt      = "\.text\n\t\.align 2\n";
     $T_HDR_info            = "\.text\n\t\.align 2\n"; # NB: requires padding
     $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
     $T_HDR_fast            = "\.text\n\t\.align 2,0x90\n";
@@ -134,42 +157,46 @@ sub init_TARGET_STUFF {
     $T_HDR_direct   = "\.text\n\t\.align 2,0x90\n";
 
     #--------------------------------------------------------#
-    } elsif ( $TargetPlatform =~ /^i386-.*-(solaris2|linux)$/ ) {
+    } elsif ( $TargetPlatform =~ /^i386-.*-(solaris2|linux|freebsd|netbsd_elf)$/ ) {
 
     $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
     $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_DO_GC       = 'PerformGC_wrapper';
     $T_PRE_APP     = # regexp that says what comes before APP/NO_APP
-                     ($TargetPlatform =~ /-linux$/) ? '#' : '/' ;
+                     ($TargetPlatform =~ /-(linux|freebsd|netbsd_elf)$/) ? '#' : '/' ;
     $T_CONST_LBL    = '^\.LC(\d+):$'; # regexp for what such a lbl looks like
     $T_POST_LBL            = ':';
     $T_X86_PRE_LLBL_PAT = '\.L';
     $T_X86_PRE_LLBL        = '.L';
     $T_X86_BADJMP   = '^\tjmp [^\.\*]';
 
-    $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.Lfe.*\n\t\.size\s+.*|\.size\s+.*|\.ident.*)\n)';
+    $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.Lfe.*\n\t\.size\s+.*|\.size\s+.*|\.ident.*)\n)';
     $T_COPY_DIRVS   = '\.(globl)';
 
-    $T_hsc_cc_PAT   = '\.string.*\)(hsc|cc) (.*)\\\\t(.*)"';
-    $T_DOT_WORD            = '\.long';
+    if ( $TargetPlatform =~ /freebsd|netbsd_elf/ ) {
+        $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
+    } else {
+        $T_hsc_cc_PAT   = '\.string.*\)(hsc|cc) (.*)\\\\t(.*)"';
+    }
+
+    $T_DOT_WORD            = '\.(long|value|byte|zero)';
     $T_DOT_GLOBAL   = '\.globl';
     $T_HDR_literal  = "\.section\t\.rodata\n"; # or just use .text??? (WDP 95/11)
-    $T_HDR_misc            = "\.text\n\t\.align 16\n";
+    $T_HDR_misc            = "\.text\n\t\.align 4\n";
     $T_HDR_data            = "\.data\n\t\.align 4\n"; # ToDo: change align??
     $T_HDR_consist  = "\.text\n";
     $T_HDR_closure  = "\.data\n\t\.align 4\n"; # ToDo: change align?
-    $T_HDR_info            = "\.text\n\t\.align 16\n"; # NB: requires padding
+    $T_HDR_srt      = "\.text\n\t\.align 4\n"; # ToDo: change align?
+    $T_HDR_info            = "\.text\n\t\.align 4\n"; # NB: requires padding
     $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
-    $T_HDR_fast            = "\.text\n\t\.align 16\n";
-    $T_HDR_vector   = "\.text\n\t\.align 16\n"; # NB: requires padding
-    $T_HDR_direct   = "\.text\n\t\.align 16\n";
+    $T_HDR_fast            = "\.text\n\t\.align 4\n";
+    $T_HDR_vector   = "\.text\n\t\.align 4\n"; # NB: requires padding
+    $T_HDR_direct   = "\.text\n\t\.align 4\n";
 
     #--------------------------------------------------------#
     } elsif ( $TargetPlatform =~ /^m68k-.*-sunos4/ ) {
 
     $T_STABBY      = 1; # 1 iff .stab things (usually if a.out format)
     $T_US          = '_'; # _ if symbols have an underscore on the front
-    $T_DO_GC       = '_PerformGC_wrapper';
     $T_PRE_APP     = '^# MAY NOT APPLY'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^LC(\d+):$';
     $T_POST_LBL            = ':';
@@ -185,6 +212,7 @@ sub init_TARGET_STUFF {
     $T_HDR_data            = "\.data\n\t\.even\n";
     $T_HDR_consist  = "\.text\n";
     $T_HDR_closure  = "\.data\n\t\.even\n";
+    $T_HDR_srt      = "\.text\n\t\.even\n";
     $T_HDR_info            = "\.text\n\t\.even\n";
     $T_HDR_entry    = "\.text\n\t\.even\n";
     $T_HDR_fast            = "\.text\n\t\.even\n";
@@ -196,7 +224,6 @@ sub init_TARGET_STUFF {
 
     $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
     $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_DO_GC       = 'PerformGC_wrapper';
     $T_PRE_APP     = '^\s*#'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^\$LC(\d+):$'; # regexp for what such a lbl looks like
     $T_POST_LBL            = ':';
@@ -212,6 +239,7 @@ sub init_TARGET_STUFF {
     $T_HDR_data            = "\t\.data\n\t\.align 2\n";
     $T_HDR_consist  = 'TOO LAZY TO DO THIS TOO';
     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
+    $T_HDR_srt      = "\t\.text\n\t\.align 2\n";
     $T_HDR_info            = "\t\.text\n\t\.align 2\n";
     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
     $T_HDR_fast            = "\t\.text\n\t\.align 2\n";
@@ -223,7 +251,6 @@ sub init_TARGET_STUFF {
 
     $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
     $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_DO_GC       = '\.PerformGC_wrapper';
     $T_PRE_APP     = 'NOT APPLICABLE'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = 'NOT APPLICABLE'; # regexp for what such a lbl looks like
     $T_POST_LBL            = ':';
@@ -240,6 +267,7 @@ sub init_TARGET_STUFF {
     $T_HDR_data            = "# data\n\.csect \.data[RW]\n\t\.align 2\n";
     $T_HDR_consist  = "# consist\n\.csect \.data[RW]\n\t\.align 2\n";
     $T_HDR_closure  = "# closure\n\.csect \.data[RW]\n\t\.align 2\n";
+    $T_HDR_srt      = "# closure\n\.csect \.data[RW]\n\t\.align 2\n";
     $T_HDR_info            = "# info\n\.csect \.data[RW]\n\t\.align 2\n"; #not RO!?
     $T_HDR_entry    = "# entry\n\.csect \.text[PR]\n\t\.align 2\n";
     $T_HDR_fast            = "# fast\n\.csect \.text[PR]\n\t\.align 2\n";
@@ -251,7 +279,6 @@ sub init_TARGET_STUFF {
 
     $T_STABBY      = 0; # 1 iff .stab things (usually if a.out format)
     $T_US          = ''; # _ if symbols have an underscore on the front
-    $T_DO_GC       = 'PerformGC_wrapper';
     $T_PRE_APP     = 'DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^\.LLC(\d+):$'; # regexp for what such a lbl looks like
     $T_POST_LBL            = ':';
@@ -260,13 +287,14 @@ sub init_TARGET_STUFF {
     $T_COPY_DIRVS   = '\.(global|proc|stab)';
 
     $T_hsc_cc_PAT   = '\.asciz.*\)(hsc|cc) (.*)\\\\t(.*)"';
-    $T_DOT_WORD            = '\.word';
+    $T_DOT_WORD            = '\.(word|byte|half|skip|uahalf|uaword)';
     $T_DOT_GLOBAL   = '^\t\.global';
     $T_HDR_literal  = "\.text\n\t\.align 8\n";
     $T_HDR_misc            = "\.text\n\t\.align 4\n";
     $T_HDR_data            = "\.data\n\t\.align 8\n";
     $T_HDR_consist  = "\.text\n";
     $T_HDR_closure  = "\.data\n\t\.align 4\n";
+    $T_HDR_srt      = "\.data\n\t\.align 4\n";
     $T_HDR_info            = "\.text\n\t\.align 4\n";
     $T_HDR_entry    = "\.text\n\t\.align 4\n";
     $T_HDR_fast            = "\.text\n\t\.align 4\n";
@@ -278,7 +306,6 @@ sub init_TARGET_STUFF {
 
     $T_STABBY      = 1; # 1 iff .stab things (usually if a.out format)
     $T_US          = '_'; # _ if symbols have an underscore on the front
-    $T_DO_GC       = '_PerformGC_wrapper';
     $T_PRE_APP     = '^# DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
     $T_CONST_LBL    = '^LC(\d+):$';
     $T_POST_LBL            = ':';
@@ -294,6 +321,7 @@ sub init_TARGET_STUFF {
     $T_HDR_data            = "\.data\n\t\.align 8\n";
     $T_HDR_consist  = "\.text\n";
     $T_HDR_closure  = "\.data\n\t\.align 4\n";
+    $T_HDR_srt      = "\.data\n\t\.align 4\n";
     $T_HDR_info            = "\.text\n\t\.align 4\n";
     $T_HDR_entry    = "\.text\n\t\.align 4\n";
     $T_HDR_fast            = "\.text\n\t\.align 4\n";
@@ -309,7 +337,6 @@ sub init_TARGET_STUFF {
 if ( 0 ) {
 print STDERR "T_STABBY: $T_STABBY\n";
 print STDERR "T_US: $T_US\n";
-print STDERR "T_DO_GC: $T_DO_GC\n";
 print STDERR "T_PRE_APP: $T_PRE_APP\n";
 print STDERR "T_CONST_LBL: $T_CONST_LBL\n";
 print STDERR "T_POST_LBL: $T_POST_LBL\n";
@@ -379,9 +406,9 @@ sub mangle_asm {
     %slowchk = ();     # ditto, its regular "slow" entry code
     %fastchk = ();     # ditto, fast entry code
     %closurechk = ();  # ditto, the (static) closure
+    %srtchk = ();      # ditto, its SRT (for top-level things)
     %infochk = ();     # given a symbol base, say what chunk its info tbl is in
     %vectorchk = ();    # ditto, return vector table
-    %directchk = ();    # ditto, direct return code
     $EXTERN_DECLS = '';        # .globl <foo> .text (MIPS only)
 
     $i = 0; $chkcat[0] = 'misc'; $chk[0] = '';
@@ -389,6 +416,7 @@ sub mangle_asm {
     while (<INASM>) {
        next if $T_STABBY && /^\.stab.*$TUS[@]?__stg_split_marker/o;
        next if $T_STABBY && /^\.stab.*ghc.*c_ID/;
+       next if /^\t\.def.*endef$/;
        next if /$TPREAPP(NO_)?APP/o; 
        next if /^;/ && $TargetPlatform =~ /^hppa/;
 
@@ -429,7 +457,7 @@ sub mangle_asm {
            $chkcat[$i]  = 'literal';
            $chksymb[$i] = $1;
 
-       } elsif ( /^$TUS[@]?__stg_split_marker(\d+)$TPOSTLBL[@]?$/o ) {
+       } elsif ( /^$TUS[@]?__stg_split_marker(\d*)$TPOSTLBL[@]?$/o ) {
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'splitmarker';
            $chksymb[$i] = $1;
@@ -444,14 +472,14 @@ sub mangle_asm {
 
            $infochk{$symb} = $i;
 
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_entry$TPOSTLBL[@]?$/o ) {
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_(entry|ret)$TPOSTLBL[@]?$/o ) {
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'slow';
            $chksymb[$i] = $1;
 
            $slowchk{$1} = $i;
 
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_fast\d+$TPOSTLBL[@]?$/o ) {
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_fast\d*$TPOSTLBL[@]?$/o ) {
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'fast';
            $chksymb[$i] = $1;
@@ -465,6 +493,18 @@ sub mangle_asm {
 
            $closurechk{$1} = $i;
 
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_srt$TPOSTLBL[@]?$/o ) {
+           $chk[++$i]   = $_;
+           $chkcat[$i]  = 'srt';
+           $chksymb[$i] = $1;
+
+           $srtchk{$1} = $i;
+
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_ct$TPOSTLBL[@]?$/o ) {
+           $chk[++$i]   = $_;
+           $chkcat[$i]  = 'data';
+           $chksymb[$i] = '';
+
        } elsif ( /^$TUS[@]?ghc.*c_ID$TPOSTLBL/o ) {
            $chk[++$i]  = $_;
            $chkcat[$i] = 'consist';
@@ -472,10 +512,8 @@ sub mangle_asm {
        } elsif ( /^($TUS[@]?__gnu_compiled_c|gcc2_compiled\.)$TPOSTLBL/o ) {
            ; # toss it
 
-       } elsif ( /^$TUS[@]?ErrorIO_call_count$TPOSTLBL[@]?$/o  # HACK!!!!
-              || /^$TUS[A-Za-z0-9_]+\.\d+$TPOSTLBL[@]?$/o
+       } elsif ( /^$TUS[A-Za-z0-9_]+\.\d+$TPOSTLBL[@]?$/o
               || /^$TUS[@]?.*_CAT$TPOSTLBL[@]?$/o              # PROF: _entryname_CAT
-              || /^$TUS[@]?CC_.*_struct$TPOSTLBL[@]?$/o        # PROF: _CC_ccident_struct
               || /^$TUS[@]?.*_done$TPOSTLBL[@]?$/o             # PROF: _module_done
               || /^$TUS[@]?_module_registered$TPOSTLBL[@]?$/o  # PROF: _module_registered
               ) {
@@ -493,41 +531,26 @@ sub mangle_asm {
            $chkcat[$i]  = 'toc';
            $chksymb[$i] = $1;
 
-       } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ && /^CC_.*$/ ) {
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_cc(s)?$TPOSTLBL[@]?$/o ) {
             # all CC_ symbols go in the data section...
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'data';
            $chksymb[$i] = '';
 
-       } elsif ( /^($TUS[@]?(ret_|djn_)[A-Za-z0-9_]+)/o ) {
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_(alt|dflt)$TPOSTLBL[@]?$/o ) {
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'misc';
            $chksymb[$i] = '';
-           $symbtmp = $1;
-            $chksymb[$i] = $symbtmp if ($TargetPlatform =~ /^powerpc-|^rs6000-/) ; #rm andre
+           #$symbtmp = $1;
+            #$chksymb[$i] = $symbtmp if ($TargetPlatform =~ /^powerpc-|^rs6000-/) ; #rm andre
 
-       } elsif ( /^$TUS[@]?vtbl_([A-Za-z0-9_]+)$TPOSTLBL[@]?$/o ) {
+       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_vtbl$TPOSTLBL[@]?$/o ) {
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'vector';
            $chksymb[$i] = $1;
 
            $vectorchk{$1} = $i;
 
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)DirectReturn$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'direct';
-           $chksymb[$i] = $1;
-
-           $directchk{$1} = $i;
-
-       } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_upd$TPOSTLBL[@]?$/o ) {
-           $chk[++$i]   = $_;
-           $chkcat[$i]  = 'misc';
-            print STDERR "_upd!!!!! I guess this code is dead!!!!\n";
-            # I guess this is never entered, since all _upds are 
-            # either vtbl_'s or ret_'s, caught above. - andre
-           $chksymb[$i] = ''; 
-
        # As a temporary solution for compiling "foreign export" declarations,
        # we use global variables to pass arguments from C to STG land.
        # These declarations live in the .hc file and not in the generated C
@@ -559,12 +582,13 @@ sub mangle_asm {
                   || ! /^(L\.\.\d+|LT\.\..*):$/ ) ) {
            local($thing);
            chop($thing = $_);
-           print STDERR "Funny global thing?: $_"
+           print "Funny global thing?: $_"
                unless $KNOWN_FUNNY_THING{$thing}
-                   || /^$TUS[@]?_(PRIn|PRStart).*$TPOSTLBL[@]?$/o # pointer reversal GC routines
-                   || /^$TUS[@]?CC_.*$TPOSTLBL$/o              # PROF: _CC_ccident  ([@]? is a silly hack (see above))
-                   || /^$TUS__fexp_.*$TPOSTLBL$/o              # foreign export droppings (temporary)
-                   || /^$TUS[@]?_reg.*$TPOSTLBL$/o;            # PROF: __reg<module>
+                   || /^$TUS[@]?stg_.*$TPOSTLBL[@]?$/o    # RTS internals
+                   || /^$TUS[@]__fexp_.*$TPOSTLBL$/o      # foreign export
+                   || /^$TUS[@]?__init.*$TPOSTLBL$/o      # __init<module>
+                   || /^$TUS[@]?.*_btm$TPOSTLBL$/o        # large bitmaps
+                   || /^$TUS[@]?.*_closure_tbl$TPOSTLBL$/o; # closure tables
            $chk[++$i]   = $_;
            $chkcat[$i]  = 'misc';
             if ($TargetPlatform =~ /^powerpc-|^rs6000-/) 
@@ -614,19 +638,8 @@ sub mangle_asm {
             $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(\S+_fast\d+)/\t\.tc \1\[TC\],\.\2/; 
             $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(\S+_entry)\n/\t\.tc \1\[TC\],\.\2\n/;
             $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(ret_\S+)/\t\.tc \1\[TC\],\.\2/;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(djn_\S+)/\t\.tc \1\[TC\],\.\2/;
+            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(alt_\S+)/\t\.tc \1\[TC\],\.\2/;
             $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(vtbl_\S+)/\t\.tc \1\[TC\],\.\2/;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],ErrorIO_innards/\t\.tc \1\[TC\],\.ErrorIO_innards/;
-            $chk[$i] =~ s/\t\.tc (\S+)\[TC\],startStgWorld/\t\.tc \1\[TC\],\.startStgWorld/;
-            $chk[$i] =~ s/\.tc UpdatePAP\[TC\],UpdatePAP/\.tc UpdatePAP\[TC\],\.UpdatePAP/;
-            $chk[$i] =~ s/\.tc _regMain\[TC\],_regMain/\.tc _regMain\[TC\],\._regMain/; #PROF
-            $chk[$i] =~ s/\.tc resumeThread\[TC\],resumeThread/\.tc resumeThread\[TC\],\.resumeThread/; #CONC
-            $chk[$i] =~ s/\.tc EnterNodeCode\[TC\],EnterNodeCode/\.tc EnterNodeCode\[TC\],\.EnterNodeCode/; #CONC
-            $chk[$i] =~ s/\.tc StackUnderflowEnterNode\[TC\],StackUnderflowEnterNode/\.tc StackUnderflowEnterNode\[TC\],\.StackUnderflowEnterNode/; #CONC
-            $chk[$i] =~ s/\.tc stopThreadDirectReturn\[TC\],stopThreadDirectReturn/\.tc stopThreadDirectReturn\[TC\],\.stopThreadDirectReturn/; #CONC
-            $chk[$i] =~ s/\.tc CommonUnderflow\[TC\],CommonUnderflow/\.tc CommonUnderflow\[TC\],\.CommonUnderflow/; #PAR
-            $chk[$i] =~ s/\.tc IndUpdRetDir\[TC\],IndUpdRetDir/\.tc IndUpdRetDir\[TC\],\.IndUpdRetDir/;
-            $chk[$i] =~ s/\t\.tc (_PRStart_\S+)\[TC\],_PRStart_\S+/\t\.tc \1\[TC\],\.\1/;
 
              $tocnumber = $chksymb[$i];
              $tocsymb = $chk[$i];
@@ -657,6 +670,7 @@ sub mangle_asm {
                if ($TargetPlatform =~ /^i386-/) {
                    $p =~ s/^\tpushl \%edi\n//;
                    $p =~ s/^\tpushl \%esi\n//;
+                   $p =~ s/^\tpushl \%ebx\n//;
                    $p =~ s/^\tsubl \$\d+,\%esp\n//;
                     $p =~ s/^\tmovl \$\d+,\%eax\n\tcall __alloca\n// if ($TargetPlatform =~ /^.*-cygwin32/);
                } elsif ($TargetPlatform =~ /^m68k-/) {
@@ -695,6 +709,9 @@ sub mangle_asm {
                    print STDERR "$Pgm: unknown prologue mangling? $TargetPlatform\n";
                }
 
+               # HWL HACK: dont die, just print a warning
+               #print stderr  "HWL: this should die! Prologue junk?: $p\n" if $p =~ /^\t[^\.]/
+               #    && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
                die "Prologue junk?: $p\n" if $p =~ /^\t[^\.]/
                    && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
 
@@ -716,7 +733,9 @@ sub mangle_asm {
                    $e =~ s/^\tret\n//;
                    $e =~ s/^\tpopl \%edi\n//;
                    $e =~ s/^\tpopl \%esi\n//;
+                   $e =~ s/^\tpopl \%ecx\n//;
                    $e =~ s/^\taddl \$\d+,\%esp\n//;
+                   $e =~ s/^\tsubl \$-\d+,\%esp\n//;
                } elsif ($TargetPlatform =~ /^m68k-/) {
                    $e =~ s/^\tunlk a6\n//;
                    $e =~ s/^\trts\n//;
@@ -734,7 +753,10 @@ sub mangle_asm {
                } else {
                    print STDERR "$Pgm: unknown epilogue mangling? $TargetPlatform\n";
                }
-               die "Epilogue junk?: $e\n" if $e =~ /^\t[^\.]/
+               # HWL HACK: dont die, just print a warning
+               #print stderr "HWL: this should die! Epilogue junk?: $e\n" if $e =~ /^\t[^\.]/
+               #    && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
+               die "Epilogue junk?: $e\n" if $e =~ /^\t[^\.\n]/
                    && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
 
                # glue together what's left
@@ -747,7 +769,7 @@ sub mangle_asm {
        # toss the register-windowing save/restore/ret* instructions
        # directly:
        if ( $TargetPlatform =~ /^sparc-/ ) {
-           $c =~ s/^\t(save .*|restore|ret|retl)\n//g;
+           $c =~ s/^\t(save.*|restore|ret|retl)\n//g;
            # throw away PROLOGUE comments
            $c =~ s/^\t!#PROLOGUE# 0\n\t!#PROLOGUE# 1\n//;
        }
@@ -782,7 +804,28 @@ sub mangle_asm {
                                                           # (this SEGVs perl4 on alphas, you see)
 
            $to_move = $1;
-           if ( $i < ($numchks - 1)
+
+           # on x86 we try not to copy any directives into a literal
+           # chunk, rather we keep looking for the next real chunk.  This
+           # is because we get things like
+           #
+           #    .globl blah_closure
+           #    .LC32
+           #           .string "..."
+           #    blah_closure:
+           #           ...
+            #
+           if ( $TargetPlatform =~ /^i386/ && $to_move =~ /$TCOPYDIRVS/ ) {
+               $j = $i + 1;
+               while ( $j < $numchks  && $chk[$j] =~ /$T_CONST_LBL/) {
+                       $j++;
+               }
+               if ( $j < $numchks ) {
+                       $chk[$j] = $to_move . $chk[$j];
+               }
+           }
+
+           elsif ( $i < ($numchks - 1)
              && ( $to_move =~ /$TCOPYDIRVS/
                || ($TargetPlatform =~ /^hppa/ && $to_move =~ /align/ && $chkcat[$i+1] eq 'literal') )) {
                $chk[$i + 1] = $to_move . $chk[$i + 1];
@@ -888,7 +931,7 @@ sub mangle_asm {
                 };
                &print_doctored($chk[$i], 0);
                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/ && $printDS) { 
-#ok                   if ($chksymb[$i] !~ /\_regMain/) {
+#ok                   if ($chksymb[$i] !~ /\__init_Main/) {
                     print OUTASM "\.csect ${chksymb[$i]}[DS]\n";       
                     print OUTASM "${p}TOC[tc0], 0\n";
 #ok                   }
@@ -947,6 +990,7 @@ sub mangle_asm {
            print OUTASM "___stg_split_marker",$chksymb[$i],"${T_POST_LBL}\n";
 
        } elsif ( $chkcat[$i] eq 'closure'
+              || $chkcat[$i] eq 'srt'
               || $chkcat[$i] eq 'infotbl'
               || $chkcat[$i] eq 'slow'
               || $chkcat[$i] eq 'fast' ) { # do them in that order
@@ -959,6 +1003,13 @@ sub mangle_asm {
                $chkcat[$closurechk{$symb}] = 'DONE ALREADY';
            }
 
+           # SRT
+           if ( defined($srtchk{$symb}) ) {
+               print OUTASM $T_HDR_srt;
+               print OUTASM $chk[$srtchk{$symb}];
+               $chkcat[$srtchk{$symb}] = 'DONE ALREADY';
+           }
+
            # INFO TABLE
            if ( defined($infochk{$symb}) ) {
 
@@ -971,21 +1022,12 @@ sub mangle_asm {
                   }
                   $chk[$infochk{$symb}] =~ s/\.long ([_A-Za-z]\S+_entry)/\.long \.\1/;
                   $chk[$infochk{$symb}] =~ s/\.long ([A-Za-z]\S+_upd)/\.long \.\1/;
-                  $chk[$infochk{$symb}] =~ s/\.long (IndUpdRet\S+)/\.long \.\1/;
-                  $chk[$infochk{$symb}] =~ s/\.long StdErrorCode/\.long \.StdErrorCode/;
-                  $chk[$infochk{$symb}] =~ s/\.long UpdErr/\.long \.UpdErr/;
                   print OUTASM $chk[$infochk{$symb}];
                 } else {
-               print OUTASM &rev_tbl($symb, $chk[$infochk{$symb}], 1);
+                 print OUTASM &rev_tbl($symb, $chk[$infochk{$symb}], 1);
                 }
                # entry code will be put here!
 
-               # paranoia
-               if ( $chk[$infochk{$symb}] =~ /$TDOTWORD[@]?\s+([A-Za-z0-9_]+_entry)$/o
-                 && $1 ne "${T_US}${symb}_entry" ) {
-                   print STDERR "!!! entry point???\n",$chk[$infochk{$symb}];
-               }
-
                $chkcat[$infochk{$symb}] = 'DONE ALREADY';
            }
 
@@ -996,12 +1038,12 @@ sub mangle_asm {
                $c = $chk[$slowchk{$symb}];
 
                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
-               ($p, $r) = split(/TOC\[tc0\], 0\n/, $c); 
-                if ($symb =~ /^[_A-Z]/)
-               { 
-                 print OUTASM "\t\.globl \.${chksymb[$i]}_entry\n"; 
-                 print OUTASM "\.csect ${symb}_entry[DS]\n";   
-                 print OUTASM "${p}TOC[tc0], 0\n";
+                 ($p, $r) = split(/TOC\[tc0\], 0\n/, $c); 
+                  if ($symb =~ /^[_A-Z]/)
+                 { 
+                   print OUTASM "\t\.globl \.${chksymb[$i]}_entry\n"; 
+                   print OUTASM "\.csect ${symb}_entry[DS]\n";         
+                   print OUTASM "${p}TOC[tc0], 0\n";
                   }; 
                   $r =~ s/\.csect \.text\[PR\]\n//; # todo: properly - andre
                   $c = &mangle_powerpc_tailjump($r);
@@ -1015,12 +1057,12 @@ sub mangle_asm {
                    } elsif ( $TargetPlatform =~ /^i386-/ ) {
                        # Reg alloc depending, gcc generated code may jump to the fast entry point via
                        # a number of registers.
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%edx\n\tjmp \*\%edx\n//;
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%ecx\n\tjmp \*\%ecx\n//;
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%eax\n\tjmp \*\%eax\n//;
+                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%edx\n\tjmp \*\%edx\n//;
+                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%ecx\n\tjmp \*\%ecx\n//;
+                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%eax\n\tjmp \*\%eax\n//;
                        # The next two only apply if we're not stealing %esi or %edi.
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%esi\n\tjmp \*\%esi\n// if ($StolenX86Regs < 3);
-                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%edi\n\tjmp \*\%edi\n// if ($StolenX86Regs < 4);
+                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%esi\n\tjmp \*\%esi\n// if ($StolenX86Regs < 3);
+                       $c =~ s/^\tmovl \$${T_US}${symb}_fast\d*,\%edi\n\tjmp \*\%edi\n// if ($StolenX86Regs < 4);
                    } elsif ( $TargetPlatform =~ /^mips-/ ) {
                        $c =~ s/^\tjmp \$31,\(\$27\),0\n\t\.align 4\n\t\.end/\t.align 4\n\t.end/;
                    } elsif ( $TargetPlatform =~ /^m68k-/ ) {
@@ -1029,8 +1071,8 @@ sub mangle_asm {
                    } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ ) {
                        $c =~ s/^\tb \.${T_US}${symb}_fast\d+\n//;
                    } elsif ( $TargetPlatform =~ /^sparc-/ ) {
-                       $c =~ s/^\tcall ${T_US}${symb}_fast\d+,.*\n\tnop\n//;
-                       $c =~ s/^\tcall ${T_US}${symb}_fast\d+,.*\n(\t[a-z].*\n)/$1/;
+                       $c =~ s/^\tcall\s+${T_US}${symb}_fast\d+,.*\n\t\s*nop\n//;
+                       $c =~ s/^\tcall\s+${T_US}${symb}_fast\d+,.*\n(\t\s*[a-z].*\n)/$1/;
                    } else {
                        print STDERR "$Pgm: mystery slow-fast dropthrough: $TargetPlatform\n";
                    }
@@ -1086,31 +1128,17 @@ sub mangle_asm {
                print OUTASM $T_HDR_vector;
                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
                   if ( $symb =~ /^[A-Z]/) {
-                     print OUTASM "\t\.globl \.vtbl_${symb}\n";
-                    print OUTASM "\t\.globl vtbl_${symb}\n";
+                     print OUTASM "\t\.globl \.${symb}_vtbl\n";
+                    print OUTASM "\t\.globl ${symb}_vtbl\n";
                   };
                  $chk[$vectorchk{$symb}] =~ s/\.long (\S+)/\.long \.\1/g;
-                 print OUTASM ".vtbl_${symb}:\n";
+                 print OUTASM ".${symb}_vtbl:\n";
                  print OUTASM $chk[$vectorchk{$symb}];
                } else {
                  print OUTASM &rev_tbl($symb, $chk[$vectorchk{$symb}], 0);
                }
                # direct return code will be put here!
                $chkcat[$vectorchk{$symb}] = 'DONE ALREADY';
-           }
-
-           # DIRECT RETURN
-           if ( defined($directchk{$symb}) ) {
-               print OUTASM $T_HDR_direct;
-                if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
-                 ($p, $r) = split(/TOC\[tc0\], 0\n/, $chk[$directchk{$symb}]); 
-                 &print_doctored($r, 0);
-                 print OUTASM "\.csect ${symb}DirectReturn[DS]\n";     
-                 print OUTASM "${p}TOC[tc0], 0\n";
-                } else {
-                 &print_doctored($chk[$directchk{$symb}], 0);
-               }
-               $chkcat[$directchk{$symb}] = 'DONE ALREADY';
 
            } elsif ( $TargetPlatform =~ /^alpha-/ ) {
                # Alphas: the commented nop is for the splitter, to ensure
@@ -1183,7 +1211,8 @@ sub print_doctored {
     local($_, $need_fallthru_patch) = @_;
 
     if ( $TargetPlatform !~ /^i386-/ 
-      || ! /^\t[a-z]/ ) { # no instructions in here, apparently
+      || ! /^\t[a-z]/  # no instructions in here, apparently
+      || /^${T_US}__init_[A-Za-z0-9_]+${T_POST_LBL}/) {
        print OUTASM $_;
        return;
     }
@@ -1191,36 +1220,6 @@ sub print_doctored {
 
     local($entry_patch)        = '';
     local($exit_patch) = '';
-    local($call_entry_patch)= '';
-    local($call_exit_patch)    = '';
-    local($gc_call_entry_patch)= '';   # Patches before and after calls to Perform_GC_wrapper
-    local($gc_call_exit_patch) = '';
-
-#OLD:  # first, convert calls to *very magic form*: (ToDo: document
-    # for real!)  from
-    #
-    #  pushl $768
-    #  call _?PerformGC_wrapper
-    #  addl $4,%esp
-    # to
-    #  movl $768, %eax
-    #  call _?PerformGC_wrapper
-    #
-    # The reason we do this now is to remove the apparent use of
-    # %esp, which would throw off the "what patch code do we need"
-    # decision.
-    #
-    # Special macros in ghc/includes/COptWraps.lh, used in
-    # ghc/runtime/CallWrap_C.lc, are required for this to work!
-    #
-
-    s/^\tpushl \$(\d+)\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tmovl \$$1,\%eax\n\tcall ${T_DO_GC}\n/go;
-    s/^\tpushl \%eax\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tcall ${T_DO_GC}\n/go;
-    s/^\tpushl \%edx\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tmovl \%edx,\%eax\n\tcall ${T_DO_GC}\n/go;
-
-#=  if ( $StolenX86Regs <= 4 ) { # %ecx is ordinary reg
-#=     s/^\tpushl \%ecx\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tmovl \%ecx,\%eax\n\tcall ${T_DO_GC}\n/go;
-#=  }
 
     # gotta watch out for weird instructions that
     # invisibly smash various regs:
@@ -1255,10 +1254,13 @@ sub print_doctored {
     #   movl $_blah,<bad-reg>
     #   jmp  *<bad-reg>
     #
-    # which is easily fixed as:
-    #
-    # sigh! try to hack around it...
-    #
+
+# the short form may tickle perl bug:
+#    s/^\tmovl \$${T_US}(.*),(\%e[abcd]x)\n\tjmp \*$2/\tjmp $T_US$1/g;
+    s/^\tmovl \$${T_US}(.*),\%eax\n\tjmp \*\%eax/\tjmp $T_US$1/g;
+    s/^\tmovl \$${T_US}(.*),\%ebx\n\tjmp \*\%ebx/\tjmp $T_US$1/g;
+    s/^\tmovl \$${T_US}(.*),\%ecx\n\tjmp \*\%ecx/\tjmp $T_US$1/g;
+    s/^\tmovl \$${T_US}(.*),\%edx\n\tjmp \*\%edx/\tjmp $T_US$1/g;
 
     if ($StolenX86Regs <= 2 ) { # YURGH! spurious uses of esi?
        s/^\tmovl (.*),\%esi\n\tjmp \*%esi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
@@ -1269,74 +1271,43 @@ sub print_doctored {
     }
     if ($StolenX86Regs <= 3 ) { # spurious uses of edi?
        s/^\tmovl (.*),\%edi\n\tjmp \*%edi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
-       s/^\tjmp \*(-?\d*)\((.*\%edi.*)\)\n/\tmovl $2,\%eax\n\tjmp \*$1\(\%eax\)\n/g;
+       s/^\tjmp \*(-?\d*\(.*\%edi.*\))\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
        s/^\tjmp \*\%edi\n/\tmovl \%edi,\%eax\n\tjmp \*\%eax\n/g;
        die "$Pgm: (mangler) still have jump involving \%edi!\n$_"
            if /(jmp|call) .*\%edi/;
     }
-#=  if ($StolenX86Regs <= 4 ) { # spurious uses of ecx?
-#=     s/^\tmovl (.*),\%ecx\n\tjmp \*%ecx\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
-#=     s/^\tjmp \*(-?\d*)\((.*\%ecx.*)\)\n/\tmovl $2,\%eax\n\tjmp \*$1\(\%eax\)\n/g;
-#=     s/^\tjmp \*\%ecx\n/\tmovl \%ecx,\%eax\n\tjmp \*\%eax\n/g;
-#=     die "$Pgm: (mangler) still have jump involving \%ecx!\n$_"
-#=         if /(jmp|call) .*\%ecx/;
-#=  }
 
     # OK, now we can decide what our patch-up code is going to
     # be:
 
     # Offsets into register table - you'd better update these magic
     # numbers should you change its contents!
-    local($OFFSET_R1)=48;
-    local($OFFSET_SpA)=80;
+    # local($OFFSET_R1)=0;  No offset for R1 in new RTS.
+    local($OFFSET_Hp)=92;
 
        # Note funky ".=" stuff; we're *adding* to these _patch guys
     if ( $StolenX86Regs <= 2
-        && ( /${OFFSET_R1}\(\%ebx\)/ || /\%esi/ || /^\tcmps/ ) ) { # R1 (esi)
-       $entry_patch .= "\tmovl \%esi,${OFFSET_R1}(\%ebx)\n";
-       $exit_patch  .= "\tmovl ${OFFSET_R1}(\%ebx),\%esi\n";
-
-       $gc_call_entry_patch  .= "\tmovl \%esi,${OFFSET_R1}(\%ebx)\n";
-       $gc_call_exit_patch .= "\tmovl ${OFFSET_R1}(\%ebx),\%esi\n";
+        && ( /[^0-9]\(\%ebx\)/ || /\%esi/ || /^\tcmps/ ) ) { # R1 (esi)
+       $entry_patch .= "\tmovl \%esi,(\%ebx)\n";
+       $exit_patch  .= "\tmovl (\%ebx),\%esi\n";
 
        # nothing for call_{entry,exit} because %esi is callee-save
     }
     if ( $StolenX86Regs <= 3
-        && ( /${OFFSET_SpA}\(\%ebx\)/ || /\%edi/ || /^\t(scas|cmps)/ ) ) { # SpA (edi)
-       $entry_patch .= "\tmovl \%edi,${OFFSET_SpA}(\%ebx)\n";
-       $exit_patch  .= "\tmovl ${OFFSET_SpA}(\%ebx),\%edi\n";
-
-       $gc_call_entry_patch  .= "\tmovl \%edi,${OFFSET_SpA}(\%ebx)\n";
-       $gc_call_exit_patch .= "\tmovl ${OFFSET_SpA}(\%ebx),\%edi\n";
+        && ( /${OFFSET_Hp}\(\%ebx\)/ || /\%edi/ || /^\t(scas|cmps)/ ) ) { # Hp (edi)
+       $entry_patch .= "\tmovl \%edi,${OFFSET_Hp}(\%ebx)\n";
+       $exit_patch  .= "\tmovl ${OFFSET_Hp}(\%ebx),\%edi\n";
 
        # nothing for call_{entry,exit} because %edi is callee-save
     }
-    local ($OFFSET_Hp) = 96;
-
-#=  local ($OFFSET_rSaveECX) = 124;
-#=  if ( $StolenX86Regs <= 4
-#=      && ( /${OFFSET_Hp}\(\%ebx\)/ || /\%ecx/ || /^\t(rep|loop)/ ) ) { # Hp (ecx)
-#=     $entry_patch .= "\tmovl \%ecx,${OFFSET_Hp}(\%ebx)\n";
-#=     $exit_patch  .= "\tmovl ${OFFSET_Hp}(\%ebx),\%ecx\n";
-#=
-#=     $call_exit_patch  .= "\tmovl \%ecx,${OFFSET_rSaveECX}(\%ebx)\n";
-#=     $call_entry_patch .= "\tmovl ${OFFSET_rSaveECX}(\%ebx),\%ecx\n";
-#=     # I have a really bad feeling about this if we ever
-#=     # have a nested call...
-#=     # NB: should just hide it somewhere in the C stack.
-#=  }
+
     # --------------------------------------------------------
     # next, here we go with non-%esp patching!
     #
     s/^(\t[a-z])/$entry_patch$1/; # before first instruction
 
-# Actually, call_entry_patch and call_exit_patch never get set,
-# so let's nuke this one
-#    s/^(\tcall .*\n(\taddl \$\d+,\%esp\n)?)/$call_exit_patch$1$call_entry_patch/g; # _all_ calls
-
 # Before calling GC we must set up the exit condition before the call
 # and entry condition when we come back
-    s/^(\tcall ${T_DO_GC}\n(\taddl \$\d+,\%esp\n)?)/$gc_call_exit_patch$1$gc_call_entry_patch/g; # _all_ calls
 
     # fix _all_ non-local jumps:
 
@@ -1348,49 +1319,14 @@ sub print_doctored {
     s/^\tJMP___SL/\tjmp \*${T_X86_PRE_LLBL}/go;
     s/^\tJMP___L/\tjmp ${T_X86_PRE_LLBL}/go;
 
-    # fix post-PerformGC wrapper (re-)entries ???
-
     if ($StolenX86Regs == 2 ) {
        die "ARGH! Jump uses \%esi or \%edi with -monly-2-regs:\n$_" 
            if /^\t(jmp|call) .*\%e(si|di)/;
-#=     die "ARGH! Jump uses \%esi, \%edi, or \%ecx with -monly-2-regs:\n$_" 
-#=         if /^\t(jmp|call) .*\%e(si|di|cx)/;
     } elsif ($StolenX86Regs == 3 ) {
        die "ARGH! Jump uses \%edi with -monly-3-regs:\n$_" 
            if /^\t(jmp|call) .*\%edi/;
-#=     die "ARGH! Jump uses \%edi or \%ecx with -monly-3-regs:\n$_" 
-#=         if /^\t(jmp|call) .*\%e(di|cx)/;
-#=  } elsif ($StolenX86Regs == 4 ) {
-#=     die "ARGH! Jump uses \%ecx with -monly-4-regs:\n$_" 
-#=         if /^\t(jmp|call) .*\%ecx/;
     }
 
-    # final peephole fixes
-
-    local($OFFSET_R2)=52;
-    s/^\tmovl \%eax,${OFFSET_R2}\(\%ebx\)\n\tjmp \*${OFFSET_R2}\(\%ebx\)\n/\tmovl \%eax,${OFFSET_R2}\(\%ebx\)\n\tjmp \*\%eax\n/;
-
-# the short form may tickle perl bug:
-#    s/^\tmovl \$${T_US}(.*),(\%e[abcd]x)\n\tjmp \*$2/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%eax\n\tjmp \*\%eax/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%ebx\n\tjmp \*\%ebx/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%ecx\n\tjmp \*\%ecx/\tjmp $T_US$1/g;
-    s/^\tmovl \$${T_US}(.*),\%edx\n\tjmp \*\%edx/\tjmp $T_US$1/g;
-
-    # Hacks to eliminate some reloads of Hp.  Worth about 5% code size.
-    # We could do much better than this, but at least it catches about
-    # half of the unnecessary reloads.
-    # Note that these will stop working if either:
-    #  (i) the offset of Hp from BaseReg changes from 80, or
-    #  (ii) the register assignment of BaseReg changes from %ebx
-
-    s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%e.x\n\tmovl \$(.*),(-?[0-9]*)\(\%e.x\)\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%e(.)x/\tmovl ${OFFSET_Hp}\(\%ebx\),\%e$3x\n\tmovl \$$1,$2\(\%e$3x\)/g;
-
-    s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%e(.)x\n\tmovl (.*),\%e(.)x\n\tmovl \%e$3x,(-?[0-9]*\(\%e$1x\))\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%e$1x/\tmovl ${OFFSET_Hp}\(\%ebx\),\%e$1x\n\tmovl $2,\%e$3x\n\tmovl \%e$3x,$4/g;
-
-    s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%edx((\n\t(movl|addl) .*,((-?[0-9]*\(.*)|(\%e[abc]x)))+)\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%edx/\tmovl ${OFFSET_Hp}\(\%ebx\),\%edx$1/g;
-    s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%eax((\n\t(movl|addl) .*,((-?[0-9]*\(.*)|(\%e[bcd]x)))+)\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%eax/\tmovl ${OFFSET_Hp}\(\%ebx\),\%eax$1/g;
-
     # --------------------------------------------------------
     # that's it -- print it
     #
@@ -1408,54 +1344,8 @@ sub print_doctored {
 \begin{code}
 sub init_FUNNY_THINGS {
     %KNOWN_FUNNY_THING = (
-       "${T_US}CheckHeapCode${T_POST_LBL}", 1,
-       "${T_US}CommonUnderflow${T_POST_LBL}", 1,
-       "${T_US}Continue${T_POST_LBL}", 1,
-       "${T_US}EnterNodeCode${T_POST_LBL}", 1,
-       "${T_US}ErrorIO_call_count${T_POST_LBL}", 1,
-       "${T_US}ErrorIO_innards${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetDir${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV0${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV1${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV2${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV3${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV4${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV5${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV6${T_POST_LBL}", 1,
-       "${T_US}IndUpdRetV7${T_POST_LBL}", 1,
-       "${T_US}PrimUnderflow${T_POST_LBL}", 1,
-       "${T_US}StackUnderflowEnterNode${T_POST_LBL}", 1,
-       "${T_US}StdErrorCode${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect0${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect1${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect2${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect3${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect4${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect5${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect6${T_POST_LBL}", 1,
-       "${T_US}UnderflowVect7${T_POST_LBL}", 1,
-       "${T_US}UpdErr${T_POST_LBL}", 1,
-       "${T_US}UpdatePAP${T_POST_LBL}", 1,
-       "${T_US}_Enter_Internal${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextAStack${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextBStack${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextCAF${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextGA${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextRoot${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextSpark${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextEvent${T_POST_LBL}", 1,
-       "${T_US}_PRMarking_MarkNextClosureInFetchBuffer${T_POST_LBL}", 1,
-       "${T_US}_Scavenge_Forward_Ref${T_POST_LBL}", 1,
-       "${T_US}__std_entry_error__${T_POST_LBL}", 1,
-       "${T_US}_startMarkWorld${T_POST_LBL}", 1,
-       "${T_US}resumeThread${T_POST_LBL}", 1,
-       "${T_US}startCcRegisteringWorld${T_POST_LBL}", 1,
-       "${T_US}startEnterFloat${T_POST_LBL}", 1,
-       "${T_US}startEnterInt${T_POST_LBL}", 1,
-       "${T_US}startPerformIO${T_POST_LBL}", 1,
-       "${T_US}startStgWorld${T_POST_LBL}", 1,
-       "${T_US}stopPerformIO${T_POST_LBL}", 1,
-        "${T_US}ShouldCompile_Z36d1z5${T_POST_LBL}", 1
+       # example
+       # "${T_US}stg_.*{T_POST_LBL}", 1,  
     );
 }
 \end{code}
@@ -1477,28 +1367,30 @@ sub rev_tbl {
     local($after) = '';
     local(@lines) = split(/\n/, $tbl);
     local($i, $j); #local ($i, $extra, $words_to_pad, $j);
-   
+
     # see comment in mangleAsm as to why this silliness is needed.
     local($TDOTWORD) = ${T_DOT_WORD};
     local($TDOTGLOBAL) = ${T_DOT_GLOBAL};
     local($TUS) = ${T_US};
     local($TPOSTLBL) = ${T_POST_LBL};
 
-    for ($i = 0; $i <= $#lines && $lines[$i] !~ /^\t$TDOTWORD\s+/o; $i++) {
+    # Deal with the header...
+    for ($i = 0; $i <= $#lines && $lines[$i] !~ /^\t?$TDOTWORD\s+/o; $i++) {
        $label .= $lines[$i] . "\n",
            next if $lines[$i] =~ /^[A-Za-z0-9_]+_info$TPOSTLBL[@]?$/o
                 || $lines[$i] =~ /$TDOTGLOBAL/o
-                || $lines[$i] =~ /^$TUS[@]?vtbl_\S+$TPOSTLBL[@]?$/o;
+                || $lines[$i] =~ /^$TUS[@]?\S+_vtbl$TPOSTLBL[@]?$/o;
 
        $before .= $lines[$i] . "\n"; # otherwise...
     }
 
+    # Grab the table data...
     if ( $TargetPlatform !~ /^hppa/ ) {
-       for ( ; $i <= $#lines && $lines[$i] =~ /^\t$TDOTWORD\s+/o; $i++) {
+       for ( ; $i <= $#lines && $lines[$i] =~ /^\t?$TDOTWORD\s+/o; $i++) {
            push(@words, $lines[$i]);
        }
     } else { # hppa weirdness
-       for ( ; $i <= $#lines && $lines[$i] =~ /^\s+\.(word|IMPORT)/; $i++) {
+       for ( ; $i <= $#lines && $lines[$i] =~ /^\s+($TDOTWORD|\.IMPORT)/; $i++) {
            if ($lines[$i] =~ /^\s+\.IMPORT/) {
                push(@imports, $lines[$i]);
            } else {
@@ -1510,8 +1402,13 @@ sub rev_tbl {
        }
     }
 
-    # now throw away the first word (entry code):
-    shift(@words) if $discard1;
+    # now throw away the first word (SRT) iff it is empty.
+    # The .zero business is for Linux/ELF.
+    # The .skip business is for Sparc/Solaris/ELF.
+    # The .blockz business is for HPPA.
+    if ($discard1 && $words[0] =~ /^\t?($TDOTWORD\s+0|\.zero\s+4|\.skip\s+4|\.blockz\s+4)/) {
+       shift(@words)
+    }
 
 # Padding removed to reduce code size and improve performance on Pentiums.
 # Simon M. 13/4/96
@@ -1534,7 +1431,7 @@ sub rev_tbl {
 
     $tbl = $before
         . (($TargetPlatform !~ /^hppa/) ? '' : join("\n", @imports) . "\n")
-        . join("\n", (reverse @words)) . "\n"
+        . join("\n", @words) . "\n"
         . $label . $after;
 
 #   print STDERR "before=$before\n";
@@ -1546,36 +1443,6 @@ sub rev_tbl {
 }
 \end{code}
 
-\begin{code}
-sub mini_mangle_asm_i386 {
-    local($in_asmf, $out_asmf) = @_;
-
-    &init_TARGET_STUFF();
-
-    # see mangleAsm comment
-    local($TUS) = ${T_US};
-    local($TPOSTLBL)=${T_POST_LBL};
-
-    open(INASM, "< $in_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
-    open(OUTASM,"> $out_asmf")
-       || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
-
-    while (<INASM>) {
-       print OUTASM;
-
-        next unless
-           /^$TUS[@]?(PerformGC|StackOverflow|Yield|PerformReschedule)_wrapper$TPOSTLBL\n/o;
-       print OUTASM "\tmovl \%esp, ${T_US}__temp_esp\n";
-       print OUTASM "\tmovl \%eax, ${T_US}__temp_eax\n";
-    }
-
-    # finished:
-    close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
-    close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
-}
-\end{code}
-
 The HP is a major nuisance.  The threaded code mangler moved info
 tables from data space to code space, but unthreaded code in the RTS
 still has references to info tables in data space.  Since the HP
@@ -1650,7 +1517,12 @@ sub mangle_powerpc_tailjump {
       };
     $c;
 }
+\end{code}
 
-# make "require"r happy...
-1;
+\begin{code}
+sub tidy_up_and_die {
+    local($return_val, $msg) = @_;
+    print STDERR $msg;
+    exit (($return_val == 0) ? 0 : 1);
+}
 \end{code}
diff --git a/ghc/driver/prefix.txt b/ghc/driver/prefix.txt
deleted file mode 100644 (file)
index a63e8c9..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# This is the driver script for the Glasgow Haskell Compiler!
-#
-# To configure this script to run on your system, you have
-# to set the following three variables (if they have not already
-# been set above):
-#
-#$bindir='/usr/local/bin'; 
-#   -- where you have installed the binaries
-#$libdir='/local/fp/lib/sparc-sun-sunos4/ghc-2.02'; 
-#   -- where you have installed the prelude libraries for this release.
-#$datadir='/local/fp/share0/ghc-2.02';
-#   -- where you have installed the arch-independent miscellania (if any).
-#
-# We sincerly apologise for the gumpf that follows, please look away.
-#
diff --git a/ghc/driver/split/Makefile b/ghc/driver/split/Makefile
new file mode 100644 (file)
index 0000000..f7019be
--- /dev/null
@@ -0,0 +1,16 @@
+#-----------------------------------------------------------------------------
+# $Id: Makefile,v 1.1 2000/06/13 16:07:20 simonmar Exp $
+
+TOP=../..
+include $(TOP)/mk/boilerplate.mk
+
+SCRIPT_PROG    = ghc-split
+SCRIPT_OBJS     = ghc-split.prl
+
+INTERP=perl
+
+SCRIPT_SUBST_VARS := TARGETPLATFORM
+
+INSTALL_LIBEXEC_SCRIPTS += $(SCRIPT_PROG)
+
+include $(TOP)/mk/target.mk
index 5e4d0bc..7d0fa6e 100644 (file)
@@ -5,6 +5,24 @@
 %************************************************************************
 
 \begin{code}
+$TargetPlatform = $TARGETPLATFORM;
+
+($Pgm = $0) =~ s|.*/||;
+$ifile      = $ARGV[0];
+$Tmp_prefix = $ARGV[1];
+$Output     = $ARGV[2];
+
+&split_asm_file($ifile);
+
+open(OUTPUT, "> $Output") ||  &tidy_up_and_die(1,"$Pgm: failed to open `$Output' (to write)\n");
+print OUTPUT "$NoOfSplitFiles\n";
+close(OUTPUT);
+
+exit(0);
+\end{code}
+
+
+\begin{code}
 sub split_asm_file {
     local($asm_file) = @_;
 
@@ -430,7 +448,9 @@ sub process_asm_block_powerpc {
 \end{code}
 
 \begin{code}
-# make "require"r happy...
-1;
+sub tidy_up_and_die {
+    local($return_val, $msg) = @_;
+    print STDERR $msg;
+    exit (($return_val == 0) ? 0 : 1);
+}
 \end{code}
-
diff --git a/ghc/driver/stats/Makefile b/ghc/driver/stats/Makefile
new file mode 100644 (file)
index 0000000..75f3aa2
--- /dev/null
@@ -0,0 +1,16 @@
+#-----------------------------------------------------------------------------
+# $Id: Makefile,v 1.1 2000/06/13 16:07:21 simonmar Exp $
+
+TOP=../..
+include $(TOP)/mk/boilerplate.mk
+
+SCRIPT_PROG    = ghc-stats
+SCRIPT_OBJS     = ghc-stats.prl
+
+INTERP=perl
+
+SCRIPT_SUBST_VARS := TARGETPLATFORM
+
+INSTALL_LIBEXEC_SCRIPTS += $(SCRIPT_PROG)
+
+include $(TOP)/mk/target.mk
diff --git a/ghc/driver/stats/ghc-stats.lprl b/ghc/driver/stats/ghc-stats.lprl
new file mode 100644 (file)
index 0000000..fed6f94
--- /dev/null
@@ -0,0 +1,85 @@
+%************************************************************************
+%*                                                                     *
+\section[Driver-stats]{Collecting garbage collection statistics for a ghc run}
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
+$StatsFile = $ARGV[0];
+&process_ghc_timings();
+
+sub process_ghc_timings {
+    local($SysSpecificTiming) = 'ghc';
+
+    open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
+    local($max_live)    = 0; 
+    local($tot_live)    = 0; # for calculating residency stuff
+    local($tot_samples) = 0;
+
+    while (<STATS>) {
+       if (! /Gen:\s+0/ && ! /Minor/ && /^\s*\d+\s+\d+\s+(\d+)\s+\d+\.\d+/ ) {
+               $max_live = $1 if $max_live < $1;
+               $tot_live += $1;
+               $tot_samples += 1;
+       }
+        $BytesAlloc = $1 if /^\s*([0-9,]+) bytes allocated in the heap/;
+
+       if ( /^\s*([0-9,]+) bytes maximum residency .* (\d+) sample/ ) {
+           $MaxResidency = $1; $ResidencySamples = $2;
+       }
+
+        $GCs = $1 if /^\s*([0-9,]+) (collections? in generation 0|garbage collections? performed)/;
+
+       if ( /^\s+([0-9]+)\s+Mb total memory/ ) {
+           $TotMem = $1;
+        }
+
+       # The presence of -? in the following pattern is only there to
+       # accommodate 0.29 && <= 2.05 RTS'
+       if ( /^\s*INIT\s+time\s*(\d+\.\d\d)s\s*\(\s*-?(\d+\.\d\d)s elapsed\)/ ) {
+           $InitTime = $1; $InitElapsed = $2;
+       } elsif ( /^\s*MUT\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
+           $MutTime = $1; $MutElapsed = $2;
+       } elsif ( /^\s*GC\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
+           $GcTime = $1; $GcElapsed = $2;
+       }
+    }
+    close(STATS) || die "Failed when closing $StatsFile\n";
+    if ( $tot_samples > 0 ) {
+       $ResidencySamples = $tot_samples;
+       $MaxResidency = $max_live;
+       $AvgResidency = int ($tot_live / $tot_samples) ;
+    }
+
+    # warn about what we didn't find
+    print STDERR "Warning: BytesAlloc not found in stats file\n" unless defined($BytesAlloc);
+    print STDERR "Warning: GCs not found in stats file\n" unless defined($GCs);
+    print STDERR "Warning: InitTime not found in stats file\n" unless defined($InitTime);
+    print STDERR "Warning: InitElapsed not found in stats file\n" unless defined($InitElapsed);
+    print STDERR "Warning: MutTime not found in stats file\n" unless defined($MutTime);
+    print STDERR "Warning: MutElapsed not found in stats file\n" unless defined($MutElapsed);
+    print STDERR "Warning: GcTime inot found in stats file\n" unless defined($GcTime);
+    print STDERR "Warning: GcElapsed not found in stats file\n" unless defined($GcElapsed);
+
+    # things we didn't necessarily expect to find
+    $MaxResidency     = 0 unless defined($MaxResidency);
+    $AvgResidency     = 0 unless defined($AvgResidency);
+    $ResidencySamples = 0 unless defined($ResidencySamples);
+
+    # a bit of tidying
+    $BytesAlloc =~ s/,//g;
+    $MaxResidency =~ s/,//g;
+    $GCs =~ s/,//g;
+    $InitTime =~ s/,//g;
+    $InitElapsed =~ s/,//g;
+    $MutTime =~ s/,//g;
+    $MutElapsed =~ s/,//g;
+    $GcTime =~ s/,//g;
+    $GcElapsed =~ s/,//g;
+
+    # print out what we found
+    print STDERR "<<$SysSpecificTiming: ",
+       "$BytesAlloc bytes, $GCs GCs, $AvgResidency/$MaxResidency avg/max bytes residency ($ResidencySamples samples), ${TotMem}M in use, $InitTime INIT ($InitElapsed elapsed), $MutTime MUT ($MutElapsed elapsed), $GcTime GC ($GcElapsed elapsed)",
+       " :$SysSpecificTiming>>\n";
+}
+\end{code}
index 1adeefc..ae1d1f5 100644 (file)
@@ -1,5 +1,5 @@
 # -----------------------------------------------------------------------------
-# $Id: paths.mk,v 1.19 2000/01/14 10:18:37 simonmar Exp $
+# $Id: paths.mk,v 1.20 2000/06/13 16:07:21 simonmar Exp $
 #
 # ghc project specific make variables
 #
@@ -29,6 +29,9 @@ GHC_MKDEPENDHS_DIR    := $(GHC_UTILS_DIR)/mkdependHS
 GHC_HSCPP_DIR          := $(GHC_UTILS_DIR)/hscpp
 GHC_HSC_DIR            := $(GHC_COMPILER_DIR)
 GHC_UNLIT_DIR          := $(GHC_UTILS_DIR)/unlit
+GHC_MANGLER_DIR        := $(GHC_DRIVER_DIR)/mangler
+GHC_SPLIT_DIR          := $(GHC_DRIVER_DIR)/split
+GHC_STAT_DIR            := $(GHC_DRIVER_DIR)/drv/stats
 
 GHC_INPLACE            = $(GHC_DRIVER_DIR)/ghc-inplace
 GHC_HSCPP              = $(GHC_HSCPP_DIR)/hscpp
@@ -36,6 +39,9 @@ GHC_MKDEPENDHS                = $(GHC_MKDEPENDHS_DIR)/mkdependHS-inplace
 GHC_HSC                = $(GHC_HSC_DIR)/hsc
 UNLIT                  = $(GHC_UNLIT_DIR)/unlit
 GHC_UNLIT              = $(GHC_UNLIT_DIR)/unlit
+GHC_MANGLER            = $(GHC_MANGLER_DIR)/ghc-asm
+GHC_SPLIT              = $(GHC_SPLIT_DIR)/ghc-split
+GHC_STATS              = $(GHC_STAT_DIR)/ghc-stats
 
 GHC_SYSMAN             = $(GHC_RUNTIME_DIR)/parallel/SysMan
 GHC_SYSMAN_DIR                 = $(GHC_RUNTIME_DIR)/parallel