blob: 427bc0ea6761a4e8a18a61724866ed8bdfb7409e [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:
194 print ' '.join(map(repr,j.getArgv()))
195 sys.stdout.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):
200 raise NotImplementedError,"Piped jobs aren't implemented yet."
201 else:
202 raise ValueError,'Encountered unknown job.'
203
204 def claim(self, option):
205 # FIXME: Move to OptionList once introduced and implement.
206 pass
207
208 def warning(self, message):
Daniel Dunbar94713452009-01-16 23:12:12 +0000209 print >>sys.stderr,'%s: %s' % (self.driverName, message)
Daniel Dunbara5677512009-01-05 19:53:30 +0000210
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000211 def printOptions(self, args):
212 for i,arg in enumerate(args):
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000213 if isinstance(arg, Arguments.MultipleValuesArg):
214 values = list(args.getValues(arg))
215 elif isinstance(arg, Arguments.ValueArg):
216 values = [args.getValue(arg)]
217 elif isinstance(arg, Arguments.JoinedAndSeparateValuesArg):
218 values = [args.getJoinedValue(arg), args.getSeparateValue(arg)]
Daniel Dunbara5677512009-01-05 19:53:30 +0000219 else:
220 values = []
Daniel Dunbar5039f212009-01-06 02:30:10 +0000221 print 'Option %d - Name: "%s", Values: {%s}' % (i, arg.opt.name,
Daniel Dunbara5677512009-01-05 19:53:30 +0000222 ', '.join(['"%s"' % v
223 for v in values]))
224
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000225 def printPhases(self, phases, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000226 def printPhase(p, f, steps, arch=None):
227 if p in steps:
228 return steps[p]
229 elif isinstance(p, Phases.BindArchAction):
230 for kid in p.inputs:
231 printPhase(kid, f, steps, p.arch)
232 steps[p] = len(steps)
233 return
234
235 if isinstance(p, Phases.InputAction):
236 phaseName = 'input'
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000237 inputStr = '"%s"' % args.getValue(p.filename)
Daniel Dunbara5677512009-01-05 19:53:30 +0000238 else:
239 phaseName = p.phase.name
240 inputs = [printPhase(i, f, steps, arch)
241 for i in p.inputs]
242 inputStr = '{%s}' % ', '.join(map(str, inputs))
243 if arch is not None:
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000244 phaseName += '-' + args.getValue(arch)
Daniel Dunbara5677512009-01-05 19:53:30 +0000245 steps[p] = index = len(steps)
246 print "%d: %s, %s, %s" % (index,phaseName,inputStr,p.type.name)
247 return index
248 steps = {}
249 for phase in phases:
250 printPhase(phase, sys.stdout, steps)
251
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000252 def handleImmediateOptions(self, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000253 # FIXME: Some driver Arguments are consumed right off the bat,
254 # like -dumpversion. Currently the gcc-dd handles these
255 # poorly, so we should be ok handling them upfront instead of
256 # after driver-driver level dispatching.
257 #
258 # FIXME: The actual order of these options in gcc is all over the
259 # place. The -dump ones seem to be first and in specification
260 # order, but there are other levels of precedence. For example,
261 # -print-search-dirs is evaluated before -print-prog-name=,
262 # regardless of order (and the last instance of -print-prog-name=
263 # wins verse itself).
264 #
265 # FIXME: Do we want to report "argument unused" type errors in the
266 # presence of things like -dumpmachine and -print-search-dirs?
267 # Probably not.
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000268 arg = args.getLastArg(self.parser.dumpmachineOption)
269 if arg:
270 print 'FIXME: %s' % arg.opt.name
271 sys.exit(1)
272
273 arg = args.getLastArg(self.parser.dumpspecsOption)
274 if arg:
275 print 'FIXME: %s' % arg.opt.name
276 sys.exit(1)
277
278 arg = args.getLastArg(self.parser.dumpversionOption)
279 if arg:
280 print 'FIXME: %s' % arg.opt.name
281 sys.exit(1)
282
283 arg = args.getLastArg(self.parser.printFileNameOption)
284 if arg:
285 print 'FIXME: %s' % arg.opt.name
286 sys.exit(1)
287
288 arg = args.getLastArg(self.parser.printMultiDirectoryOption)
289 if arg:
290 print 'FIXME: %s' % arg.opt.name
291 sys.exit(1)
292
293 arg = args.getLastArg(self.parser.printMultiLibOption)
294 if arg:
295 print 'FIXME: %s' % arg.opt.name
296 sys.exit(1)
297
298 arg = args.getLastArg(self.parser.printProgNameOption)
299 if arg:
300 print 'FIXME: %s' % arg.opt.name
301 sys.exit(1)
302
303 arg = args.getLastArg(self.parser.printLibgccFilenameOption)
304 if arg:
305 print 'FIXME: %s' % arg.opt.name
306 sys.exit(1)
307
308 arg = args.getLastArg(self.parser.printSearchDirsOption)
309 if arg:
310 print 'FIXME: %s' % arg.opt.name
311 sys.exit(1)
Daniel Dunbara5677512009-01-05 19:53:30 +0000312
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000313 def buildNormalPipeline(self, args):
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000314 hasCombine = args.getLastArg(self.parser.combineOption)
315 hasSyntaxOnly = args.getLastArg(self.parser.syntaxOnlyOption)
316 hasDashC = args.getLastArg(self.parser.cOption)
317 hasDashE = args.getLastArg(self.parser.EOption)
318 hasDashS = args.getLastArg(self.parser.SOption)
Daniel Dunbara5677512009-01-05 19:53:30 +0000319
320 inputType = None
321 inputTypeOpt = None
322 inputs = []
323 for a in args:
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000324 if a.opt is self.parser.inputOption:
Daniel Dunbar94713452009-01-16 23:12:12 +0000325 inputValue = args.getValue(a)
Daniel Dunbara5677512009-01-05 19:53:30 +0000326 if inputType is None:
Daniel Dunbar94713452009-01-16 23:12:12 +0000327 base,ext = os.path.splitext(inputValue)
Daniel Dunbara5677512009-01-05 19:53:30 +0000328 if ext and ext in Types.kTypeSuffixMap:
329 klass = Types.kTypeSuffixMap[ext]
330 else:
331 # FIXME: Its not clear why we shouldn't just
332 # revert to unknown. I think this is more likely a
333 # bug / unintended behavior in gcc. Not very
334 # important though.
335 klass = Types.ObjectType
336 else:
337 assert inputTypeOpt is not None
338 self.claim(inputTypeOpt)
339 klass = inputType
Daniel Dunbar94713452009-01-16 23:12:12 +0000340
341 # Check that the file exists. It isn't clear this is
342 # worth doing, since the tool presumably does this
343 # anyway, and this just adds an extra stat to the
344 # equation, but this is gcc compatible.
345 if not os.path.exists(inputValue):
346 self.warning("%s: No such file or directory" % inputValue)
347 else:
348 inputs.append((klass, a))
Daniel Dunbar2ec55bc2009-01-12 03:33:58 +0000349 elif a.opt.isLinkerInput:
350 # Treat as a linker input.
Daniel Dunbar5039f212009-01-06 02:30:10 +0000351 #
352 # FIXME: This might not be good enough. We may
353 # need to introduce another type for this case, so
354 # that other code which needs to know the inputs
355 # handles this properly. Best not to try and lipo
356 # this, for example.
357 inputs.append((Types.ObjectType, a))
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000358 elif a.opt is self.parser.xOption:
Daniel Dunbar5039f212009-01-06 02:30:10 +0000359 inputTypeOpt = a
360 value = args.getValue(a)
361 if value in Types.kTypeSpecifierMap:
362 inputType = Types.kTypeSpecifierMap[value]
363 else:
364 # FIXME: How are we going to handle diagnostics.
365 self.warning("language %s not recognized" % value)
Daniel Dunbara5677512009-01-05 19:53:30 +0000366
Daniel Dunbar5039f212009-01-06 02:30:10 +0000367 # FIXME: Its not clear why we shouldn't just
368 # revert to unknown. I think this is more likely a
369 # bug / unintended behavior in gcc. Not very
370 # important though.
Daniel Dunbar25d4a8f2009-01-13 21:07:43 +0000371 inputType = Types.ObjectType
Daniel Dunbara5677512009-01-05 19:53:30 +0000372
373 # We claim things here so that options for which we silently allow
374 # override only ever claim the used option.
375 if hasCombine:
376 self.claim(hasCombine)
377
378 finalPhase = Phases.Phase.eOrderPostAssemble
379 finalPhaseOpt = None
380
381 # Determine what compilation mode we are in.
382 if hasDashE:
383 finalPhase = Phases.Phase.eOrderPreprocess
384 finalPhaseOpt = hasDashE
385 elif hasSyntaxOnly:
386 finalPhase = Phases.Phase.eOrderCompile
387 finalPhaseOpt = hasSyntaxOnly
388 elif hasDashS:
389 finalPhase = Phases.Phase.eOrderCompile
390 finalPhaseOpt = hasDashS
391 elif hasDashC:
392 finalPhase = Phases.Phase.eOrderAssemble
393 finalPhaseOpt = hasDashC
394
395 if finalPhaseOpt:
396 self.claim(finalPhaseOpt)
397
398 # FIXME: Support -combine.
399 if hasCombine:
Daniel Dunbar94713452009-01-16 23:12:12 +0000400 raise NotImplementedError,"-combine is not yet supported"
401
402 if (not inputs and
403 not args.getLastArg(self.parser.hashHashHashOption)):
404 raise Arguments.InvalidArgumentsError("no input files")
Daniel Dunbara5677512009-01-05 19:53:30 +0000405
406 actions = []
407 linkerInputs = []
408 # FIXME: This is gross.
409 linkPhase = Phases.LinkPhase()
410 for klass,input in inputs:
411 # Figure out what step to start at.
412
413 # FIXME: This should be part of the input class probably?
414 # Altough it doesn't quite fit there either, things like
415 # asm-with-preprocess don't easily fit into a linear scheme.
416
417 # FIXME: I think we are going to end up wanting to just build
418 # a simple FSA which we run the inputs down.
419 sequence = []
420 if klass.preprocess:
421 sequence.append(Phases.PreprocessPhase())
422 if klass == Types.ObjectType:
423 sequence.append(linkPhase)
424 elif klass.onlyAssemble:
425 sequence.extend([Phases.AssemblePhase(),
426 linkPhase])
427 elif klass.onlyPrecompile:
428 sequence.append(Phases.PrecompilePhase())
429 else:
430 sequence.extend([Phases.CompilePhase(),
431 Phases.AssemblePhase(),
432 linkPhase])
433
434 if sequence[0].order > finalPhase:
435 assert finalPhaseOpt and finalPhaseOpt.opt
436 # FIXME: Explain what type of input file is. Or just match
437 # gcc warning.
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000438 self.warning("%s: %s input file unused when %s is present" % (args.getValue(input),
Daniel Dunbara5677512009-01-05 19:53:30 +0000439 sequence[0].name,
440 finalPhaseOpt.opt.name))
441 else:
442 # Build the pipeline for this file.
443
444 current = Phases.InputAction(input, klass)
445 for transition in sequence:
446 # If the current action produces no output, or we are
447 # past what the user requested, we are done.
448 if (current.type is Types.NothingType or
449 transition.order > finalPhase):
450 break
451 else:
452 if isinstance(transition, Phases.PreprocessPhase):
453 assert isinstance(klass.preprocess, Types.InputType)
454 current = Phases.JobAction(transition,
455 [current],
456 klass.preprocess)
457 elif isinstance(transition, Phases.PrecompilePhase):
458 current = Phases.JobAction(transition,
459 [current],
460 Types.PCHType)
461 elif isinstance(transition, Phases.CompilePhase):
462 if hasSyntaxOnly:
463 output = Types.NothingType
464 else:
465 output = Types.AsmTypeNoPP
466 current = Phases.JobAction(transition,
467 [current],
468 output)
469 elif isinstance(transition, Phases.AssemblePhase):
470 current = Phases.JobAction(transition,
471 [current],
472 Types.ObjectType)
473 elif transition is linkPhase:
474 linkerInputs.append(current)
475 current = None
476 break
477 else:
478 raise RuntimeError,'Unrecognized transition: %s.' % transition
479 pass
480
481 if current is not None:
482 assert not isinstance(current, Phases.InputAction)
483 actions.append(current)
484
485 if linkerInputs:
486 actions.append(Phases.JobAction(linkPhase,
487 linkerInputs,
488 Types.ImageType))
489
490 return actions
491
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000492 def buildPipeline(self, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000493 # FIXME: We need to handle canonicalization of the specified arch.
494
495 archs = []
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000496 hasDashM = None
497 hasSaveTemps = (args.getLastArg(self.parser.saveTempsOption) or
498 args.getLastArg(self.parser.saveTempsOption2))
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000499 for arg in args:
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000500 if arg.opt is self.parser.archOption:
Daniel Dunbar5039f212009-01-06 02:30:10 +0000501 archs.append(arg)
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000502 elif arg.opt.name.startswith('-M'):
503 hasDashM = arg
Daniel Dunbara5677512009-01-05 19:53:30 +0000504
505 if not archs:
Daniel Dunbar1f73ecb2009-01-13 04:05:40 +0000506 archs.append(args.makeSeparateArg(self.hostInfo.getArchName(args),
Daniel Dunbar39cbfaa2009-01-07 18:54:26 +0000507 self.parser.archOption))
Daniel Dunbara5677512009-01-05 19:53:30 +0000508
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000509 actions = self.buildNormalPipeline(args)
Daniel Dunbara5677512009-01-05 19:53:30 +0000510
511 # FIXME: Use custom exception for this.
512 #
513 # FIXME: We killed off some others but these aren't yet detected in
514 # a functional manner. If we added information to jobs about which
515 # "auxiliary" files they wrote then we could detect the conflict
516 # these cause downstream.
517 if len(archs) > 1:
518 if hasDashM:
Daniel Dunbar94713452009-01-16 23:12:12 +0000519 raise Arguments.InvalidArgumentsError("Cannot use -M options with multiple arch flags.")
Daniel Dunbara5677512009-01-05 19:53:30 +0000520 elif hasSaveTemps:
Daniel Dunbar94713452009-01-16 23:12:12 +0000521 raise Arguments.InvalidArgumentsError("Cannot use -save-temps with multiple arch flags.")
Daniel Dunbara5677512009-01-05 19:53:30 +0000522
523 # Execute once per arch.
524 finalActions = []
525 for p in actions:
526 # Make sure we can lipo this kind of output. If not (and it
527 # is an actual output) then we disallow, since we can't
528 # create an output file with the right name without
529 # overwriting it. We could remove this oddity by just
530 # changing the output names to include the arch, which would
531 # also fix -save-temps. Compatibility wins for now.
532 #
533 # FIXME: Is this error substantially less useful than
534 # gcc-dd's? The main problem is that "Cannot use compiler
535 # output with multiple arch flags" won't make sense to most
536 # developers.
537 if (len(archs) > 1 and
538 p.type not in (Types.NothingType,Types.ObjectType,Types.ImageType)):
Daniel Dunbar94713452009-01-16 23:12:12 +0000539 raise Arguments.InvalidArgumentsError('Cannot use %s output with multiple arch flags.' % p.type.name)
Daniel Dunbara5677512009-01-05 19:53:30 +0000540
541 inputs = []
542 for arch in archs:
543 inputs.append(Phases.BindArchAction(p, arch))
544
545 # Lipo if necessary. We do it this way because we need to set
546 # the arch flag so that -Xarch_ gets rewritten.
547 if len(inputs) == 1 or p.type == Types.NothingType:
548 finalActions.extend(inputs)
549 else:
550 finalActions.append(Phases.JobAction(Phases.LipoPhase(),
551 inputs,
552 p.type))
553
554 # FIXME: We need to add -Wl,arch_multiple and -Wl,final_output in
555 # certain cases. This may be icky because we need to figure out the
556 # mode first. Current plan is to hack on the pipeline once it is built
557 # and we know what is being spit out. This avoids having to handling
558 # things like -c and -combine in multiple places.
559 #
560 # The annoying one of these is -Wl,final_output because it involves
561 # communication across different phases.
562 #
563 # Hopefully we can do this purely as part of the binding, but
564 # leaving comment here for now until it is clear this works.
565
566 return finalActions
567
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000568 def bindPhases(self, phases, args):
Daniel Dunbara5677512009-01-05 19:53:30 +0000569 jobs = Jobs.JobList()
570
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000571 finalOutput = args.getLastArg(self.parser.oOption)
572 hasSaveTemps = (args.getLastArg(self.parser.saveTempsOption) or
573 args.getLastArg(self.parser.saveTempsOption2))
574 hasNoIntegratedCPP = args.getLastArg(self.parser.noIntegratedCPPOption)
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000575 hasTraditionalCPP = args.getLastArg(self.parser.traditionalCPPOption)
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000576 hasPipe = args.getLastArg(self.parser.pipeOption)
Daniel Dunbar2ec55bc2009-01-12 03:33:58 +0000577
Daniel Dunbara5677512009-01-05 19:53:30 +0000578 # We claim things here so that options for which we silently allow
579 # override only ever claim the used option.
580 if hasPipe:
581 self.claim(hasPipe)
582 # FIXME: Hack, override -pipe till we support it.
583 hasPipe = None
584 # Claim these here. Its not completely accurate but any warnings
585 # about these being unused are likely to be noise anyway.
586 if hasSaveTemps:
587 self.claim(hasSaveTemps)
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000588
589 if hasTraditionalCPP:
590 self.claim(hasTraditionalCPP)
591 elif hasNoIntegratedCPP:
Daniel Dunbara5677512009-01-05 19:53:30 +0000592 self.claim(hasNoIntegratedCPP)
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000593
Daniel Dunbar76290532009-01-13 06:25:31 +0000594 # FIXME: Move to... somewhere else.
Daniel Dunbara5677512009-01-05 19:53:30 +0000595 class InputInfo:
596 def __init__(self, source, type, baseInput):
597 self.source = source
598 self.type = type
599 self.baseInput = baseInput
600
601 def __repr__(self):
602 return '%s(%r, %r, %r)' % (self.__class__.__name__,
603 self.source, self.type, self.baseInput)
Daniel Dunbar76290532009-01-13 06:25:31 +0000604
605 def isOriginalInput(self):
606 return self.source is self.baseInput
Daniel Dunbara5677512009-01-05 19:53:30 +0000607
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000608 def createJobs(tc, phase,
609 canAcceptPipe=False, atTopLevel=False, arch=None,
610 tcArgs=None):
Daniel Dunbara5677512009-01-05 19:53:30 +0000611 if isinstance(phase, Phases.InputAction):
612 return InputInfo(phase.filename, phase.type, phase.filename)
613 elif isinstance(phase, Phases.BindArchAction):
Daniel Dunbar1e5f3eb2009-01-06 01:35:44 +0000614 archName = args.getValue(phase.arch)
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000615 tc = self.hostInfo.getToolChainForArch(archName)
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000616 return createJobs(tc, phase.inputs[0],
617 canAcceptPipe, atTopLevel, phase.arch,
618 tcArgs=None)
619
620 if tcArgs is None:
621 tcArgs = tc.translateArgs(args, arch)
Daniel Dunbara5677512009-01-05 19:53:30 +0000622
623 assert isinstance(phase, Phases.JobAction)
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000624 tool = tc.selectTool(phase)
Daniel Dunbara5677512009-01-05 19:53:30 +0000625
626 # See if we should use an integrated CPP. We only use an
627 # integrated cpp when we have exactly one input, since this is
628 # the only use case we care about.
629 useIntegratedCPP = False
630 inputList = phase.inputs
631 if (not hasNoIntegratedCPP and
Daniel Dunbar6325fcf2009-01-12 09:23:15 +0000632 not hasTraditionalCPP and
Daniel Dunbara5677512009-01-05 19:53:30 +0000633 not hasSaveTemps and
634 tool.hasIntegratedCPP()):
635 if (len(phase.inputs) == 1 and
636 isinstance(phase.inputs[0].phase, Phases.PreprocessPhase)):
637 useIntegratedCPP = True
638 inputList = phase.inputs[0].inputs
639
640 # Only try to use pipes when exactly one input.
641 canAcceptPipe = len(inputList) == 1 and tool.acceptsPipedInput()
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000642 inputs = [createJobs(tc, p, canAcceptPipe, False, arch, tcArgs)
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000643 for p in inputList]
Daniel Dunbara5677512009-01-05 19:53:30 +0000644
645 # Determine if we should output to a pipe.
646 canOutputToPipe = canAcceptPipe and tool.canPipeOutput()
647 outputToPipe = False
648 if canOutputToPipe:
649 # Some things default to writing to a pipe if the final
650 # phase and there was no user override.
651 #
652 # FIXME: What is the best way to handle this?
653 if (atTopLevel and
654 isinstance(phase, Phases.PreprocessPhase) and
655 not finalOutput):
656 outputToPipe = True
657 elif hasPipe:
658 outputToPipe = True
659
660 # Figure out where to put the job (pipes).
661 jobList = jobs
662 if canAcceptPipe and isinstance(inputs[0].source, Jobs.PipedJob):
663 jobList = inputs[0].source
664
665 # Figure out where to put the output.
666 baseInput = inputs[0].baseInput
667 if phase.type == Types.NothingType:
668 output = None
669 elif outputToPipe:
670 if isinstance(jobList, Jobs.PipedJob):
671 output = jobList
672 else:
673 jobList = output = Jobs.PipedJob([])
674 jobs.addJob(output)
675 else:
676 # Figure out what the derived output location would be.
677 #
678 # FIXME: gcc has some special case in here so that it doesn't
679 # create output files if they would conflict with an input.
Daniel Dunbara5677512009-01-05 19:53:30 +0000680 if phase.type is Types.ImageType:
681 namedOutput = "a.out"
682 else:
Daniel Dunbar2ec55bc2009-01-12 03:33:58 +0000683 inputName = args.getValue(baseInput)
Daniel Dunbara5677512009-01-05 19:53:30 +0000684 base,_ = os.path.splitext(inputName)
685 assert phase.type.tempSuffix is not None
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000686 namedOutput = base + '.' + phase.type.tempSuffix
Daniel Dunbara5677512009-01-05 19:53:30 +0000687
688 # Output to user requested destination?
689 if atTopLevel and finalOutput:
690 output = finalOutput
691 # Contruct a named destination?
692 elif atTopLevel or hasSaveTemps:
Daniel Dunbar3235fdb2009-01-12 07:48:07 +0000693 output = args.makeSeparateArg(os.path.basename(namedOutput),
Daniel Dunbar39cbfaa2009-01-07 18:54:26 +0000694 self.parser.oOption)
Daniel Dunbara5677512009-01-05 19:53:30 +0000695 else:
696 # Output to temp file...
Daniel Dunbarba6e3232009-01-06 06:12:13 +0000697 fd,filename = tempfile.mkstemp(suffix='.'+phase.type.tempSuffix)
Daniel Dunbar39cbfaa2009-01-07 18:54:26 +0000698 output = args.makeSeparateArg(filename,
699 self.parser.oOption)
Daniel Dunbara5677512009-01-05 19:53:30 +0000700
Daniel Dunbardb439902009-01-07 18:40:45 +0000701 tool.constructJob(phase, arch, jobList, inputs, output, phase.type,
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000702 tcArgs)
Daniel Dunbara5677512009-01-05 19:53:30 +0000703
704 return InputInfo(output, phase.type, baseInput)
705
706 # It is an error to provide a -o option if we are making multiple
707 # output files.
708 if finalOutput and len([a for a in phases if a.type is not Types.NothingType]) > 1:
Daniel Dunbar94713452009-01-16 23:12:12 +0000709 raise Arguments.InvalidArgumentsError("cannot specify -o when generating multiple files")
Daniel Dunbara5677512009-01-05 19:53:30 +0000710
711 for phase in phases:
Daniel Dunbar11672ec2009-01-13 18:51:26 +0000712 createJobs(self.toolChain, phase,
Daniel Dunbarbee1f0d2009-01-11 22:06:22 +0000713 canAcceptPipe=True, atTopLevel=True)
Daniel Dunbara5677512009-01-05 19:53:30 +0000714
715 return jobs