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