DriverPipeline.hs 45.2 KB
Newer Older
1
2
3
4
-----------------------------------------------------------------------------
--
-- GHC Driver
--
5
-- (c) The University of Glasgow 2002
6
7
8
--
-----------------------------------------------------------------------------

9
#include "../includes/ghcconfig.h"
rrt's avatar
rrt committed
10

11
module DriverPipeline (
12

13
	-- Interfaces for the batch-mode driver
14
   compileFile, staticLink,
15

16
17
18
19
	-- Interfaces for the compilation manager (interpreted/batch-mode)
   preprocess, 
   compile, CompResult(..), 
   link, 
20

rrt's avatar
rrt committed
21
22
        -- DLL building
   doMkDLL
23
24
25
26
  ) where

#include "HsVersions.h"

27
import Packages
28
import GetImports
29
30
import DriverState
import DriverUtil
31
import DriverPhases
32
import DriverFlags
sof's avatar
sof committed
33
import SysTools		( newTempName, addFilesToClean, getSysMan, copy )
34
import qualified SysTools	
35
import HscMain
36
import Finder
37
38
39
import HscTypes
import Outputable
import Module
40
import ErrUtils
41
import CmdLineOpts
42
import Config
43
import RdrName		( GlobalRdrEnv )
44
import Panic
45
import Util
46
import StringBuffer	( hGetStringBuffer )
47
import BasicTypes	( SuccessFlag(..) )
48
import Maybes		( expectJust )
49

50
51
import ParserCoreUtils ( getCoreModuleName )

52
53
54
import EXCEPTION
import DATA_IOREF	( readIORef, writeIORef )

55
56
import Directory
import System
57
58
59
60
import IO
import Monad
import Maybe

61

62
63
-- ---------------------------------------------------------------------------
-- Pre-process
64
65
66

-- Just preprocess a file, put the result in a temp. file (used by the
-- compilation manager during the summary phase).
67
68
69
--
-- We return the augmented DynFlags, because they contain the result
-- of slurping in the OPTIONS pragmas
70

71
preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
72
preprocess dflags filename =
73
  ASSERT2(isHaskellSrcFilename filename, text filename) 
74
  runPipeline (StopBefore anyHsc) ("preprocess")  dflags
75
76
77
	False{-temporary output file-}
	Nothing{-no specific output file-}
	filename
78
	Nothing{-no ModLocation-}
79

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94


-- ---------------------------------------------------------------------------
--		Compile a file
--  	This is used in batch mode 
compileFile :: GhcMode -> DynFlags -> FilePath -> IO FilePath
compileFile mode dflags src = do
   exists <- doesFileExist src
   when (not exists) $ 
   	throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
   
   o_file  <- readIORef v_Output_file
   no_link <- readIORef v_NoLink	-- Set by -c or -no-link
	-- When linking, the -o argument refers to the linker's output.	
	-- otherwise, we use it as the name for the pipeline's output.
95
96
   let maybe_o_file | isLinkMode mode && not no_link = Nothing
		    | otherwise		   	     = o_file
97

98
99
   mode_flag_string <- readIORef v_GhcModeFlag
   (_, out_file) <- runPipeline mode mode_flag_string dflags True maybe_o_file
100
101
102
103
				src Nothing{-no ModLocation-}
   return out_file


104
105
-- ---------------------------------------------------------------------------
-- Compile
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

-- Compile a single module, under the control of the compilation manager.
--
-- This is the interface between the compilation manager and the
-- compiler proper (hsc), where we deal with tedious details like
-- reading the OPTIONS pragma from the source file, and passing the
-- output of hsc through the C compiler.

-- The driver sits between 'compile' and 'hscMain', translating calls
-- to the former into calls to the latter, and results from the latter
-- into results from the former.  It does things like preprocessing
-- the .hs file if necessary, and compiling up the .stub_c files to
-- generate Linkables.

-- NB.  No old interface can also mean that the source has changed.

122
compile :: HscEnv
123
124
125
126
	-> ModSummary
	-> Bool			-- True <=> source unchanged
	-> Bool			-- True <=> have object
        -> Maybe ModIface       -- Old interface, if available
127
128
129
        -> IO CompResult

data CompResult
130
131
132
133
   = CompOK   ModDetails 		-- New details
	      (Maybe GlobalRdrEnv)	-- Lexical environment for the module
					-- (Maybe because we may have loaded it from
					--  its precompiled interface)
134
135
136
137
              ModIface			-- New iface
              (Maybe Linkable)	-- New code; Nothing => compilation was not reqd
		                --			(old code is still valid)

138
   | CompErrs 
139
140


141
142
compile hsc_env mod_summary
	source_unchanged have_object old_iface = do 
143

144
145
146
   let dyn_flags   = hsc_dflags hsc_env
       this_mod    = ms_mod mod_summary
       src_flavour = ms_hsc_src mod_summary
147

148
   showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
149
150

   let verb	  = verbosity dyn_flags
151
   let location	  = ms_location mod_summary
152
   let input_fn   = expectJust "compile:hs" (ml_hs_file location) 
153
   let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
154
155
156

   when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))

157
158
159
   -- Add in the OPTIONS from the source file
   -- This is nasty: we've done this once already, in the compilation manager
   -- It might be better to cache the flags in the ml_hspp_file field,say
160
   opts <- getOptionsFromSource input_fnpp
161
162
   (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
   checkProcessArgsResult unhandled_flags input_fn
163

164
   let (basename, _) = splitFilename input_fn
165

166
167
168
169
170
171
172
173
174
  -- We add the directory in which the .hs files resides) to the import path.
  -- This is needed when we try to compile the .hc file later, if it
  -- imports a _stub.h file that we created here.
   let current_dir = directoryOf basename
   old_paths <- readIORef v_Include_paths
   writeIORef v_Include_paths (current_dir : old_paths)
   -- put back the old include paths afterward.
   later (writeIORef v_Include_paths old_paths) $ do

175
   -- Figure out what lang we're generating
176
   hsc_lang <- hscMaybeAdjustTarget StopLn src_flavour (hscTarget dyn_flags)
177
178
179
180
181
   -- ... and what the next phase should be
   next_phase <- hscNextPhase src_flavour hsc_lang
   -- ... and what file to generate the output into
   get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
   output_fn     <- get_output_fn next_phase (Just location)
182

183
   let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
184
				hscOutName = output_fn,
185
186
187
188
189
				hscStubCOutName = basename ++ "_stub.c",
				hscStubHOutName = basename ++ "_stub.h",
				extCoreName = basename ++ ".hcr" }

   -- -no-recomp should also work with --make
190
191
   let do_recomp = recompFlag dyn_flags
       source_unchanged' = source_unchanged && do_recomp
192
       hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
193
194

   -- run the compiler
195
   hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
196
197
198
			 source_unchanged' have_object old_iface

   case hsc_result of
199
      HscFail -> return CompErrs
200

201
      HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
202

203
      HscRecomp details rdr_env iface
204
205
206
207
208
209
210
		stub_h_exists stub_c_exists maybe_interpreted_code 

	| isHsBoot src_flavour	-- No further compilation to do
	-> return (CompOK details rdr_env iface Nothing)

	| otherwise		-- Normal Haskell source files
	-> do
211
212
213
214
215
216
217
218
219
220
221
222
223
224
	   let 
	   maybe_stub_o <- compileStub dyn_flags' stub_c_exists
	   let stub_unlinked = case maybe_stub_o of
				  Nothing -> []
				  Just stub_o -> [ DotO stub_o ]

	   (hs_unlinked, unlinked_time) <-
	     case hsc_lang of

		-- in interpreted mode, just return the compiled code
		-- as our "unlinked" object.
		HscInterpreted -> 
		    case maybe_interpreted_code of
#ifdef GHCI
225
		       Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
226
227
228
229
230
231
			-- Why do we use the timestamp of the source file here,
			-- rather than the current time?  This works better in
			-- the case where the local clock is out of sync
			-- with the filesystem's clock.  It's just as accurate:
			-- if the source is modified, then the linkable will
			-- be out of date.
232
233
234
235
#endif
		       Nothing -> panic "compile: no interpreted code"

		-- we're in batch mode: finish the compilation pipeline.
236
237
238
		_other -> do
		   let object_filename = ml_obj_file location

239
		   runPipeline DoLink "" dyn_flags
240
			       True Nothing output_fn (Just location)
241
			-- the object filename comes from the ModLocation
242
243
244

		   o_time <- getModificationTime object_filename
		   return ([DotO object_filename], o_time)
245

246
	   let linkable = LM unlinked_time this_mod
247
248
			     (hs_unlinked ++ stub_unlinked)

249
	   return (CompOK details rdr_env iface (Just linkable))
250

251
-----------------------------------------------------------------------------
252
253
254
255
256
257
258
-- stub .h and .c files (for foreign export support)

compileStub dflags stub_c_exists
  | not stub_c_exists = return Nothing
  | stub_c_exists = do
	-- compile the _stub.c file w/ gcc
	let stub_c = hscStubCOutName dflags
259
	(_, stub_o) <- runPipeline DoLink "stub-compile" dflags
260
261
262
263
			    True{-persistent output-} 
			    Nothing{-no specific output file-}
			    stub_c
			    Nothing{-no ModLocation-}
264
265
266
	return (Just stub_o)


267
268
-- ---------------------------------------------------------------------------
-- Link
269
270
271
272

link :: GhciMode		-- interactive or batch
     -> DynFlags		-- dynamic flags
     -> Bool			-- attempt linking in batch mode?
273
     -> HomePackageTable	-- what to link
274
275
276
277
278
279
280
281
282
283
     -> IO SuccessFlag

-- For the moment, in the batch linker, we don't bother to tell doLink
-- which packages to link -- it just tries all that are available.
-- batch_attempt_linking should only be *looked at* in batch mode.  It
-- should only be True if the upsweep was successful and someone
-- exports main, i.e., we have good reason to believe that linking
-- will succeed.

#ifdef GHCI
284
285
link Interactive dflags batch_attempt_linking hpt
    = do -- Not Linking...(demand linker will do the job)
286
287
288
	 return Succeeded
#endif

289
link Batch dflags batch_attempt_linking hpt
290
   | batch_attempt_linking
291
   = do 
292
293
294
295
296
297
298
299
300
301
302
303
304
	let 
	    home_mod_infos = moduleEnvElts hpt

	    -- the packages we depend on
	    pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos

	    -- the linkables to link
	    linkables = map hm_linkable home_mod_infos

        when (verb >= 3) $ do
	     hPutStrLn stderr "link: linkables are ..."
             hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))

305
306
307
308
	-- check for the -no-link flag
	omit_linking <- readIORef v_NoLink
	if omit_linking 
	  then do when (verb >= 3) $
309
		    hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
310
311
312
313
314
	          return Succeeded
	  else do

	when (verb >= 1) $
             hPutStrLn stderr "Linking ..."
315

316
317
318
	let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
	    obj_files = concatMap getOfiles linkables

319
	-- Don't showPass in Batch mode; doLink will do that for us.
320
        staticLink dflags obj_files pkg_deps
321
322

        when (verb >= 3) (hPutStrLn stderr "link: done")
323
324
325
326
327
328
329
330
331
332
333

	-- staticLink only returns if it succeeds
        return Succeeded

   | otherwise
   = do when (verb >= 3) $ do
	    hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
            hPutStrLn stderr "   Main.main not exported; not linking."
        return Succeeded
   where
      verb = verbosity dflags
334
      
335
336
-- ---------------------------------------------------------------------------
-- Run a compilation pipeline, consisting of multiple phases.
337

338
339
340
341
-- The DynFlags can be modified by phases in the pipeline (eg. by
-- OPTIONS pragmas), and the changes affect later phases in the
-- pipeline, but we throw away the resulting DynFlags at the end.

342
343
344
runPipeline
  :: GhcMode		-- when to stop
  -> String		-- "stop after" flag
345
  -> DynFlags		-- dynamic flags
346
347
348
  -> Bool		-- final output is persistent?
  -> Maybe FilePath	-- where to put the output, optionally
  -> FilePath 		-- input filename
349
  -> Maybe ModLocation  -- a ModLocation for this module, if we have one
350
  -> IO (DynFlags, FilePath)	-- (final flags, output filename)
351

352
runPipeline todo mode_flag_string dflags keep_output 
353
  maybe_output_filename input_fn maybe_loc
354
355
356
357
  = do
  split <- readIORef v_Split_object_files
  let (basename, suffix) = splitFilename input_fn
      start_phase = startPhase suffix
358

359
360
361
      todo' = case todo of
		StopBefore As | split -> StopBefore SplitAs
		other		      -> todo
362

363
364
365
366
367
368
369
  -- We want to catch cases of "you can't get there from here" before
  -- we start the pipeline, because otherwise it will just run off the
  -- end.
  --
  -- There is a partial ordering on phases, where A < B iff A occurs
  -- before B in a normal compilation pipeline.
  --
370
371
372
373
  let stop_phase = case todo' of 
			StopBefore phase -> phase
			other		 -> StopLn

374
375
  when (not (start_phase `happensBefore` stop_phase)) $
	throwDyn (UsageError 
376
		    ("flag `" ++ mode_flag_string
377
378
379
380
381
		     ++ "' is incompatible with source file `"
		     ++ input_fn ++ "'"))

  -- generate a function which will be used to calculate output file names
  -- as we go along.
382
383
  get_output_fn <- genOutputFilenameFunc stop_phase keep_output 
					 maybe_output_filename basename
384

385
  -- Execute the pipeline...
386
  (dflags', output_fn, maybe_loc) <- pipeLoop dflags start_phase stop_phase input_fn 
387
				  	      basename suffix get_output_fn maybe_loc
388

389
  -- Sometimes, a compilation phase doesn't actually generate any output
390
391
392
  -- (eg. the CPP phase when -fcpp is not turned on).  If we end on this
  -- stage, but we wanted to keep the output, then we have to explicitly
  -- copy the file.
393
  if keep_output 
394
	then do final_fn <- get_output_fn stop_phase maybe_loc
395
	        when (final_fn /= output_fn) $
396
	 	  copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
397
			++ "'") output_fn final_fn
398
	        return (dflags', final_fn)
399
	else
400
	        return (dflags', output_fn)
401
402


403
pipeLoop :: DynFlags -> Phase -> Phase 
404
405
406
407
	 -> FilePath  -> String -> Suffix
	 -> (Phase -> Maybe ModLocation -> IO FilePath)
	 -> Maybe ModLocation
	 -> IO (DynFlags, FilePath, Maybe ModLocation)
408

409
pipeLoop dflags phase stop_phase 
410
411
	 input_fn orig_basename orig_suff 
	 orig_get_output_fn maybe_loc
412

413
414
  | phase `eqPhase` stop_phase		  -- All done
  = return (dflags, input_fn, maybe_loc)
415

416
  | not (phase `happensBefore` stop_phase)
417
418
419
420
	-- Something has gone wrong.  We'll try to cover all the cases when
	-- this could happen, so if we reach here it is a panic.
	-- eg. it might happen if the -C flag is used on a source file that
	-- has {-# OPTIONS -fasm #-}.
421
422
423
424
425
  = panic ("pipeLoop: at phase " ++ show phase ++ 
	   " but I wanted to stop at phase " ++ show stop_phase)

  | otherwise 
  = do	{ (next_phase, dflags', maybe_loc, output_fn)
426
		<- runPhase phase stop_phase dflags orig_basename 
427
			    orig_suff input_fn orig_get_output_fn maybe_loc
428
	; pipeLoop dflags' next_phase stop_phase output_fn
429
430
431
		   orig_basename orig_suff orig_get_output_fn maybe_loc }

genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
432
  -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
433
genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
434
 = do
435
   hcsuf      <- readIORef v_HC_suf
436
   odir       <- readIORef v_Output_dir
437
   osuf       <- readIORef v_Object_suf
438
   keep_hc    <- readIORef v_Keep_hc_files
sof's avatar
sof committed
439
#ifdef ILX
rrt's avatar
rrt committed
440
   keep_il    <- readIORef v_Keep_il_files
sof's avatar
sof committed
441
442
   keep_ilx   <- readIORef v_Keep_ilx_files
#endif
443
444
   keep_raw_s <- readIORef v_Keep_raw_s_files
   keep_s     <- readIORef v_Keep_s_files
445
   let
446
447
448
        myPhaseInputExt HCc    = hcsuf
        myPhaseInputExt StopLn = osuf
        myPhaseInputExt other  = phaseInputExt other
449

450
	func next_phase maybe_location
451
452
453
454
455
		| is_last_phase, Just f <- maybe_output_filename = return f
		| is_last_phase && keep_final_output = persistent_fn
		| keep_this_output 		     = persistent_fn
     		| otherwise        		     = newTempName suffix

456
	   where
457
		is_last_phase = next_phase `eqPhase` stop_phase
458
459
460
461

		-- sometimes, we keep output from intermediate stages
		keep_this_output = 
     		     case next_phase of
462
     			     StopLn              -> True
463
464
465
466
467
     			     Mangle | keep_raw_s -> True
     			     As     | keep_s     -> True
     			     HCc    | keep_hc    -> True
     			     _other              -> False

468
		suffix = myPhaseInputExt next_phase
469
470
471

		-- persistent object files get put in odir
	        persistent_fn 
472
473
		   | StopLn <- next_phase = return odir_persistent
		   | otherwise            = return persistent
474

475
		persistent = basename ++ '.':suffix
476

477
		odir_persistent
478
		   | Just loc <- maybe_location = ml_obj_file loc
479
480
481
		   | Just d <- odir = replaceFilenameDirectory persistent d
		   | otherwise      = persistent

482
   return func
483
484


485
486
487
488
489
490
491
492
493
494
-- -----------------------------------------------------------------------------
-- Each phase in the pipeline returns the next phase to execute, and the
-- name of the file in which the output was placed.
--
-- We must do things dynamically this way, because we often don't know
-- what the rest of the phases will be until part-way through the
-- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
-- of a source file can change the latter stages of the pipeline from
-- taking the via-C route to using the native code generator.

495
496
runPhase :: Phase	-- Do this phase first
	 -> Phase	-- Stop just before this phase
497
498
499
500
501
	 -> DynFlags
	 -> String	-- basename of original input source
	 -> String	-- its extension
	 -> FilePath	-- name of file which contains the input to this phase.
	 -> (Phase -> Maybe ModLocation -> IO FilePath)
502
			-- how to calculate the output filename
503
	 -> Maybe ModLocation		-- the ModLocation, if we have one
504
	 -> IO (Phase,	  		-- next phase
505
506
507
		DynFlags,		-- new dynamic flags
		Maybe ModLocation,	-- the ModLocation, if we have one
		FilePath)		-- output filename
508

509
510
511
512
	-- Invariant: the output filename always contains the output
	-- Interesting case: Hsc when there is no recompilation to do
	--		     Then the output filename is still a .o file 

513
514
515
-------------------------------------------------------------------------------
-- Unlit phase 

516
runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
517
  = do let unlit_flags = getOpts dflags opt_L
rrt's avatar
rrt committed
518
       -- The -h option passes the file name for unlit to put in a #line directive
519
       output_fn <- get_output_fn (Cpp sf) maybe_loc
520

521
522
       SysTools.runUnlit dflags 
		(map SysTools.Option unlit_flags ++
sof's avatar
sof committed
523
524
       			  [ SysTools.Option     "-h"
 			  , SysTools.Option     input_fn
sof's avatar
sof committed
525
526
			  , SysTools.FileOption "" input_fn
			  , SysTools.FileOption "" output_fn
sof's avatar
sof committed
527
			  ])
528

529
       return (Cpp sf, dflags, maybe_loc, output_fn)
530
531

-------------------------------------------------------------------------------
532
533
-- Cpp phase : (a) gets OPTIONS out of file
--	       (b) runs cpp if necessary
534

535
runPhase (Cpp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
536
  = do src_opts <- getOptionsFromSource input_fn
537
538
       (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
       checkProcessArgsResult unhandled_flags (basename++'.':suff)
539

540
       if not (cppFlag dflags) then
sof's avatar
sof committed
541
542
           -- no need to preprocess CPP, just pass input file along
	   -- to the next phase of the pipeline.
543
          return (HsPp sf, dflags, maybe_loc, input_fn)
sof's avatar
sof committed
544
	else do
545
	    output_fn <- get_output_fn (HsPp sf) maybe_loc
546
	    doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
547
	    return (HsPp sf, dflags, maybe_loc, output_fn)
548

sof's avatar
sof committed
549
550
551
-------------------------------------------------------------------------------
-- HsPp phase 

552
runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
553
  = do if not (ppFlag dflags) then
sof's avatar
sof committed
554
555
           -- no need to preprocess, just pass input file along
	   -- to the next phase of the pipeline.
556
          return (Hsc sf, dflags, maybe_loc, input_fn)
sof's avatar
sof committed
557
	else do
558
	    let hspp_opts = getOpts dflags opt_F
sof's avatar
sof committed
559
       	    hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
560
	    let orig_fn = basename ++ '.':suff
561
	    output_fn <- get_output_fn (Hsc sf) maybe_loc
562
563
	    SysTools.runPp dflags
			   ( [ SysTools.Option     orig_fn
sof's avatar
sof committed
564
565
566
567
568
569
			     , SysTools.Option     input_fn
			     , SysTools.FileOption "" output_fn
			     ] ++
			     map SysTools.Option hs_src_pp_opts ++
			     map SysTools.Option hspp_opts
			   )
570
	    return (Hsc sf, dflags, maybe_loc, output_fn)
571

572
573
574
-----------------------------------------------------------------------------
-- Hsc phase

575
576
-- Compilation of a single module, in "legacy" mode (_not_ under
-- the direction of the compilation manager).
577
runPhase (Hsc src_flavour) stop dflags basename suff input_fn get_output_fn _maybe_loc 
578
 = do	-- normal Hsc mode, not mkdependHS
579

580
581
582
  -- we add the current directory (i.e. the directory in which
  -- the .hs files resides) to the import path, since this is
  -- what gcc does, and it's probably what you want.
583
	let current_dir = directoryOf basename
584
	
585
586
	paths <- readIORef v_Include_paths
	writeIORef v_Include_paths (current_dir : paths)
587
	
588
  -- gather the imports and module name
589
        (hspp_buf,mod_name) <- 
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
            case src_flavour of
		ExtCoreFile -> do {  -- no explicit imports in ExtCore input.
			          ; m <- getCoreModuleName input_fn
			          ; return (Nothing, mkModule m) }

		other -> do { buf <- hGetStringBuffer input_fn
			    ; (_,_,mod_name) <- getImports dflags buf input_fn
			    ; return (Just buf, mod_name) }

  -- Build a ModLocation to pass to hscMain.
  -- The source filename is rather irrelevant by now, but it's used
  -- by hscMain for messages.  hscMain also needs 
  -- the .hi and .o filenames, and this is as good a way
  -- as any to generate them, and better than most. (e.g. takes 
  -- into accout the -osuf flags)
	location1 <- mkHomeModLocation2 mod_name basename suff

  -- Boot-ify it if necessary
	let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
		      | otherwise	     = location1 
					

  -- Take -ohi into account if present
  -- This can't be done in mkHomeModuleLocation because
  -- it only applies to the module being compiles
615
	ohi <- readIORef v_Output_hi
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
	let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
		      | otherwise      = location2

  -- Take -o into account if present
  -- Very like -ohi, but we must *only* do this if we aren't linking
  -- (If we're linking then the -o applies to the linked thing, not to
  -- the object file for one module.)
  -- Note the nasty duplication with the same computation in compileFile above
	expl_o_file <- readIORef v_Output_file
	no_link     <- readIORef v_NoLink
	let location4 | Just ofile <- expl_o_file, no_link 
		      = location3 { ml_obj_file = ofile }
		      | otherwise = location3

  -- Tell the finder cache about this module
	addHomeModuleToFinder mod_name location4

  -- Make the ModSummary to hand to hscMain
	src_timestamp <- getModificationTime (basename ++ '.':suff)
	let
	    unused_field = panic "runPhase:ModSummary field"
		-- Some fields are not looked at by hscMain
	    mod_summary = ModSummary {	ms_mod 	     = mod_name, 
					ms_hsc_src   = src_flavour,
				 	ms_hspp_file = Just input_fn,
					ms_hspp_buf  = hspp_buf,
					ms_location  = location4,
					ms_hs_date   = src_timestamp,
					ms_imps	     = unused_field,
					ms_srcimps   = unused_field }

	    o_file = ml_obj_file location4 	-- The real object file


  -- Figure out if the source has changed, for recompilation avoidance.
651
  --
652
  -- Setting source_unchanged to True means that M.o seems
653
654
  -- to be up to date wrt M.hs; so no need to recompile unless imports have
  -- changed (which the compiler itself figures out).
655
  -- Setting source_unchanged to False tells the compiler that M.o is out of
656
  -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
657
	let do_recomp = recompFlag dflags
658
	source_unchanged <- 
659
660
661
662
663
664
          if not do_recomp || isStopLn stop
		-- Set source_unchanged to False unconditionally if
		--	(a) recompilation checker is off, or
		-- 	(b) we aren't going all the way to .o file (e.g. ghc -S),
	     then return False	
		-- Otherwise look at file modification dates
665
	     else do o_file_exists <- doesFileExist o_file
666
		     if not o_file_exists
667
		        then return False	-- Need to recompile
668
			else do t2 <- getModificationTime o_file
669
			        if t2 > src_timestamp
670
671
				  then return True
				  else return False
672

673
  -- get the DynFlags
674
	hsc_lang   <- hscMaybeAdjustTarget stop src_flavour (hscTarget dflags)
675
676
	next_phase <- hscNextPhase src_flavour hsc_lang
	output_fn  <- get_output_fn next_phase (Just location4)
677

678
        let dflags' = dflags { hscTarget = hsc_lang,
679
680
681
682
			       hscOutName = output_fn,
		   	       hscStubCOutName = basename ++ "_stub.c",
			       hscStubHOutName = basename ++ "_stub.h",
			       extCoreName = basename ++ ".hcr" }
683

684
	hsc_env <- newHscEnv OneShot dflags'
685

686
  -- run the compiler!
687
688
689
690
	result <- hscMain hsc_env printErrorsAndWarnings
			  mod_summary source_unchanged 
			  False		-- No object file
			  Nothing	-- No iface
691

692
	case result of
693

694
	    HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
695

696
            HscNoRecomp details iface -> do
697
		SysTools.touch dflags' "Touching object file" o_file
698
		return (StopLn, dflags', Just location4, o_file)
699

700
701
	    HscRecomp _details _rdr_env _iface 
		      stub_h_exists stub_c_exists
702
		      _maybe_interpreted_code -> do
703

704
		-- Deal with stubs 
705
		maybe_stub_o <- compileStub dflags' stub_c_exists
706
		case maybe_stub_o of
707
		      Nothing     -> return ()
708
		      Just stub_o -> add v_Ld_inputs stub_o
709
710
711
712
713
714
715
716

		-- In the case of hs-boot files, generate a dummy .o-boot 
		-- stamp file for the benefit of Make
		case src_flavour of
		  HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
		  other	     -> return ()

		return (next_phase, dflags', Just location4, output_fn)
717

718
719
720
-----------------------------------------------------------------------------
-- Cmm phase

721
runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
722
723
  = do
       output_fn <- get_output_fn Cmm maybe_loc
724
       doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn	
725
       return (Cmm, dflags, maybe_loc, output_fn)
726

727
runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
728
  = do
729
	hsc_lang <- hscMaybeAdjustTarget stop HsSrcFile (hscTarget dflags)
730
	next_phase <- hscNextPhase HsSrcFile hsc_lang
731
732
	output_fn <- get_output_fn next_phase maybe_loc

733
        let dflags' = dflags { hscTarget = hsc_lang,
734
735
736
737
			       hscOutName = output_fn,
		   	       hscStubCOutName = basename ++ "_stub.c",
			       hscStubHOutName = basename ++ "_stub.h",
			       extCoreName = basename ++ ".hcr" }
738

739
	ok <- hscCmmFile dflags' input_fn
740
741
742

	when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))

743
	return (next_phase, dflags, maybe_loc, output_fn)
744

745
746
747
748
749
750
-----------------------------------------------------------------------------
-- Cc phase

-- we don't support preprocessing .c files (with -E) now.  Doing so introduces
-- way too many hacks, and I can't say I've ever used it anyway.

751
runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
752
   | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
753
   = do	let cc_opts = getOpts dflags opt_c
754
	    hcc = cc_phase `eqPhase` HCc
755

756
       	cmdline_include_paths <- readIORef v_Include_paths
757

758
759
760
761
762
763
	-- HC files have the dependent packages stamped into them
	pkgs <- if hcc then getHCFilePackages input_fn else return []

	-- add package include paths even if we're just compiling .c
	-- files; this is the Value Add(TM) that using ghc instead of
	-- gcc gives you :)
764
        pkg_include_dirs <- getPackageIncludePath dflags pkgs
rrt's avatar
rrt committed
765
766
        let include_paths = foldr (\ x xs -> "-I" : x : xs) []
			      (cmdline_include_paths ++ pkg_include_dirs)
767

768
	(md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
769
        pic_c_flags <- picCCOpts dflags
770

771
        let verb = getVerbFlag dflags
772

773
	pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
774

775
	split_objs <- readIORef v_Split_object_files
sof's avatar
sof committed
776
777
	let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
		      | otherwise         = [ ]
778

779
	excessPrecision <- readIORef v_Excess_precision
780

781
782
783
784
785
786
787
	-- Decide next phase
	mangle <- readIORef v_Do_asm_mangling
        let next_phase
		| hcc && mangle     = Mangle
		| otherwise         = As
	output_fn <- get_output_fn next_phase maybe_loc

788
789
	-- force the C compiler to interpret this file as C when
	-- compiling .hc files, by adding the -x c option.
790
791
	let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
		    | otherwise = [ ]
792

793
	SysTools.runCc dflags (langopt ++
794
			[ SysTools.FileOption "" input_fn
sof's avatar
sof committed
795
			, SysTools.Option "-o"
sof's avatar
sof committed
796
			, SysTools.FileOption "" output_fn
sof's avatar
sof committed
797
798
799
			]
		       ++ map SysTools.Option (
		          md_c_flags
800
                       ++ pic_c_flags
801
		       ++ (if hcc && mangle
802
803
		  	     then md_regd_c_flags
		  	     else [])
804
		       ++ [ verb, "-S", "-Wimplicit", "-O" ]
805
806
		       ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
		       ++ cc_opts
sof's avatar
sof committed
807
		       ++ split_opt
808
809
810
		       ++ (if excessPrecision then [] else [ "-ffloat-store" ])
		       ++ include_paths
		       ++ pkg_extra_cc_opts
sof's avatar
sof committed
811
		       ))
812

813
	return (next_phase, dflags, maybe_loc, output_fn)
814
815
816
817
818
819

	-- ToDo: postprocess the output from gcc

-----------------------------------------------------------------------------
-- Mangle phase

820
runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
821
   = do let mangler_opts = getOpts dflags opt_m
822
823
824
825
826
827

#if i386_TARGET_ARCH
        machdep_opts <- return [ show (stolen_x86_regs dflags) ]
#else
	machdep_opts <- return []
#endif
828
829
830
831
832

	split <- readIORef v_Split_object_files
	let next_phase
		| split = SplitMangle
		| otherwise = As
833
	output_fn <- get_output_fn next_phase maybe_loc
834

835
	SysTools.runMangle dflags (map SysTools.Option mangler_opts
sof's avatar
sof committed
836
837
		          ++ [ SysTools.FileOption "" input_fn
			     , SysTools.FileOption "" output_fn
sof's avatar
sof committed
838
839
			     ]
			  ++ map SysTools.Option machdep_opts)
840

841
	return (next_phase, dflags, maybe_loc, output_fn)
842
843
844
845

-----------------------------------------------------------------------------
-- Splitting phase

846
runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
847
848
849
850
  = do  -- tmp_pfx is the prefix used for the split .s files
	-- We also use it as the file to contain the no. of split .s files (sigh)
	split_s_prefix <- SysTools.newTempName "split"
	let n_files_fn = split_s_prefix
851

852
853
	SysTools.runSplit dflags
			  [ SysTools.FileOption "" input_fn
sof's avatar
sof committed
854
855
			  , SysTools.FileOption "" split_s_prefix
			  , SysTools.FileOption "" n_files_fn
sof's avatar
sof committed
856
			  ]
857
858
859
860
861
862
863
864
865

	-- Save the number of split files for future references
	s <- readFile n_files_fn
	let n_files = read s :: Int
	writeIORef v_Split_info (split_s_prefix, n_files)

	-- Remember to delete all these files
	addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
			| n <- [1..n_files]]
866

867
	return (SplitAs, dflags, maybe_loc, "**splitmangle**")
868
	  -- we don't use the filename
869
870
871
872

-----------------------------------------------------------------------------
-- As phase

873
runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
874
  = do	let as_opts =  getOpts dflags opt_a
875
        cmdline_include_paths <- readIORef v_Include_paths
876

877
	output_fn <- get_output_fn StopLn maybe_loc
878

879
880
881
882
	-- we create directories for the object file, because it
	-- might be a hierarchical module.
	createDirectoryHierarchy (directoryOf output_fn)

883
884
	SysTools.runAs dflags	
		       (map SysTools.Option as_opts
sof's avatar
sof committed
885
886
		       ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
		       ++ [ SysTools.Option "-c"
sof's avatar
sof committed
887
		          , SysTools.FileOption "" input_fn
sof's avatar
sof committed
888
			  , SysTools.Option "-o"
sof's avatar
sof committed
889
			  , SysTools.FileOption "" output_fn
sof's avatar
sof committed
890
			  ])
891

892
	return (StopLn, dflags, maybe_loc, output_fn)
893
894


895
runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
896
  = do  let as_opts = getOpts dflags opt_a
897

898
	(split_s_prefix, n) <- readIORef v_Split_info
899

900
	odir <- readIORef v_Output_dir
901
	let real_odir = case odir of
902
				Nothing -> basename ++ "_split"
903
904
				Just d  -> d

905
906
	let assemble_file n
	      = do  let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
907
		    let output_o = replaceFilenameDirectory
908
					(basename ++ "__" ++ show n ++ ".o")
909
					 real_odir
910
		    real_o <- osuf_ify output_o
911
912
		    SysTools.runAs dflags
				 (map SysTools.Option as_opts ++
sof's avatar
sof committed
913
914
		    		    [ SysTools.Option "-c"
				    , SysTools.Option "-o"
sof's avatar
sof committed
915
916
				    , SysTools.FileOption "" real_o
				    , SysTools.FileOption "" input_s
sof's avatar
sof committed
917
				    ])
918
919
	
	mapM_ assemble_file [1..n]
920

921
922
	output_fn <- get_output_fn StopLn maybe_loc
	return (StopLn, dflags, maybe_loc, output_fn)
923

rrt's avatar
rrt committed
924
925
926
927
928
#ifdef ILX
-----------------------------------------------------------------------------
-- Ilx2Il phase
-- Run ilx2il over the ILX output, getting an IL file

929
runPhase Ilx2Il stop dflags _basename _suff input_fn get_output_fn maybe_loc
930
  = do	let ilx2il_opts = getOpts dflags opt_I
rrt's avatar
rrt committed
931
932
933
934
        SysTools.runIlx2il (map SysTools.Option ilx2il_opts
                           ++ [ SysTools.Option "--no-add-suffix-to-assembly",
				SysTools.Option "mscorlib",
				SysTools.Option "-o",
sof's avatar
sof committed
935
936
				SysTools.FileOption "" output_fn,
				SysTools.FileOption "" input_fn ])
937
	return True
rrt's avatar
rrt committed
938
939
940
941
942

-----------------------------------------------------------------------------
-- Ilasm phase
-- Run ilasm over the IL, getting a DLL

943
runPhase Ilasm stop dflags _basename _suff input_fn get_output_fn maybe_loc
944
  = do	let ilasm_opts = getOpts dflags opt_i
rrt's avatar
rrt committed
945
946
947
        SysTools.runIlasm (map SysTools.Option ilasm_opts
		           ++ [ SysTools.Option "/QUIET",
				SysTools.Option "/DLL",
sof's avatar
sof committed
948
949
				SysTools.FileOption "/OUT=" output_fn,
				SysTools.FileOption "" input_fn ])
950
	return True
rrt's avatar
rrt committed
951

ross's avatar
ross committed
952
#endif /* ILX */
rrt's avatar
rrt committed
953

954
955
956
957
958
959
-----------------------------------------------------------------------------
-- MoveBinary sort-of-phase
-- After having produced a binary, move it somewhere else and generate a
-- wrapper script calling the binary. Currently, we need this only in 
-- a parallel way (i.e. in GUM), because PVM expects the binary in a
-- central directory.
960
-- This is called from staticLink below, after linking. I haven't made it
961
962
963
964
-- a separate phase to minimise interfering with other modules, and
-- we don't need the generality of a phase (MoveBinary is always
-- done after linking and makes only sense in a parallel setup)   -- HWL

965
runPhase_MoveBinary input_fn
966
  = do	
967
        sysMan   <- getSysMan
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019