blob: de4596bf2c0df3d343f7121ae312ca1fc61f3a57 [file] [log] [blame]
Daniel Dunbara5677512009-01-05 19:53:30 +00001import os
Daniel Dunbar9066af82009-01-09 01:00:40 +00002import platform
Daniel Dunbara5677512009-01-05 19:53:30 +00003import sys
4import tempfile
5from pprint import pprint
6
7###
8
9import Arguments
10import Jobs
Daniel Dunbar9066af82009-01-09 01:00:40 +000011import HostInfo
Daniel Dunbara5677512009-01-05 19:53:30 +000012import Phases
13import Tools
14import Types
15import Util
16
17# FIXME: Clean up naming of options and arguments. Decide whether to
18# rename Option and be consistent about use of Option/Arg.
19
20####
21
Daniel Dunbara5677512009-01-05 19:53:30 +000022class Driver(object):
Daniel Dunbar94713452009-01-16 23:12:12 +000023 def __init__(self, driverName, driverDir):
24 self.driverName = driverName
25 self.driverDir = driverDir
Daniel Dunbar9066af82009-01-09 01:00:40 +000026 self.hostInfo = None
Daniel Dunbarba6e3232009-01-06 06:12:13 +000027 self.parser = Arguments.OptionParser()
Daniel Dunbar33a5d612009-01-14 01:03:36 +000028 self.cccHostBits = self.cccHostMachine = None
29 self.cccHostSystem = self.cccHostRelease = None
30 self.cccCXX = False
31 self.cccClang = False
Daniel Dunbarfb7ea272009-01-14 01:32:05 +000032 self.cccEcho = False
Daniel Dunbar33a5d612009-01-14 01:03:36 +000033 self.cccFallback = False
Daniel Dunbara5677512009-01-05 19:53:30 +000034
Daniel Dunbara75ea3d2009-01-09 22:21:24 +000035 # Host queries which can be forcibly over-riden by the user for
36 # testing purposes.
37 #
38 # FIXME: We should make sure these are drawn from a fixed set so
39 # that nothing downstream ever plays a guessing game.
40
41 def getHostBits(self):
42 if self.cccHostBits:
43 return self.cccHostBits
44
45 return platform.architecture()[0].replace('bit','')
46
47 def getHostMachine(self):
48 if self.cccHostMachine:
49 return self.cccHostMachine
50
51 machine = platform.machine()
52 # Normalize names.
53 if machine == 'Power Macintosh':
54 return 'ppc'
55 return machine
56
57 def getHostSystemName(self):
58 if self.cccHostSystem:
59 return self.cccHostSystem
60
61 return platform.system().lower()
62
Daniel Dunbar9c257c32009-01-12 04:21:12 +000063 def getHostReleaseName(self):
64 if self.cccHostRelease:
65 return self.cccHostRelease
66
67 return platform.release()
68
Daniel Dunbarfb7ea272009-01-14 01:32:05 +000069 def getenvBool(self, name):
70 var = os.getenv(name)
71 if not var:
72 return False
73
74 try:
75 return bool(int(var))
76 except:
77 return False
78
Daniel Dunbara75ea3d2009-01-09 22:21:24 +000079 ###
80
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +000081 def run(self, argv):
Daniel Dunbara5677512009-01-05 19:53:30 +000082 # FIXME: Things to support from environment: GCC_EXEC_PREFIX,
83 # COMPILER_PATH, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS,
84 # QA_OVERRIDE_GCC3_OPTIONS, ...?
85
86 # FIXME: -V and -b processing
87
88 # Handle some special -ccc- options used for testing which are
89 # only allowed at the beginning of the command line.
90 cccPrintOptions = False
91 cccPrintPhases = False
Daniel Dunbara75ea3d2009-01-09 22:21:24 +000092
93 # FIXME: How to handle override of host? ccc specific options?
94 # Abuse -b?
Daniel Dunbarfb7ea272009-01-14 01:32:05 +000095 if self.getenvBool('CCC_CLANG'):
96 self.cccClang = True
97 if self.getenvBool('CCC_ECHO'):
98 self.cccEcho = True
99 if self.getenvBool('CCC_FALLBACK'):
100 self.cccFallback = True
101
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000102 while argv and argv[0].startswith('-ccc-'):
Daniel Dunbar94713452009-01-16 23:12:12 +0000103 fullOpt,argv = argv[0],argv[1:]
104 opt = fullOpt[5:]
Daniel Dunbara5677512009-01-05 19:53:30 +0000105
106 if opt == 'print-options':
107 cccPrintOptions = True
108 elif opt == 'print-phases':
109 cccPrintPhases = True
Daniel Dunbar33a5d612009-01-14 01:03:36 +0000110 elif opt == 'cxx':
111 self.cccCXX = True
112 elif opt == 'clang':
113 self.cccClang = True
Daniel Dunbarfb7ea272009-01-14 01:32:05 +0000114 elif opt == 'echo':
115 self.cccEcho = True
Daniel Dunbar33a5d612009-01-14 01:03:36 +0000116 elif opt == 'fallback':
117 self.cccFallback = True
Daniel Dunbar9066af82009-01-09 01:00:40 +0000118 elif opt == 'host-bits':
Daniel Dunbara75ea3d2009-01-09 22:21:24 +0000119 self.cccHostBits,argv = argv[0],argv[1:]
Daniel Dunbar9066af82009-01-09 01:00:40 +0000120 elif opt == 'host-machine':
Daniel Dunbara75ea3d2009-01-09 22:21:24 +0000121 self.cccHostMachine,argv = argv[0],argv[1:]
Daniel Dunbar9066af82009-01-09 01:00:40 +0000122 elif opt == 'host-system':
Daniel Dunbara75ea3d2009-01-09 22:21:24 +0000123 self.cccHostSystem,argv = argv[0],argv[1:]
Daniel Dunbar9c257c32009-01-12 04:21:12 +0000124 elif opt == 'host-release':
125 self.cccHostRelease,argv = argv[0],argv[1:]
Daniel Dunbara5677512009-01-05 19:53:30 +0000126 else:
Daniel Dunbar94713452009-01-16 23:12:12 +0000127 raise Arguments.InvalidArgumentsError("invalid option: %r" % fullOpt)
Daniel Dunbara5677512009-01-05 19:53:30 +0000128
Daniel Dunbara75ea3d2009-01-09 22:21:24 +0000129 self.hostInfo = HostInfo.getHostInfo(self)
Daniel Dunbar43124722009-01-10 02:07:54 +0000130 self.toolChain = self.hostInfo.getToolChain()
Daniel Dunbar9066af82009-01-09 01:00:40 +0000131
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000132 args = self.parser.parseArgs(argv)
Daniel Dunbara5677512009-01-05 19:53:30 +0000133
134 # FIXME: Ho hum I have just realized -Xarch_ is broken. We really
135 # need to reparse the Arguments after they have been expanded by
136 # -Xarch. How is this going to work?
137 #
138 # Scratch that, we aren't going to do that; it really disrupts the
139 # organization, doesn't consistently work with gcc-dd, and is
140 # confusing. Instead we are going to enforce that -Xarch_ is only
141 # used with options which do not alter the driver behavior. Let's
142 # hope this is ok, because the current architecture is a little
143 # tied to it.
144
145 if cccPrintOptions:
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000146 self.printOptions(args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000147 sys.exit(0)
148
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000149 self.handleImmediateOptions(args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000150
Daniel Dunbar9066af82009-01-09 01:00:40 +0000151 if self.hostInfo.useDriverDriver():
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000152 phases = self.buildPipeline(args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000153 else:
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000154 phases = self.buildNormalPipeline(args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000155
156 if cccPrintPhases:
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000157 self.printPhases(phases, args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000158 sys.exit(0)
Daniel Dunbar9066af82009-01-09 01:00:40 +0000159
Daniel Dunbara5677512009-01-05 19:53:30 +0000160 if 0:
161 print Util.pprint(phases)
162
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000163 jobs = self.bindPhases(phases, args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000164
165 # FIXME: We should provide some basic sanity checking of the
166 # pipeline as a "verification" sort of stage. For example, the
167 # pipeline should never end up writing to an output file in two
168 # places (I think). The pipeline should also never end up writing
169 # to an output file that is an input.
170 #
171 # This is intended to just be a "verify" step, not a functionality
172 # step. It should catch things like the driver driver not
173 # preventing -save-temps, but it shouldn't change behavior (so we
174 # can turn it off in Release-Asserts builds).
175
176 # Print in -### syntax.
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000177 hasHashHashHash = args.getLastArg(self.parser.hashHashHashOption)
Daniel Dunbara5677512009-01-05 19:53:30 +0000178 if hasHashHashHash:
179 self.claim(hasHashHashHash)
180 for j in jobs.iterjobs():
181 if isinstance(j, Jobs.Command):
Daniel Dunbar3ecc20f2009-01-12 19:36:35 +0000182 print >>sys.stderr, ' "%s"' % '" "'.join(j.getArgv())
Daniel Dunbara5677512009-01-05 19:53:30 +0000183 elif isinstance(j, Jobs.PipedJob):
184 for c in j.commands:
Daniel Dunbar3ecc20f2009-01-12 19:36:35 +0000185 print >>sys.stderr, ' "%s" %c' % ('" "'.join(c.getArgv()),
186 "| "[c is j.commands[-1]])
Daniel Dunbara5677512009-01-05 19:53:30 +0000187 elif not isinstance(j, JobList):
188 raise ValueError,'Encountered unknown job.'
189 sys.exit(0)
190
191 for j in jobs.iterjobs():
192 if isinstance(j, Jobs.Command):
Daniel Dunbarfb7ea272009-01-14 01:32:05 +0000193 if self.cccEcho:
Anders Carlsson0f7d9ec2009-01-18 02:54:17 +0000194 print >>sys.stderr, ' '.join(map(repr,j.getArgv()))
195 sys.stderr.flush()
Daniel Dunbardb439902009-01-07 18:40:45 +0000196 res = os.spawnvp(os.P_WAIT, j.executable, j.getArgv())
Daniel Dunbara5677512009-01-05 19:53:30 +0000197 if res:
198 sys.exit(res)
199 elif isinstance(j, Jobs.PipedJob):
Daniel Dunbar7d791fd2009-01-17 02:02:35 +0000200 import subprocess
201 procs = []
202 for sj in j.commands:
203 if self.cccEcho:
Anders Carlsson0f7d9ec2009-01-18 02:54:17 +0000204 print >> sys.stderr, ' '.join(map(repr,sj.getArgv()))
Daniel Dunbar7d791fd2009-01-17 02:02:35 +0000205 sys.stdout.flush()
206
207 if not procs:
208 stdin = None
209 else:
210 stdin = procs[-1].stdout
211 if sj is j.commands[-1]:
212 stdout = None
213 else:
214 stdout = subprocess.PIPE
215 procs.append(subprocess.Popen(sj.getArgv(),
216 executable=sj.executable,
217 stdin=stdin,
218 stdout=stdout))
219 for proc in procs:
220 res = proc.wait()
221 if res:
222 sys.exit(res)
Daniel Dunbara5677512009-01-05 19:53:30 +0000223 else:
224 raise ValueError,'Encountered unknown job.'
225
226 def claim(self, option):
227 # FIXME: Move to OptionList once introduced and implement.
228 pass
229
230 def warning(self, message):
Daniel Dunbar94713452009-01-16 23:12:12 +0000231 print >>sys.stderr,'%s: %s' % (self.driverName, message)
Daniel Dunbara5677512009-01-05 19:53:30 +0000232
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000233 def printOptions(self, args):
234 for i,arg in enumerate(args):
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000235 if isinstance(arg, Arguments.MultipleValuesArg):
236 values = list(args.getValues(arg))
237 elif isinstance(arg, Arguments.ValueArg):
238 values = [args.getValue(arg)]
239 elif isinstance(arg, Arguments.JoinedAndSeparateValuesArg):
240 values = [args.getJoinedValue(arg), args.getSeparateValue(arg)]
Daniel Dunbara5677512009-01-05 19:53:30 +0000241 else:
242 values = []
Daniel Dunbar5039f212009-01-06 02:30:10 +0000243 print 'Option %d - Name: "%s", Values: {%s}' % (i, arg.opt.name,
Daniel Dunbara5677512009-01-05 19:53:30 +0000244 ', '.join(['"%s"' % v
245 for v in values]))
246
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000247 def printPhases(self, phases, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000248 def printPhase(p, f, steps, arch=None):
249 if p in steps:
250 return steps[p]
251 elif isinstance(p, Phases.BindArchAction):
252 for kid in p.inputs:
253 printPhase(kid, f, steps, p.arch)
254 steps[p] = len(steps)
255 return
256
257 if isinstance(p, Phases.InputAction):
258 phaseName = 'input'
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000259 inputStr = '"%s"' % args.getValue(p.filename)
Daniel Dunbara5677512009-01-05 19:53:30 +0000260 else:
261 phaseName = p.phase.name
262 inputs = [printPhase(i, f, steps, arch)
263 for i in p.inputs]
264 inputStr = '{%s}' % ', '.join(map(str, inputs))
265 if arch is not None:
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000266 phaseName += '-' + args.getValue(arch)
Daniel Dunbara5677512009-01-05 19:53:30 +0000267 steps[p] = index = len(steps)
268 print "%d: %s, %s, %s" % (index,phaseName,inputStr,p.type.name)
269 return index
270 steps = {}
271 for phase in phases:
272 printPhase(phase, sys.stdout, steps)
273
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000274 def handleImmediateOptions(self, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000275 # FIXME: Some driver Arguments are consumed right off the bat,
276 # like -dumpversion. Currently the gcc-dd handles these
277 # poorly, so we should be ok handling them upfront instead of
278 # after driver-driver level dispatching.
279 #
280 # FIXME: The actual order of these options in gcc is all over the
281 # place. The -dump ones seem to be first and in specification
282 # order, but there are other levels of precedence. For example,
283 # -print-search-dirs is evaluated before -print-prog-name=,
284 # regardless of order (and the last instance of -print-prog-name=
285 # wins verse itself).
286 #
287 # FIXME: Do we want to report "argument unused" type errors in the
288 # presence of things like -dumpmachine and -print-search-dirs?
289 # Probably not.
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000290 arg = args.getLastArg(self.parser.dumpmachineOption)
291 if arg:
292 print 'FIXME: %s' % arg.opt.name
293 sys.exit(1)
294
295 arg = args.getLastArg(self.parser.dumpspecsOption)
296 if arg:
297 print 'FIXME: %s' % arg.opt.name
298 sys.exit(1)
299
300 arg = args.getLastArg(self.parser.dumpversionOption)
301 if arg:
302 print 'FIXME: %s' % arg.opt.name
303 sys.exit(1)
304
305 arg = args.getLastArg(self.parser.printFileNameOption)
306 if arg:
307 print 'FIXME: %s' % arg.opt.name
308 sys.exit(1)
309
310 arg = args.getLastArg(self.parser.printMultiDirectoryOption)
311 if arg:
312 print 'FIXME: %s' % arg.opt.name
313 sys.exit(1)
314
315 arg = args.getLastArg(self.parser.printMultiLibOption)
316 if arg:
317 print 'FIXME: %s' % arg.opt.name
318 sys.exit(1)
319
320 arg = args.getLastArg(self.parser.printProgNameOption)
321 if arg:
322 print 'FIXME: %s' % arg.opt.name
323 sys.exit(1)
324
325 arg = args.getLastArg(self.parser.printLibgccFilenameOption)
326 if arg:
327 print 'FIXME: %s' % arg.opt.name
328 sys.exit(1)
329
330 arg = args.getLastArg(self.parser.printSearchDirsOption)
331 if arg:
332 print 'FIXME: %s' % arg.opt.name
333 sys.exit(1)
Daniel Dunbara5677512009-01-05 19:53:30 +0000334
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000335 def buildNormalPipeline(self, args):
Daniel Dunbarde388a52009-01-21 01:07:49 +0000336 hasAnalyze = args.getLastArg(self.parser.analyzeOption)
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000337 hasCombine = args.getLastArg(self.parser.combineOption)
338 hasSyntaxOnly = args.getLastArg(self.parser.syntaxOnlyOption)
339 hasDashC = args.getLastArg(self.parser.cOption)
340 hasDashE = args.getLastArg(self.parser.EOption)
341 hasDashS = args.getLastArg(self.parser.SOption)
Daniel Dunbarfce72bc2009-01-20 01:53:54 +0000342 hasDashM = args.getLastArg(self.parser.MOption)
343 hasDashMM = args.getLastArg(self.parser.MMOption)
Daniel Dunbara5677512009-01-05 19:53:30 +0000344
345 inputType = None
346 inputTypeOpt = None
347 inputs = []
348 for a in args:
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000349 if a.opt is self.parser.inputOption:
Daniel Dunbar94713452009-01-16 23:12:12 +0000350 inputValue = args.getValue(a)
Daniel Dunbara5677512009-01-05 19:53:30 +0000351 if inputType is None:
Daniel Dunbar94713452009-01-16 23:12:12 +0000352 base,ext = os.path.splitext(inputValue)
Daniel Dunbara5677512009-01-05 19:53:30 +0000353 if ext and ext in Types.kTypeSuffixMap:
354 klass = Types.kTypeSuffixMap[ext]
355 else:
356 # FIXME: Its not clear why we shouldn't just
357 # revert to unknown. I think this is more likely a
358 # bug / unintended behavior in gcc. Not very
359 # important though.
360 klass = Types.ObjectType
361 else:
362 assert inputTypeOpt is not None
363 self.claim(inputTypeOpt)
364 klass = inputType
Daniel Dunbar94713452009-01-16 23:12:12 +0000365
366 # Check that the file exists. It isn't clear this is
367 # worth doing, since the tool presumably does this
368 # anyway, and this just adds an extra stat to the
369 # equation, but this is gcc compatible.
370 if not os.path.exists(inputValue):
371 self.warning("%s: No such file or directory" % inputValue)
372 else:
373 inputs.append((klass, a))
Daniel Dunbar2ec55bc2009-01-12 03:33:58 +0000374 elif a.opt.isLinkerInput:
375 # Treat as a linker input.
Daniel Dunbar5039f212009-01-06 02:30:10 +0000376 #
377 # FIXME: This might not be good enough. We may
378 # need to introduce another type for this case, so
379 # that other code which needs to know the inputs
380 # handles this properly. Best not to try and lipo
381 # this, for example.
382 inputs.append((Types.ObjectType, a))
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000383 elif a.opt is self.parser.xOption:
Daniel Dunbar5039f212009-01-06 02:30:10 +0000384 inputTypeOpt = a
385 value = args.getValue(a)
386 if value in Types.kTypeSpecifierMap:
387 inputType = Types.kTypeSpecifierMap[value]
388 else:
389 # FIXME: How are we going to handle diagnostics.
390 self.warning("language %s not recognized" % value)
Daniel Dunbara5677512009-01-05 19:53:30 +0000391
Daniel Dunbar5039f212009-01-06 02:30:10 +0000392 # FIXME: Its not clear why we shouldn't just
393 # revert to unknown. I think this is more likely a
394 # bug / unintended behavior in gcc. Not very
395 # important though.
Daniel Dunbar25d4a8f2009-01-13 21:07:43 +0000396 inputType = Types.ObjectType
Daniel Dunbara5677512009-01-05 19:53:30 +0000397
398 # We claim things here so that options for which we silently allow
399 # override only ever claim the used option.
400 if hasCombine:
401 self.claim(hasCombine)
402
403 finalPhase = Phases.Phase.eOrderPostAssemble
404 finalPhaseOpt = None
405
406 # Determine what compilation mode we are in.
Daniel Dunbarfce72bc2009-01-20 01:53:54 +0000407 if hasDashE or hasDashM or hasDashMM:
Daniel Dunbara5677512009-01-05 19:53:30 +0000408 finalPhase = Phases.Phase.eOrderPreprocess
409 finalPhaseOpt = hasDashE
Daniel Dunbarde388a52009-01-21 01:07:49 +0000410 elif hasAnalyze:
411 finalPhase = Phases.Phase.eOrderCompile
412 finalPhaseOpt = hasAnalyze
Daniel Dunbara5677512009-01-05 19:53:30 +0000413 elif hasSyntaxOnly:
414 finalPhase = Phases.Phase.eOrderCompile
415 finalPhaseOpt = hasSyntaxOnly
416 elif hasDashS:
417 finalPhase = Phases.Phase.eOrderCompile
418 finalPhaseOpt = hasDashS
419 elif hasDashC:
420 finalPhase = Phases.Phase.eOrderAssemble
421 finalPhaseOpt = hasDashC
422
423 if finalPhaseOpt:
424 self.claim(finalPhaseOpt)
425
426 # FIXME: Support -combine.
427 if hasCombine:
Daniel Dunbar94713452009-01-16 23:12:12 +0000428 raise NotImplementedError,"-combine is not yet supported"
429
Daniel Dunbar470104e2009-01-17 00:53:19 +0000430 # Reject -Z* at the top level for now.
431 arg = args.getLastArg(self.parser.ZOption)
432 if arg:
433 raise Arguments.InvalidArgumentsError("%s: unsupported use of internal gcc option" % ' '.join(args.render(arg)))
434
Daniel Dunbar94713452009-01-16 23:12:12 +0000435 if (not inputs and
436 not args.getLastArg(self.parser.hashHashHashOption)):
437 raise Arguments.InvalidArgumentsError("no input files")
Daniel Dunbara5677512009-01-05 19:53:30 +0000438
439 actions = []
440 linkerInputs = []
441 # FIXME: This is gross.
442 linkPhase = Phases.LinkPhase()
443 for klass,input in inputs:
444 # Figure out what step to start at.
445
446 # FIXME: This should be part of the input class probably?
447 # Altough it doesn't quite fit there either, things like
448 # asm-with-preprocess don't easily fit into a linear scheme.
449
450 # FIXME: I think we are going to end up wanting to just build
451 # a simple FSA which we run the inputs down.
452 sequence = []
453 if klass.preprocess:
454 sequence.append(Phases.PreprocessPhase())
455 if klass == Types.ObjectType:
456 sequence.append(linkPhase)
457 elif klass.onlyAssemble:
458 sequence.extend([Phases.AssemblePhase(),
459 linkPhase])
460 elif klass.onlyPrecompile:
461 sequence.append(Phases.PrecompilePhase())
Daniel Dunbarde388a52009-01-21 01:07:49 +0000462 elif hasAnalyze:
463 sequence.append(Phases.AnalyzePhase())
464 elif hasSyntaxOnly:
465 sequence.append(Phases.SyntaxOnlyPhase())
Daniel Dunbara5677512009-01-05 19:53:30 +0000466 else:
467 sequence.extend([Phases.CompilePhase(),
468 Phases.AssemblePhase(),
469 linkPhase])
470
471 if sequence[0].order > finalPhase:
472 assert finalPhaseOpt and finalPhaseOpt.opt
473 # FIXME: Explain what type of input file is. Or just match
474 # gcc warning.
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000475 self.warning("%s: %s input file unused when %s is present" % (args.getValue(input),
Daniel Dunbara5677512009-01-05 19:53:30 +0000476 sequence[0].name,
477 finalPhaseOpt.opt.name))
478 else:
479 # Build the pipeline for this file.
480
481 current = Phases.InputAction(input, klass)
482 for transition in sequence:
483 # If the current action produces no output, or we are
484 # past what the user requested, we are done.
485 if (current.type is Types.NothingType or
486 transition.order > finalPhase):
487 break
488 else:
489 if isinstance(transition, Phases.PreprocessPhase):
490 assert isinstance(klass.preprocess, Types.InputType)
491 current = Phases.JobAction(transition,
492 [current],
493 klass.preprocess)
494 elif isinstance(transition, Phases.PrecompilePhase):
495 current = Phases.JobAction(transition,
496 [current],
497 Types.PCHType)
Daniel Dunbarde388a52009-01-21 01:07:49 +0000498 elif isinstance(transition, Phases.AnalyzePhase):
499 output = Types.PlistType
500 current = Phases.JobAction(transition,
501 [current],
502 output)
503 elif isinstance(transition, Phases.SyntaxOnlyPhase):
504 output = Types.NothingType
505 current = Phases.JobAction(transition,
506 [current],
507 output)
Daniel Dunbara5677512009-01-05 19:53:30 +0000508 elif isinstance(transition, Phases.CompilePhase):
Daniel Dunbarde388a52009-01-21 01:07:49 +0000509 output = Types.AsmTypeNoPP
Daniel Dunbara5677512009-01-05 19:53:30 +0000510 current = Phases.JobAction(transition,
511 [current],
512 output)
513 elif isinstance(transition, Phases.AssemblePhase):
514 current = Phases.JobAction(transition,
515 [current],
516 Types.ObjectType)
517 elif transition is linkPhase:
518 linkerInputs.append(current)
519 current = None
520 break
521 else:
522 raise RuntimeError,'Unrecognized transition: %s.' % transition
523 pass
524
525 if current is not None:
526 assert not isinstance(current, Phases.InputAction)
527 actions.append(current)
528
529 if linkerInputs:
530 actions.append(Phases.JobAction(linkPhase,
531 linkerInputs,
532 Types.ImageType))
533
534 return actions
535
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000536 def buildPipeline(self, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000537 # FIXME: We need to handle canonicalization of the specified arch.
538
Daniel Dunbar7c584962009-01-20 21:29:14 +0000539 archs = {}
Daniel Dunbarfce72bc2009-01-20 01:53:54 +0000540 hasDashM = args.getLastArg(self.parser.MGroup)
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000541 hasSaveTemps = (args.getLastArg(self.parser.saveTempsOption) or
542 args.getLastArg(self.parser.saveTempsOption2))
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000543 for arg in args:
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000544 if arg.opt is self.parser.archOption:
Daniel Dunbar7c584962009-01-20 21:29:14 +0000545 # FIXME: Canonicalize this.
546 archName = args.getValue(arg)
547 archs[archName] = arg
548
549 archs = archs.values()
Daniel Dunbara5677512009-01-05 19:53:30 +0000550 if not archs:
Daniel Dunbar1f73ecb2009-01-13 04:05:40 +0000551 archs.append(args.makeSeparateArg(self.hostInfo.getArchName(args),
Daniel Dunbar39cbfaa2009-01-07 18:54:26 +0000552 self.parser.archOption))
Daniel Dunbara5677512009-01-05 19:53:30 +0000553
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000554 actions = self.buildNormalPipeline(args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000555
556 # FIXME: Use custom exception for this.
557 #
558 # FIXME: We killed off some others but these aren't yet detected in
559 # a functional manner. If we added information to jobs about which
560 # "auxiliary" files they wrote then we could detect the conflict
561 # these cause downstream.
562 if len(archs) > 1:
563 if hasDashM:
Daniel Dunbar94713452009-01-16 23:12:12 +0000564 raise Arguments.InvalidArgumentsError("Cannot use -M options with multiple arch flags.")
Daniel Dunbara5677512009-01-05 19:53:30 +0000565 elif hasSaveTemps:
Daniel Dunbar94713452009-01-16 23:12:12 +0000566 raise Arguments.InvalidArgumentsError("Cannot use -save-temps with multiple arch flags.")
Daniel Dunbara5677512009-01-05 19:53:30 +0000567
568 # Execute once per arch.
569 finalActions = []
570 for p in actions:
571 # Make sure we can lipo this kind of output. If not (and it
572 # is an actual output) then we disallow, since we can't
573 # create an output file with the right name without
574 # overwriting it. We could remove this oddity by just
575 # changing the output names to include the arch, which would
576 # also fix -save-temps. Compatibility wins for now.
577 #
578 # FIXME: Is this error substantially less useful than
579 # gcc-dd's? The main problem is that "Cannot use compiler
580 # output with multiple arch flags" won't make sense to most
581 # developers.
582 if (len(archs) > 1 and
583 p.type not in (Types.NothingType,Types.ObjectType,Types.ImageType)):
Daniel Dunbar94713452009-01-16 23:12:12 +0000584 raise Arguments.InvalidArgumentsError('Cannot use %s output with multiple arch flags.' % p.type.name)
Daniel Dunbara5677512009-01-05 19:53:30 +0000585
586 inputs = []
587 for arch in archs:
588 inputs.append(Phases.BindArchAction(p, arch))
589
590 # Lipo if necessary. We do it this way because we need to set
591 # the arch flag so that -Xarch_ gets rewritten.
592 if len(inputs) == 1 or p.type == Types.NothingType:
593 finalActions.extend(inputs)
594 else:
595 finalActions.append(Phases.JobAction(Phases.LipoPhase(),
596 inputs,
597 p.type))
598
Daniel Dunbara5677512009-01-05 19:53:30 +0000599 return finalActions
600
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000601 def bindPhases(self, phases, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000602 jobs = Jobs.JobList()
603
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000604 finalOutput = args.getLastArg(self.parser.oOption)
605 hasSaveTemps = (args.getLastArg(self.parser.saveTempsOption) or
606 args.getLastArg(self.parser.saveTempsOption2))
607 hasNoIntegratedCPP = args.getLastArg(self.parser.noIntegratedCPPOption)
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000608 hasTraditionalCPP = args.getLastArg(self.parser.traditionalCPPOption)
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000609 hasPipe = args.getLastArg(self.parser.pipeOption)
Daniel Dunbar2ec55bc2009-01-12 03:33:58 +0000610
Daniel Dunbara5677512009-01-05 19:53:30 +0000611 # We claim things here so that options for which we silently allow
612 # override only ever claim the used option.
613 if hasPipe:
614 self.claim(hasPipe)
615 # FIXME: Hack, override -pipe till we support it.
Daniel Dunbar7d791fd2009-01-17 02:02:35 +0000616 if hasSaveTemps:
617 self.warning('-pipe ignored because -save-temps specified')
618 hasPipe = None
Daniel Dunbara5677512009-01-05 19:53:30 +0000619 # Claim these here. Its not completely accurate but any warnings
620 # about these being unused are likely to be noise anyway.
621 if hasSaveTemps:
622 self.claim(hasSaveTemps)
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000623
624 if hasTraditionalCPP:
625 self.claim(hasTraditionalCPP)
626 elif hasNoIntegratedCPP:
Daniel Dunbara5677512009-01-05 19:53:30 +0000627 self.claim(hasNoIntegratedCPP)
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000628
Daniel Dunbar76290532009-01-13 06:25:31 +0000629 # FIXME: Move to... somewhere else.
Daniel Dunbara5677512009-01-05 19:53:30 +0000630 class InputInfo:
631 def __init__(self, source, type, baseInput):
632 self.source = source
633 self.type = type
634 self.baseInput = baseInput
635
636 def __repr__(self):
637 return '%s(%r, %r, %r)' % (self.__class__.__name__,
638 self.source, self.type, self.baseInput)
Daniel Dunbar76290532009-01-13 06:25:31 +0000639
640 def isOriginalInput(self):
641 return self.source is self.baseInput
Daniel Dunbara5677512009-01-05 19:53:30 +0000642
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000643 def createJobs(tc, phase,
644 canAcceptPipe=False, atTopLevel=False, arch=None,
Daniel Dunbar7c584962009-01-20 21:29:14 +0000645 tcArgs=None, linkingOutput=None):
Daniel Dunbara5677512009-01-05 19:53:30 +0000646 if isinstance(phase, Phases.InputAction):
647 return InputInfo(phase.filename, phase.type, phase.filename)
648 elif isinstance(phase, Phases.BindArchAction):
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000649 archName = args.getValue(phase.arch)
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000650 tc = self.hostInfo.getToolChainForArch(archName)
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000651 return createJobs(tc, phase.inputs[0],
652 canAcceptPipe, atTopLevel, phase.arch,
Daniel Dunbar7c584962009-01-20 21:29:14 +0000653 None, linkingOutput)
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000654
655 if tcArgs is None:
656 tcArgs = tc.translateArgs(args, arch)
Daniel Dunbara5677512009-01-05 19:53:30 +0000657
658 assert isinstance(phase, Phases.JobAction)
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000659 tool = tc.selectTool(phase)
Daniel Dunbara5677512009-01-05 19:53:30 +0000660
661 # See if we should use an integrated CPP. We only use an
662 # integrated cpp when we have exactly one input, since this is
663 # the only use case we care about.
664 useIntegratedCPP = False
665 inputList = phase.inputs
666 if (not hasNoIntegratedCPP and
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000667 not hasTraditionalCPP and
Daniel Dunbara5677512009-01-05 19:53:30 +0000668 not hasSaveTemps and
669 tool.hasIntegratedCPP()):
670 if (len(phase.inputs) == 1 and
Daniel Dunbar06172d62009-01-20 00:47:24 +0000671 isinstance(phase.inputs[0], Phases.JobAction) and
Daniel Dunbara5677512009-01-05 19:53:30 +0000672 isinstance(phase.inputs[0].phase, Phases.PreprocessPhase)):
673 useIntegratedCPP = True
674 inputList = phase.inputs[0].inputs
675
676 # Only try to use pipes when exactly one input.
677 canAcceptPipe = len(inputList) == 1 and tool.acceptsPipedInput()
Daniel Dunbar7c584962009-01-20 21:29:14 +0000678 inputs = [createJobs(tc, p, canAcceptPipe, False,
679 arch, tcArgs, linkingOutput)
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000680 for p in inputList]
Daniel Dunbara5677512009-01-05 19:53:30 +0000681
682 # Determine if we should output to a pipe.
683 canOutputToPipe = canAcceptPipe and tool.canPipeOutput()
684 outputToPipe = False
685 if canOutputToPipe:
686 # Some things default to writing to a pipe if the final
687 # phase and there was no user override.
688 #
689 # FIXME: What is the best way to handle this?
Daniel Dunbaraf44a622009-01-18 21:35:24 +0000690 if atTopLevel:
691 if (isinstance(phase.phase, Phases.PreprocessPhase) and
692 not finalOutput):
693 outputToPipe = True
Daniel Dunbara5677512009-01-05 19:53:30 +0000694 elif hasPipe:
695 outputToPipe = True
696
697 # Figure out where to put the job (pipes).
698 jobList = jobs
699 if canAcceptPipe and isinstance(inputs[0].source, Jobs.PipedJob):
700 jobList = inputs[0].source
Daniel Dunbar7c584962009-01-20 21:29:14 +0000701
Daniel Dunbara5677512009-01-05 19:53:30 +0000702 baseInput = inputs[0].baseInput
Daniel Dunbarf93ebd92009-01-21 00:05:15 +0000703 output,jobList = self.getOutputName(phase, outputToPipe, jobs, jobList, baseInput,
704 args, atTopLevel, hasSaveTemps, finalOutput)
Daniel Dunbardb439902009-01-07 18:40:45 +0000705 tool.constructJob(phase, arch, jobList, inputs, output, phase.type,
Daniel Dunbar7c584962009-01-20 21:29:14 +0000706 tcArgs, linkingOutput)
Daniel Dunbara5677512009-01-05 19:53:30 +0000707
708 return InputInfo(output, phase.type, baseInput)
709
710 # It is an error to provide a -o option if we are making multiple
711 # output files.
712 if finalOutput and len([a for a in phases if a.type is not Types.NothingType]) > 1:
Daniel Dunbar94713452009-01-16 23:12:12 +0000713 raise Arguments.InvalidArgumentsError("cannot specify -o when generating multiple files")
Daniel Dunbara5677512009-01-05 19:53:30 +0000714
715 for phase in phases:
Daniel Dunbar7c584962009-01-20 21:29:14 +0000716 # If we are linking an image for multiple archs then the
717 # linker wants -arch_multiple and -final_output <final image
718 # name>. Unfortunately this requires some gross contortions.
719 #
720 # FIXME: This is a hack; find a cleaner way to integrate this
721 # into the process.
722 linkingOutput = None
723 if (isinstance(phase, Phases.JobAction) and
724 isinstance(phase.phase, Phases.LipoPhase)):
725 finalOutput = args.getLastArg(self.parser.oOption)
726 if finalOutput:
727 linkingOutput = finalOutput
728 else:
729 linkingOutput = args.makeSeparateArg('a.out',
730 self.parser.oOption)
731
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000732 createJobs(self.toolChain, phase,
Daniel Dunbar7c584962009-01-20 21:29:14 +0000733 canAcceptPipe=True, atTopLevel=True,
734 linkingOutput=linkingOutput)
Daniel Dunbara5677512009-01-05 19:53:30 +0000735
736 return jobs
Daniel Dunbar7c584962009-01-20 21:29:14 +0000737
738 def getOutputName(self, phase, outputToPipe, jobs, jobList, baseInput,
739 args, atTopLevel, hasSaveTemps, finalOutput):
740 # Figure out where to put the output.
741 if phase.type == Types.NothingType:
742 output = None
743 elif outputToPipe:
744 if isinstance(jobList, Jobs.PipedJob):
745 output = jobList
746 else:
747 jobList = output = Jobs.PipedJob([])
748 jobs.addJob(output)
749 else:
750 # Figure out what the derived output location would be.
751 #
752 # FIXME: gcc has some special case in here so that it doesn't
753 # create output files if they would conflict with an input.
754 if phase.type is Types.ImageType:
755 namedOutput = "a.out"
756 else:
757 inputName = args.getValue(baseInput)
758 base,_ = os.path.splitext(inputName)
759 assert phase.type.tempSuffix is not None
760 namedOutput = base + '.' + phase.type.tempSuffix
761
762 # Output to user requested destination?
763 if atTopLevel and finalOutput:
764 output = finalOutput
765 # Contruct a named destination?
766 elif atTopLevel or hasSaveTemps:
767 # As an annoying special case, pch generation
768 # doesn't strip the pathname.
769 if phase.type is Types.PCHType:
770 outputName = namedOutput
771 else:
772 outputName = os.path.basename(namedOutput)
773 output = args.makeSeparateArg(outputName,
774 self.parser.oOption)
775 else:
776 # Output to temp file...
777 fd,filename = tempfile.mkstemp(suffix='.'+phase.type.tempSuffix)
778 output = args.makeSeparateArg(filename,
779 self.parser.oOption)
Daniel Dunbarf93ebd92009-01-21 00:05:15 +0000780 return output,jobList