[project @ 2001-06-14 12:50:05 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / DriverPipeline.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverPipeline.hs,v 1.78 2001/06/14 12:50:06 simonpj Exp $
3 --
4 -- GHC Driver
5 --
6 -- (c) Simon Marlow 2000
7 --
8 -----------------------------------------------------------------------------
9
10 #include "../includes/config.h"
11
12 module DriverPipeline (
13
14         -- interfaces for the batch-mode driver
15    GhcMode(..), getGhcMode, v_GhcMode,
16    genPipeline, runPipeline, pipeLoop,
17
18         -- interfaces for the compilation manager (interpreted/batch-mode)
19    preprocess, compile, CompResult(..),
20
21         -- batch-mode linking interface
22    doLink,
23         -- DLL building
24    doMkDLL
25   ) where
26
27 #include "HsVersions.h"
28
29 import CmStaticInfo
30 import CmTypes
31 import GetImports
32 import DriverState
33 import DriverUtil
34 import DriverMkDepend
35 import DriverPhases
36 import DriverFlags
37 import SysTools         ( newTempName, addFilesToClean, getSysMan )
38 import qualified SysTools       
39 import HscMain
40 import Finder
41 import HscTypes
42 import Outputable
43 import Module
44 import ErrUtils
45 import CmdLineOpts
46 import Config
47 import Panic
48 import Util
49
50 import Time             ( getClockTime )
51 import Directory
52 import System
53 import IOExts
54 import Exception
55
56 import IO
57 import Monad
58 import Maybe
59
60 import PackedString
61 import MatchPS
62
63 -----------------------------------------------------------------------------
64 -- GHC modes of operation
65
66 data GhcMode
67   = DoMkDependHS                        -- ghc -M
68   | DoMkDLL                             -- ghc --mk-dll
69   | StopBefore Phase                    -- ghc -E | -C | -S | -c
70   | DoMake                              -- ghc --make
71   | DoInteractive                       -- ghc --interactive
72   | DoLink                              -- [ the default ]
73   deriving (Eq)
74
75 GLOBAL_VAR(v_GhcMode, error "todo", GhcMode)
76
77 modeFlag :: String -> Maybe GhcMode
78 modeFlag "-M"            = Just $ DoMkDependHS
79 modeFlag "--mk-dll"      = Just $ DoMkDLL
80 modeFlag "-E"            = Just $ StopBefore Hsc
81 modeFlag "-C"            = Just $ StopBefore HCc
82 modeFlag "-S"            = Just $ StopBefore As
83 modeFlag "-c"            = Just $ StopBefore Ln
84 modeFlag "--make"        = Just $ DoMake
85 modeFlag "--interactive" = Just $ DoInteractive
86 modeFlag _               = Nothing
87
88 getGhcMode :: [String]
89          -> IO ( [String]   -- rest of command line
90                , GhcMode
91                , String     -- "GhcMode" flag
92                )
93 getGhcMode flags 
94   = case my_partition modeFlag flags of
95         ([]   , rest) -> return (rest, DoLink,  "") -- default is to do linking
96         ([(flag,one)], rest) -> return (rest, one, flag)
97         (_    , _   ) -> 
98           throwDyn (UsageError 
99                 "only one of the flags -M, -E, -C, -S, -c, --make, --interactive, -mk-dll is allowed")
100
101 -----------------------------------------------------------------------------
102 -- genPipeline
103 --
104 -- Herein is all the magic about which phases to run in which order, whether
105 -- the intermediate files should be in TMPDIR or in the current directory,
106 -- what the suffix of the intermediate files should be, etc.
107
108 -- The following compilation pipeline algorithm is fairly hacky.  A
109 -- better way to do this would be to express the whole compilation as a
110 -- data flow DAG, where the nodes are the intermediate files and the
111 -- edges are the compilation phases.  This framework would also work
112 -- nicely if a haskell dependency generator was included in the
113 -- driver.
114
115 -- It would also deal much more cleanly with compilation phases that
116 -- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
117 -- possibly stub files), where some of the output files need to be
118 -- processed further (eg. the stub files need to be compiled by the C
119 -- compiler).
120
121 -- A cool thing to do would then be to execute the data flow graph
122 -- concurrently, automatically taking advantage of extra processors on
123 -- the host machine.  For example, when compiling two Haskell files
124 -- where one depends on the other, the data flow graph would determine
125 -- that the C compiler from the first compilation can be overlapped
126 -- with the hsc compilation for the second file.
127
128 data IntermediateFileType
129   = Temporary
130   | Persistent
131   deriving (Eq, Show)
132
133 genPipeline
134    :: GhcMode           -- when to stop
135    -> String            -- "stop after" flag (for error messages)
136    -> Bool              -- True => output is persistent
137    -> HscLang           -- preferred output language for hsc
138    -> String            -- original filename
139    -> IO [              -- list of phases to run for this file
140              (Phase,
141               IntermediateFileType,  -- keep the output from this phase?
142               String)                -- output file suffix
143          ]      
144
145 genPipeline todo stop_flag persistent_output lang filename 
146  = do
147    split      <- readIORef v_Split_object_files
148    mangle     <- readIORef v_Do_asm_mangling
149    keep_hc    <- readIORef v_Keep_hc_files
150    keep_raw_s <- readIORef v_Keep_raw_s_files
151    keep_s     <- readIORef v_Keep_s_files
152    osuf       <- readIORef v_Object_suf
153    hcsuf      <- readIORef v_HC_suf
154
155    let
156    ----------- -----  ----   ---   --   --  -  -  -
157     (_basename, suffix) = splitFilename filename
158
159     start = startPhase suffix
160
161       -- special case for mkdependHS: .hspp files go through MkDependHS
162     start_phase | todo == DoMkDependHS && start == Hsc  = MkDependHS
163                 | otherwise = start
164
165     haskellish = haskellish_suffix suffix
166     cish = cish_suffix suffix
167
168        -- for a .hc file we need to force lang to HscC
169     real_lang | start_phase == HCc || start_phase == Mangle = HscC
170               | otherwise                                   = lang
171
172    let
173    ----------- -----  ----   ---   --   --  -  -  -
174     pipeline
175       | todo == DoMkDependHS = [ Unlit, Cpp, MkDependHS ]
176
177       | haskellish = 
178        case real_lang of
179         HscC    | split && mangle -> [ Unlit, Cpp, Hsc, HCc, Mangle, 
180                                         SplitMangle, SplitAs ]
181                 | mangle          -> [ Unlit, Cpp, Hsc, HCc, Mangle, As ]
182                 | split           -> not_valid
183                 | otherwise       -> [ Unlit, Cpp, Hsc, HCc, As ]
184
185         HscAsm  | split           -> [ Unlit, Cpp, Hsc, SplitMangle, SplitAs ]
186                 | otherwise       -> [ Unlit, Cpp, Hsc, As ]
187
188         HscJava | split           -> not_valid
189                 | otherwise       -> error "not implemented: compiling via Java"
190         HscILX  | split           -> not_valid
191                 | otherwise       -> [ Unlit, Cpp, Hsc ]
192
193       | cish      = [ Cc, As ]
194
195       | otherwise = [ ]  -- just pass this file through to the linker
196
197         -- ToDo: this is somewhat cryptic
198     not_valid = throwDyn (UsageError ("invalid option combination"))
199
200     stop_phase = case todo of 
201                         StopBefore As | split -> SplitAs
202                         StopBefore phase      -> phase
203                         DoMkDependHS          -> Ln
204                         DoLink                -> Ln
205    ----------- -----  ----   ---   --   --  -  -  -
206
207         -- this shouldn't happen.
208    if start_phase /= Ln && start_phase `notElem` pipeline
209         then throwDyn (CmdLineError ("can't find starting phase for "
210                                      ++ filename))
211         else do
212
213         -- if we can't find the phase we're supposed to stop before,
214         -- something has gone wrong.  This test carefully avoids the
215         -- case where we aren't supposed to do any compilation, because the file
216         -- is already in linkable form (for example).
217    if start_phase `elem` pipeline && 
218         (stop_phase /= Ln && stop_phase `notElem` pipeline)
219       then throwDyn (UsageError 
220                 ("flag " ++ stop_flag
221                  ++ " is incompatible with source file `" ++ filename ++ "'"))
222       else do
223
224    let
225         -- .o and .hc suffixes can be overriden by command-line options:
226       myPhaseInputExt Ln  | Just s <- osuf  = s
227       myPhaseInputExt HCc | Just s <- hcsuf = s
228       myPhaseInputExt other                 = phaseInputExt other
229
230       annotatePipeline
231          :: [Phase]             -- raw pipeline
232          -> Phase               -- phase to stop before
233          -> [(Phase, IntermediateFileType, String{-file extension-})]
234       annotatePipeline []     _    = []
235       annotatePipeline (Ln:_) _    = []
236       annotatePipeline (phase:next_phase:ps) stop = 
237           (phase, keep_this_output, myPhaseInputExt next_phase)
238              : annotatePipeline (next_phase:ps) stop
239           where
240                 keep_this_output
241                      | next_phase == stop 
242                      = if persistent_output then Persistent else Temporary
243                      | otherwise
244                      = case next_phase of
245                              Ln -> Persistent
246                              Mangle | keep_raw_s -> Persistent
247                              As     | keep_s     -> Persistent
248                              HCc    | keep_hc    -> Persistent
249                              _other              -> Temporary
250
251         -- add information about output files to the pipeline
252         -- the suffix on an output file is determined by the next phase
253         -- in the pipeline, so we add linking to the end of the pipeline
254         -- to force the output from the final phase to be a .o file.
255
256       annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
257
258       phase_ne p (p1,_,_) = (p1 /= p)
259    ----------- -----  ----   ---   --   --  -  -  -
260
261    return (
262      takeWhile (phase_ne stop_phase ) $
263      dropWhile (phase_ne start_phase) $
264      annotated_pipeline
265     )
266
267
268 runPipeline
269   :: [ (Phase, IntermediateFileType, String) ] -- phases to run
270   -> String                     -- input file
271   -> Bool                       -- doing linking afterward?
272   -> Bool                       -- take into account -o when generating output?
273   -> IO String                  -- return final filename
274
275 runPipeline pipeline input_fn do_linking use_ofile
276   = pipeLoop pipeline input_fn do_linking use_ofile basename suffix
277   where (basename, suffix) = splitFilename input_fn
278
279 pipeLoop [] input_fn _ _ _ _ = return input_fn
280 pipeLoop ((phase, keep, o_suffix):phases) 
281         input_fn do_linking use_ofile orig_basename orig_suffix
282   = do
283
284      output_fn <- outputFileName (null phases) keep o_suffix
285
286      carry_on <- run_phase phase orig_basename orig_suffix input_fn output_fn
287         -- sometimes we bail out early, eg. when the compiler's recompilation
288         -- checker has determined that recompilation isn't necessary.
289      if not carry_on 
290         then do let (_,keep,final_suffix) = last phases
291                 ofile <- outputFileName True keep final_suffix
292                 return ofile
293         else do -- carry on ...
294
295      pipeLoop phases output_fn do_linking use_ofile orig_basename orig_suffix
296
297   where
298      outputFileName last_phase keep suffix
299         = do o_file <- readIORef v_Output_file
300              if last_phase && not do_linking && use_ofile && isJust o_file
301                then case o_file of 
302                        Just s  -> return s
303                        Nothing -> error "outputFileName"
304                else if keep == Persistent
305                            then odir_ify (orig_basename ++ '.':suffix)
306                            else newTempName suffix
307
308 -------------------------------------------------------------------------------
309 -- Unlit phase 
310
311 run_phase Unlit _basename _suff input_fn output_fn
312   = do unlit_flags <- getOpts opt_L
313        SysTools.runUnlit (unlit_flags ++ ["-h", input_fn, input_fn, output_fn])
314        return True
315
316 -------------------------------------------------------------------------------
317 -- Cpp phase 
318
319 run_phase Cpp basename suff input_fn output_fn
320   = do src_opts <- getOptionsFromSource input_fn
321        unhandled_flags <- processArgs dynamic_flags src_opts []
322        checkProcessArgsResult unhandled_flags basename suff
323
324        do_cpp <- dynFlag cppFlag
325        if do_cpp
326           then do
327             hscpp_opts      <- getOpts opt_P
328             hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
329
330             cmdline_include_paths <- readIORef v_Include_paths
331             pkg_include_dirs <- getPackageIncludePath
332             let include_paths = map (\p -> "-I"++p) (cmdline_include_paths
333                                                         ++ pkg_include_dirs)
334
335             verb <- getVerbFlag
336             (md_c_flags, _) <- machdepCCOpts
337
338             SysTools.runCpp ([verb]
339                             ++ include_paths
340                             ++ hs_src_cpp_opts
341                             ++ hscpp_opts
342                             ++ md_c_flags
343                             ++ [ "-x", "c", input_fn, "-o", output_fn ])
344
345         -- ToDo: switch away from using 'echo' alltogether (but need
346         -- a faster alternative than what's done below).
347 #if defined(mingw32_TARGET_OS) && defined(MINIMAL_UNIX_DEPS)
348           else (do
349             h <- openFile output_fn WriteMode
350             hPutStrLn h ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}")
351             ls <- readFile input_fn -- inefficient, but it'll do for now.
352                                     -- ToDo: speed up via slurping.
353             hPutStrLn h ls
354             hClose h) `catchAllIO`
355                         (\_ -> throwDyn (PhaseFailed "Ineffective C pre-processor" (ExitFailure 1)))
356 #else
357           else do
358             SysTools.runSomething "Ineffective C pre-processor"
359                    ("echo '{-# LINE 1 \""  ++ input_fn ++ "\" #-}' > " 
360                     ++ output_fn ++ " && cat " ++ input_fn
361                     ++ " >> " ++ output_fn) []
362 #endif
363        return True
364
365 -----------------------------------------------------------------------------
366 -- MkDependHS phase
367
368 run_phase MkDependHS basename suff input_fn _output_fn = do 
369    src <- readFile input_fn
370    let (import_sources, import_normals, _) = getImports src
371
372    let orig_fn = basename ++ '.':suff
373    deps_sources <- mapM (findDependency True  orig_fn) import_sources
374    deps_normals <- mapM (findDependency False orig_fn) import_normals
375    let deps = deps_sources ++ deps_normals
376
377    osuf_opt <- readIORef v_Object_suf
378    let osuf = case osuf_opt of
379                         Nothing -> phaseInputExt Ln
380                         Just s  -> s
381
382    extra_suffixes <- readIORef v_Dep_suffixes
383    let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
384        ofiles = map (\suf -> basename ++ '.':suf) suffixes
385            
386    objs <- mapM odir_ify ofiles
387    
388    hdl <- readIORef v_Dep_tmp_hdl
389
390         -- std dependency of the object(s) on the source file
391    hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
392
393    let genDep (dep, False {- not an hi file -}) = 
394           hPutStrLn hdl (unwords objs ++ " : " ++ dep)
395        genDep (dep, True  {- is an hi file -}) = do
396           hisuf <- readIORef v_Hi_suf
397           let dep_base = remove_suffix '.' dep
398               deps = (dep_base ++ hisuf)
399                      : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
400                   -- length objs should be == length deps
401           sequence_ (zipWith (\o d -> hPutStrLn hdl (o ++ " : " ++ d)) objs deps)
402
403    mapM genDep [ d | Just d <- deps ]
404
405    return True
406
407 -- add the lines to dep_makefile:
408            -- always:
409                    -- this.o : this.hs
410
411            -- if the dependency is on something other than a .hi file:
412                    -- this.o this.p_o ... : dep
413            -- otherwise
414                    -- if the import is {-# SOURCE #-}
415                            -- this.o this.p_o ... : dep.hi-boot[-$vers]
416                            
417                    -- else
418                            -- this.o ...   : dep.hi
419                            -- this.p_o ... : dep.p_hi
420                            -- ...
421    
422            -- (where .o is $osuf, and the other suffixes come from
423            -- the cmdline -s options).
424    
425 -----------------------------------------------------------------------------
426 -- Hsc phase
427
428 -- Compilation of a single module, in "legacy" mode (_not_ under
429 -- the direction of the compilation manager).
430 run_phase Hsc basename suff input_fn output_fn
431   = do
432         
433   -- we add the current directory (i.e. the directory in which
434   -- the .hs files resides) to the import path, since this is
435   -- what gcc does, and it's probably what you want.
436         let current_dir = getdir basename
437         
438         paths <- readIORef v_Include_paths
439         writeIORef v_Include_paths (current_dir : paths)
440         
441   -- figure out which header files to #include in a generated .hc file
442         c_includes <- getPackageCIncludes
443         cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
444
445         let cc_injects = unlines (map mk_include 
446                                  (c_includes ++ reverse cmdline_includes))
447             mk_include h_file = 
448                 case h_file of 
449                    '"':_{-"-} -> "#include "++h_file
450                    '<':_      -> "#include "++h_file
451                    _          -> "#include \""++h_file++"\""
452
453         writeIORef v_HCHeader cc_injects
454
455   -- gather the imports and module name
456         (srcimps,imps,mod_name) <- getImportsFromFile input_fn
457
458   -- build a ModuleLocation to pass to hscMain.
459         Just (mod, location')
460            <- mkHomeModuleLocn mod_name basename (Just (basename ++ '.':suff))
461
462   -- take -ohi into account if present
463         ohi <- readIORef v_Output_hi
464         let location | Just fn <- ohi = location'{ ml_hi_file = fn }
465                      | otherwise      = location'
466
467   -- figure out if the source has changed, for recompilation avoidance.
468   -- only do this if we're eventually going to generate a .o file.
469   -- (ToDo: do when generating .hc files too?)
470   --
471   -- Setting source_unchanged to True means that M.o seems
472   -- to be up to date wrt M.hs; so no need to recompile unless imports have
473   -- changed (which the compiler itself figures out).
474   -- Setting source_unchanged to False tells the compiler that M.o is out of
475   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
476         do_recomp   <- readIORef v_Recomp
477         todo        <- readIORef v_GhcMode
478         expl_o_file <- readIORef v_Output_file
479         let o_file = 
480                 case expl_o_file of
481                   Nothing -> unJust "source_unchanged" (ml_obj_file location)
482                   Just x  -> x
483         source_unchanged <- 
484           if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
485              then return False
486              else do t1 <- getModificationTime (basename ++ '.':suff)
487                      o_file_exists <- doesFileExist o_file
488                      if not o_file_exists
489                         then return False       -- Need to recompile
490                         else do t2 <- getModificationTime o_file
491                                 if t2 > t1
492                                   then return True
493                                   else return False
494
495   -- get the DynFlags
496         dyn_flags <- getDynFlags
497
498         let dyn_flags' = dyn_flags { hscOutName = output_fn,
499                                      hscStubCOutName = basename ++ "_stub.c",
500                                      hscStubHOutName = basename ++ "_stub.h",
501                                      extCoreName = basename ++ ".core" }
502
503   -- run the compiler!
504         pcs <- initPersistentCompilerState
505         result <- hscMain OneShot
506                           dyn_flags' mod
507                           location{ ml_hspp_file=Just input_fn }
508                           source_unchanged
509                           False
510                           Nothing        -- no iface
511                           emptyModuleEnv -- HomeSymbolTable
512                           emptyModuleEnv -- HomeIfaceTable
513                           pcs
514
515         case result of {
516
517             HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
518
519             HscNoRecomp pcs details iface -> do { SysTools.touch "Touching object file" o_file
520                                                 ; return False } ;
521
522             HscRecomp pcs details iface stub_h_exists stub_c_exists
523                       _maybe_interpreted_code -> do
524
525             -- deal with stubs
526         maybe_stub_o <- compileStub dyn_flags' stub_c_exists
527         case maybe_stub_o of
528                 Nothing -> return ()
529                 Just stub_o -> add v_Ld_inputs stub_o
530
531         return True
532     }
533
534 -----------------------------------------------------------------------------
535 -- Cc phase
536
537 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
538 -- way too many hacks, and I can't say I've ever used it anyway.
539
540 run_phase cc_phase basename suff input_fn output_fn
541    | cc_phase == Cc || cc_phase == HCc
542    = do cc_opts              <- getOpts opt_c
543         cmdline_include_dirs <- readIORef v_Include_paths
544
545         let hcc = cc_phase == HCc
546
547                 -- add package include paths even if we're just compiling
548                 -- .c files; this is the Value Add(TM) that using
549                 -- ghc instead of gcc gives you :)
550         pkg_include_dirs <- getPackageIncludePath
551         let include_paths = map (\p -> "-I"++p) (cmdline_include_dirs 
552                                                         ++ pkg_include_dirs)
553
554         mangle <- readIORef v_Do_asm_mangling
555         (md_c_flags, md_regd_c_flags) <- machdepCCOpts
556
557         verb <- getVerbFlag
558
559         o2 <- readIORef v_minus_o2_for_C
560         let opt_flag | o2        = "-O2"
561                      | otherwise = "-O"
562
563         pkg_extra_cc_opts <- getPackageExtraCcOpts
564
565         split_objs <- readIORef v_Split_object_files
566         let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
567                       | otherwise         = [ ]
568
569         excessPrecision <- readIORef v_Excess_precision
570         SysTools.runCc ([ "-x", "c", input_fn, "-o", output_fn ]
571                        ++ md_c_flags
572                        ++ (if cc_phase == HCc && mangle
573                              then md_regd_c_flags
574                              else [])
575                        ++ [ verb, "-S", "-Wimplicit", opt_flag ]
576                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
577                        ++ cc_opts
578                        ++ split_opt
579                        ++ (if excessPrecision then [] else [ "-ffloat-store" ])
580                        ++ include_paths
581                        ++ pkg_extra_cc_opts
582                        )
583         return True
584
585         -- ToDo: postprocess the output from gcc
586
587 -----------------------------------------------------------------------------
588 -- Mangle phase
589
590 run_phase Mangle _basename _suff input_fn output_fn
591   = do mangler_opts <- getOpts opt_m
592        machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
593                        then do n_regs <- dynFlag stolen_x86_regs
594                                return [ show n_regs ]
595                        else return []
596
597        SysTools.runMangle (mangler_opts
598                           ++ [ input_fn, output_fn ]
599                           ++ machdep_opts)
600        return True
601
602 -----------------------------------------------------------------------------
603 -- Splitting phase
604
605 run_phase SplitMangle _basename _suff input_fn _output_fn
606   = do  -- tmp_pfx is the prefix used for the split .s files
607         -- We also use it as the file to contain the no. of split .s files (sigh)
608         split_s_prefix <- SysTools.newTempName "split"
609         let n_files_fn = split_s_prefix
610
611         SysTools.runSplit [input_fn, split_s_prefix, n_files_fn]
612
613         -- Save the number of split files for future references
614         s <- readFile n_files_fn
615         let n_files = read s :: Int
616         writeIORef v_Split_info (split_s_prefix, n_files)
617
618         -- Remember to delete all these files
619         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
620                         | n <- [1..n_files]]
621
622         return True
623
624 -----------------------------------------------------------------------------
625 -- As phase
626
627 run_phase As _basename _suff input_fn output_fn
628   = do  as_opts               <- getOpts opt_a
629         cmdline_include_paths <- readIORef v_Include_paths
630
631         SysTools.runAs (as_opts
632                        ++ [ "-I" ++ p | p <- cmdline_include_paths ]
633                        ++ [ "-c", input_fn, "-o",  output_fn ])
634         return True
635
636 run_phase SplitAs basename _suff _input_fn _output_fn
637   = do  as_opts <- getOpts opt_a
638
639         (split_s_prefix, n) <- readIORef v_Split_info
640
641         odir <- readIORef v_Output_dir
642         let real_odir = case odir of
643                                 Nothing -> basename
644                                 Just d  -> d
645
646         let assemble_file n
647               = do  let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
648                     let output_o = newdir real_odir 
649                                         (basename ++ "__" ++ show n ++ ".o")
650                     real_o <- osuf_ify output_o
651                     SysTools.runAs (as_opts ++ ["-c", "-o", real_o, input_s])
652         
653         mapM_ assemble_file [1..n]
654         return True
655
656 -----------------------------------------------------------------------------
657 -- MoveBinary sort-of-phase
658 -- After having produced a binary, move it somewhere else and generate a
659 -- wrapper script calling the binary. Currently, we need this only in 
660 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
661 -- central directory.
662 -- This is called from doLink below, after linking. I haven't made it
663 -- a separate phase to minimise interfering with other modules, and
664 -- we don't need the generality of a phase (MoveBinary is always
665 -- done after linking and makes only sense in a parallel setup)   -- HWL
666
667 run_phase_MoveBinary input_fn
668   = do  
669         sysMan   <- getSysMan
670         pvm_root <- getEnv "PVM_ROOT"
671         pvm_arch <- getEnv "PVM_ARCH"
672         let 
673            pvm_executable_base = "=" ++ input_fn
674            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
675         -- nuke old binary; maybe use configur'ed names for cp and rm?
676         system ("rm -f " ++ pvm_executable)
677         -- move the newly created binary into PVM land
678         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
679         -- generate a wrapper script for running a parallel prg under PVM
680         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
681         return True
682
683 -- generates a Perl skript starting a parallel prg under PVM
684 mk_pvm_wrapper_script :: String -> String -> String -> String
685 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
686  [
687   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
688   "  if $running_under_some_shell;",
689   "# =!=!=!=!=!=!=!=!=!=!=!",
690   "# This script is automatically generated: DO NOT EDIT!!!",
691   "# Generated by Glasgow Haskell Compiler",
692   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
693   "#",
694   "$pvm_executable      = '" ++ pvm_executable ++ "';",
695   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
696   "$SysMan = '" ++ sysMan ++ "';",
697   "",
698   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
699   "# first, some magical shortcuts to run "commands" on the binary",
700   "# (which is hidden)",
701   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
702   "    local($cmd) = $1;",
703   "    system("$cmd $pvm_executable");",
704   "    exit(0); # all done",
705   "}", -}
706   "",
707   "# Now, run the real binary; process the args first",
708   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
709   "$debug = '';",
710   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
711   "@nonPVM_args = ();",
712   "$in_RTS_args = 0;",
713   "",
714   "args: while ($a = shift(@ARGV)) {",
715   "    if ( $a eq '+RTS' ) {",
716   "     $in_RTS_args = 1;",
717   "    } elsif ( $a eq '-RTS' ) {",
718   "     $in_RTS_args = 0;",
719   "    }",
720   "    if ( $a eq '-d' && $in_RTS_args ) {",
721   "     $debug = '-';",
722   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
723   "     $nprocessors = $1;",
724   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
725   "     $nprocessors = $1;",
726   "    } else {",
727   "     push(@nonPVM_args, $a);",
728   "    }",
729   "}",
730   "",
731   "local($return_val) = 0;",
732   "# Start the parallel execution by calling SysMan",
733   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
734   "$return_val = $?;",
735   "# ToDo: fix race condition moving files and flushing them!!",
736   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
737   "exit($return_val);"
738  ]
739
740 -----------------------------------------------------------------------------
741 -- Complain about non-dynamic flags in OPTIONS pragmas
742
743 checkProcessArgsResult flags basename suff
744   = do when (not (null flags)) (throwDyn (ProgramError (
745            basename ++ "." ++ suff 
746            ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t" 
747            ++ unwords flags)) (ExitFailure 1))
748
749 -----------------------------------------------------------------------------
750 -- Linking
751
752 doLink :: [String] -> IO ()
753 doLink o_files = do
754     verb       <- getVerbFlag
755     static     <- readIORef v_Static
756     no_hs_main <- readIORef v_NoHsMain
757
758     o_file <- readIORef v_Output_file
759     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
760
761     pkg_lib_paths <- getPackageLibraryPath
762     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
763
764     lib_paths <- readIORef v_Library_paths
765     let lib_path_opts = map ("-L"++) lib_paths
766
767     pkg_libs <- getPackageLibraries
768     let imp          = if static then "" else "_imp"
769         pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
770
771     libs <- readIORef v_Cmdline_libraries
772     let lib_opts = map ("-l"++) (reverse libs)
773          -- reverse because they're added in reverse order from the cmd line
774
775     pkg_extra_ld_opts <- getPackageExtraLdOpts
776
777         -- probably _stub.o files
778     extra_ld_inputs <- readIORef v_Ld_inputs
779
780         -- opts from -optl-<blah>
781     extra_ld_opts <- getStaticOpts v_Opt_l
782
783     rts_pkg <- getPackageDetails ["rts"]
784     std_pkg <- getPackageDetails ["std"]
785     let extra_os = if static || no_hs_main
786                    then []
787                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
788                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
789
790     (md_c_flags, _) <- machdepCCOpts
791     SysTools.runLink ( [verb, "-o", output_fn]
792                       ++ md_c_flags
793                       ++ o_files
794                       ++ extra_os
795                       ++ extra_ld_inputs
796                       ++ lib_path_opts
797                       ++ lib_opts
798                       ++ pkg_lib_path_opts
799                       ++ pkg_lib_opts
800                       ++ pkg_extra_ld_opts
801                       ++ extra_ld_opts
802                       ++ if static then [ "-u _PrelMain_mainIO_closure" , "-u ___init_PrelMain"] else [])
803
804     -- parallel only: move binary to another dir -- HWL
805     ways_ <- readIORef v_Ways
806     when (WayPar `elem` ways_)
807          (do success <- run_phase_MoveBinary output_fn
808              if success then return ()
809                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
810
811 -----------------------------------------------------------------------------
812 -- Making a DLL (only for Win32)
813
814 doMkDLL :: [String] -> IO ()
815 doMkDLL o_files = do
816     verb       <- getVerbFlag
817     static     <- readIORef v_Static
818     no_hs_main <- readIORef v_NoHsMain
819
820     o_file <- readIORef v_Output_file
821     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
822
823     pkg_lib_paths <- getPackageLibraryPath
824     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
825
826     lib_paths <- readIORef v_Library_paths
827     let lib_path_opts = map ("-L"++) lib_paths
828
829     pkg_libs <- getPackageLibraries
830     let imp = if static then "" else "_imp"
831         pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
832
833     libs <- readIORef v_Cmdline_libraries
834     let lib_opts = map ("-l"++) (reverse libs)
835          -- reverse because they're added in reverse order from the cmd line
836
837     pkg_extra_ld_opts <- getPackageExtraLdOpts
838
839         -- probably _stub.o files
840     extra_ld_inputs <- readIORef v_Ld_inputs
841
842         -- opts from -optdll-<blah>
843     extra_ld_opts <- getStaticOpts v_Opt_dll
844
845     rts_pkg <- getPackageDetails ["rts"]
846     std_pkg <- getPackageDetails ["std"]
847
848     let extra_os = if static || no_hs_main
849                    then []
850                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
851                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
852
853     (md_c_flags, _) <- machdepCCOpts
854     SysTools.runMkDLL
855          ([ verb, "-o", output_fn ]
856          ++ md_c_flags
857          ++ o_files
858          ++ extra_os
859          ++ [ "--target=i386-mingw32" ]
860          ++ extra_ld_inputs
861          ++ lib_path_opts
862          ++ lib_opts
863          ++ pkg_lib_path_opts
864          ++ pkg_lib_opts
865          ++ pkg_extra_ld_opts
866          ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
867                Nothing -> [ "--export-all" ]
868                Just _  -> [ "" ])
869          ++ extra_ld_opts
870         )
871
872 -----------------------------------------------------------------------------
873 -- Just preprocess a file, put the result in a temp. file (used by the
874 -- compilation manager during the summary phase).
875
876 preprocess :: FilePath -> IO FilePath
877 preprocess filename =
878   ASSERT(haskellish_src_file filename) 
879   do restoreDynFlags    -- Restore to state of last save
880      pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False 
881                              defaultHscLang filename
882      runPipeline pipeline filename False{-no linking-} False{-no -o flag-}
883
884 -----------------------------------------------------------------------------
885 -- Compile a single module, under the control of the compilation manager.
886 --
887 -- This is the interface between the compilation manager and the
888 -- compiler proper (hsc), where we deal with tedious details like
889 -- reading the OPTIONS pragma from the source file, and passing the
890 -- output of hsc through the C compiler.
891
892 -- The driver sits between 'compile' and 'hscMain', translating calls
893 -- to the former into calls to the latter, and results from the latter
894 -- into results from the former.  It does things like preprocessing
895 -- the .hs file if necessary, and compiling up the .stub_c files to
896 -- generate Linkables.
897
898 -- NB.  No old interface can also mean that the source has changed.
899
900 compile :: GhciMode                -- distinguish batch from interactive
901         -> ModSummary              -- summary, including source
902         -> Bool                    -- True <=> source unchanged
903         -> Bool                    -- True <=> have object
904         -> Maybe ModIface          -- old interface, if available
905         -> HomeSymbolTable         -- for home module ModDetails
906         -> HomeIfaceTable          -- for home module Ifaces
907         -> PersistentCompilerState -- persistent compiler state
908         -> IO CompResult
909
910 data CompResult
911    = CompOK   PersistentCompilerState   -- updated PCS
912               ModDetails  -- new details (HST additions)
913               ModIface    -- new iface   (HIT additions)
914               (Maybe Linkable)
915                        -- new code; Nothing => compilation was not reqd
916                        -- (old code is still valid)
917
918    | CompErrs PersistentCompilerState   -- updated PCS
919
920
921 compile ghci_mode summary source_unchanged have_object 
922         old_iface hst hit pcs = do 
923    dyn_flags <- restoreDynFlags         -- Restore to the state of the last save
924
925
926    showPass dyn_flags 
927         (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
928
929    let verb       = verbosity dyn_flags
930    let location   = ms_location summary
931    let input_fn   = unJust "compile:hs" (ml_hs_file location) 
932    let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
933
934    when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
935
936    opts <- getOptionsFromSource input_fnpp
937    processArgs dynamic_flags opts []
938    dyn_flags <- getDynFlags
939
940    let hsc_lang      = hscLang dyn_flags
941        (basename, _) = splitFilename input_fn
942        
943    output_fn <- case hsc_lang of
944                     HscAsm         -> newTempName (phaseInputExt As)
945                     HscC           -> newTempName (phaseInputExt HCc)
946                     HscJava        -> newTempName "java" -- ToDo
947                     HscILX         -> return (basename ++ ".ilx")       -- newTempName "ilx"    -- ToDo
948                     HscInterpreted -> return (error "no output file")
949
950    let dyn_flags' = dyn_flags { hscOutName = output_fn,
951                                 hscStubCOutName = basename ++ "_stub.c",
952                                 hscStubHOutName = basename ++ "_stub.h",
953                                 extCoreName = basename ++ ".core" }
954
955    -- figure out which header files to #include in a generated .hc file
956    c_includes <- getPackageCIncludes
957    cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
958
959    let cc_injects = unlines (map mk_include 
960                                  (c_includes ++ reverse cmdline_includes))
961        mk_include h_file = 
962         case h_file of 
963            '"':_{-"-} -> "#include "++h_file
964            '<':_      -> "#include "++h_file
965            _          -> "#include \""++h_file++"\""
966
967    writeIORef v_HCHeader cc_injects
968
969    -- run the compiler
970    hsc_result <- hscMain ghci_mode dyn_flags'
971                          (ms_mod summary) location
972                          source_unchanged have_object old_iface hst hit pcs
973
974    case hsc_result of
975       HscFail pcs -> return (CompErrs pcs)
976
977       HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
978
979       HscRecomp pcs details iface
980         stub_h_exists stub_c_exists maybe_interpreted_code -> do
981            
982            let 
983            maybe_stub_o <- compileStub dyn_flags' stub_c_exists
984            let stub_unlinked = case maybe_stub_o of
985                                   Nothing -> []
986                                   Just stub_o -> [ DotO stub_o ]
987
988            (hs_unlinked, unlinked_time) <-
989              case hsc_lang of
990
991                 -- in interpreted mode, just return the compiled code
992                 -- as our "unlinked" object.
993                 HscInterpreted -> 
994                     case maybe_interpreted_code of
995                        Just (bcos,itbl_env) -> do tm <- getClockTime 
996                                                   return ([BCOs bcos itbl_env], tm)
997                        Nothing -> panic "compile: no interpreted code"
998
999                 -- we're in batch mode: finish the compilation pipeline.
1000                 _other -> do pipe <- genPipeline (StopBefore Ln) "" True 
1001                                         hsc_lang output_fn
1002                              -- runPipeline takes input_fn so it can split off 
1003                              -- the base name and use it as the base of 
1004                              -- the output object file.
1005                              let (basename, suffix) = splitFilename input_fn
1006                              o_file <- pipeLoop pipe output_fn False False 
1007                                                 basename suffix
1008                              o_time <- getModificationTime o_file
1009                              return ([DotO o_file], o_time)
1010
1011            let linkable = LM unlinked_time (moduleName (ms_mod summary)) 
1012                              (hs_unlinked ++ stub_unlinked)
1013
1014            return (CompOK pcs details iface (Just linkable))
1015
1016
1017 -----------------------------------------------------------------------------
1018 -- stub .h and .c files (for foreign export support)
1019
1020 compileStub dflags stub_c_exists
1021   | not stub_c_exists = return Nothing
1022   | stub_c_exists = do
1023         -- compile the _stub.c file w/ gcc
1024         let stub_c = hscStubCOutName dflags
1025         pipeline <- genPipeline (StopBefore Ln) "" True defaultHscLang stub_c
1026         stub_o <- runPipeline pipeline stub_c False{-no linking-} 
1027                         False{-no -o option-}
1028
1029         return (Just stub_o)