Driver.cpp revision 16e04ff3b6cfee92c56be7a50da704b8431ac300
1//===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Driver/Driver.h"
11
12#include "clang/Driver/Action.h"
13#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/HostInfo.h"
18#include "clang/Driver/Job.h"
19#include "clang/Driver/Option.h"
20#include "clang/Driver/Options.h"
21#include "clang/Driver/Tool.h"
22#include "clang/Driver/ToolChain.h"
23#include "clang/Driver/Types.h"
24
25#include "llvm/ADT/StringSet.h"
26#include "llvm/Support/PrettyStackTrace.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/System/Path.h"
29
30#include "InputInfo.h"
31
32#include <map>
33
34using namespace clang::driver;
35
36Driver::Driver(const char *_Name, const char *_Dir,
37               const char *_DefaultHostTriple,
38               const char *_DefaultImageName,
39               Diagnostic &_Diags)
40  : Opts(new OptTable()), Diags(_Diags),
41    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
42    DefaultImageName(_DefaultImageName),
43    Host(0),
44    CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
45    CCCNoClang(false), CCCNoClangCXX(false), CCCNoClangCPP(false),
46    SuppressMissingInputWarning(false)
47{
48}
49
50Driver::~Driver() {
51  delete Opts;
52  delete Host;
53}
54
55ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) {
56  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
57  ArgList *Args = new ArgList(ArgBegin, ArgEnd);
58
59  // FIXME: Handle '@' args (or at least error on them).
60
61  unsigned Index = 0, End = ArgEnd - ArgBegin;
62  while (Index < End) {
63    // gcc's handling of empty arguments doesn't make
64    // sense, but this is not a common use case. :)
65    //
66    // We just ignore them here (note that other things may
67    // still take them as arguments).
68    if (Args->getArgString(Index)[0] == '\0') {
69      ++Index;
70      continue;
71    }
72
73    unsigned Prev = Index;
74    Arg *A = getOpts().ParseOneArg(*Args, Index, End);
75    if (A) {
76      if (A->getOption().isUnsupported()) {
77        Diag(clang::diag::err_drv_unsupported_opt) << A->getOption().getName();
78        continue;
79      }
80
81      Args->append(A);
82    }
83
84    assert(Index > Prev && "Parser failed to consume argument.");
85    (void) Prev;
86  }
87
88  return Args;
89}
90
91Compilation *Driver::BuildCompilation(int argc, const char **argv) {
92  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
93
94  // FIXME: Handle environment options which effect driver behavior,
95  // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
96  // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
97
98  // FIXME: What are we going to do with -V and -b?
99
100  // FIXME: Handle CCC_ADD_ARGS.
101
102  // FIXME: This stuff needs to go into the Compilation, not the
103  // driver.
104  bool CCCPrintOptions = false, CCCPrintActions = false;
105
106  const char **Start = argv + 1, **End = argv + argc;
107  const char *HostTriple = DefaultHostTriple.c_str();
108
109  // Read -ccc args.
110  //
111  // FIXME: We need to figure out where this behavior should
112  // live. Most of it should be outside in the client; the parts that
113  // aren't should have proper options, either by introducing new ones
114  // or by overloading gcc ones like -V or -b.
115  for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
116    const char *Opt = *Start + 5;
117
118    if (!strcmp(Opt, "print-options")) {
119      CCCPrintOptions = true;
120    } else if (!strcmp(Opt, "print-phases")) {
121      CCCPrintActions = true;
122    } else if (!strcmp(Opt, "print-bindings")) {
123      CCCPrintBindings = true;
124    } else if (!strcmp(Opt, "cxx")) {
125      CCCIsCXX = true;
126    } else if (!strcmp(Opt, "echo")) {
127      CCCEcho = true;
128
129    } else if (!strcmp(Opt, "no-clang")) {
130      CCCNoClang = true;
131    } else if (!strcmp(Opt, "no-clang-cxx")) {
132      CCCNoClangCXX = true;
133    } else if (!strcmp(Opt, "no-clang-cpp")) {
134      CCCNoClangCPP = true;
135    } else if (!strcmp(Opt, "clang-archs")) {
136      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
137      const char *Cur = *++Start;
138
139      for (;;) {
140        const char *Next = strchr(Cur, ',');
141
142        if (Next) {
143          CCCClangArchs.insert(std::string(Cur, Next));
144          Cur = Next + 1;
145        } else {
146          CCCClangArchs.insert(std::string(Cur));
147          break;
148        }
149      }
150
151    } else if (!strcmp(Opt, "host-triple")) {
152      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
153      HostTriple = *++Start;
154
155    } else {
156      // FIXME: Error handling.
157      llvm::errs() << "invalid option: " << *Start << "\n";
158      exit(1);
159    }
160  }
161
162  ArgList *Args = ParseArgStrings(Start, End);
163
164  Host = GetHostInfo(HostTriple);
165  // FIXME: This shouldn't live inside Driver, the default tool chain
166  // is part of the compilation (it is arg dependent).
167  DefaultToolChain = Host->getToolChain(*Args);
168
169  // FIXME: This behavior shouldn't be here.
170  if (CCCPrintOptions) {
171    PrintOptions(*Args);
172    return 0;
173  }
174
175  if (!HandleImmediateArgs(*Args))
176    return 0;
177
178  // Construct the list of abstract actions to perform for this
179  // compilation.
180  ActionList Actions;
181  if (Host->useDriverDriver())
182    BuildUniversalActions(*Args, Actions);
183  else
184    BuildActions(*Args, Actions);
185
186  if (CCCPrintActions) {
187    PrintActions(*Args, Actions);
188    return 0;
189  }
190
191  // The compilation takes ownership of Args.
192  Compilation *C = new Compilation(*DefaultToolChain, Args);
193  BuildJobs(*C, Actions);
194
195  return C;
196}
197
198void Driver::PrintOptions(const ArgList &Args) const {
199  unsigned i = 0;
200  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
201       it != ie; ++it, ++i) {
202    Arg *A = *it;
203    llvm::errs() << "Option " << i << " - "
204                 << "Name: \"" << A->getOption().getName() << "\", "
205                 << "Values: {";
206    for (unsigned j = 0; j < A->getNumValues(); ++j) {
207      if (j)
208        llvm::errs() << ", ";
209      llvm::errs() << '"' << A->getValue(Args, j) << '"';
210    }
211    llvm::errs() << "}\n";
212  }
213}
214
215void Driver::PrintVersion() const {
216  // FIXME: Get a reasonable version number.
217
218  // FIXME: The following handlers should use a callback mechanism, we
219  // don't know what the client would like to do.
220  llvm::outs() << "ccc version 1.0" << "\n";
221}
222
223bool Driver::HandleImmediateArgs(const ArgList &Args) {
224  // The order these options are handled in in gcc is all over the
225  // place, but we don't expect inconsistencies w.r.t. that to matter
226  // in practice.
227  if (Args.hasArg(options::OPT_v) ||
228      Args.hasArg(options::OPT__HASH_HASH_HASH)) {
229    PrintVersion();
230    SuppressMissingInputWarning = true;
231  }
232
233  // FIXME: The following handlers should use a callback mechanism, we
234  // don't know what the client would like to do.
235  if (Arg *A = Args.getLastArg(options::OPT_print_file_name_EQ)) {
236    llvm::outs() << GetFilePath(A->getValue(Args)).toString() << "\n";
237    return false;
238  }
239
240  if (Arg *A = Args.getLastArg(options::OPT_print_prog_name_EQ)) {
241    llvm::outs() << GetProgramPath(A->getValue(Args)).toString() << "\n";
242    return false;
243  }
244
245  if (Args.hasArg(options::OPT_print_libgcc_file_name)) {
246    llvm::outs() << GetProgramPath("libgcc.a").toString() << "\n";
247    return false;
248  }
249
250  return true;
251}
252
253static unsigned PrintActions1(const ArgList &Args,
254                              Action *A,
255                              std::map<Action*, unsigned> &Ids) {
256  if (Ids.count(A))
257    return Ids[A];
258
259  std::string str;
260  llvm::raw_string_ostream os(str);
261
262  os << Action::getClassName(A->getKind()) << ", ";
263  if (InputAction *IA = dyn_cast<InputAction>(A)) {
264    os << "\"" << IA->getInputArg().getValue(Args) << "\"";
265  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
266    os << "\"" << BIA->getArchName() << "\", "
267       << "{" << PrintActions1(Args, *BIA->begin(), Ids) << "}";
268  } else {
269    os << "{";
270    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
271      os << PrintActions1(Args, *it, Ids);
272      ++it;
273      if (it != ie)
274        os << ", ";
275    }
276    os << "}";
277  }
278
279  unsigned Id = Ids.size();
280  Ids[A] = Id;
281  llvm::errs() << Id << ": " << os.str() << ", "
282               << types::getTypeName(A->getType()) << "\n";
283
284  return Id;
285}
286
287void Driver::PrintActions(const ArgList &Args,
288                          const ActionList &Actions) const {
289  std::map<Action*, unsigned> Ids;
290  for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
291       it != ie; ++it)
292    PrintActions1(Args, *it, Ids);
293}
294
295void Driver::BuildUniversalActions(ArgList &Args, ActionList &Actions) const {
296  llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
297  // Collect the list of architectures. Duplicates are allowed, but
298  // should only be handled once (in the order seen).
299  llvm::StringSet<> ArchNames;
300  llvm::SmallVector<const char *, 4> Archs;
301  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
302       it != ie; ++it) {
303    Arg *A = *it;
304
305    if (A->getOption().getId() == options::OPT_arch) {
306      const char *Name = A->getValue(Args);
307
308      // FIXME: We need to handle canonicalization of the specified
309      // arch?
310
311      if (ArchNames.insert(Name))
312        Archs.push_back(Name);
313    }
314  }
315
316  // When there is no explicit arch for this platform, get one from
317  // the host so that -Xarch_ is handled correctly.
318  if (!Archs.size()) {
319    const char *Arch = DefaultToolChain->getArchName().c_str();
320    Archs.push_back(Arch);
321  }
322
323  // FIXME: We killed off some others but these aren't yet detected in
324  // a functional manner. If we added information to jobs about which
325  // "auxiliary" files they wrote then we could detect the conflict
326  // these cause downstream.
327  if (Archs.size() > 1) {
328    // No recovery needed, the point of this is just to prevent
329    // overwriting the same files.
330    if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
331      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
332        << A->getOption().getName();
333    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
334      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
335        << A->getOption().getName();
336  }
337
338  ActionList SingleActions;
339  BuildActions(Args, SingleActions);
340
341  // Add in arch binding and lipo (if necessary) for every top level
342  // action.
343  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
344    Action *Act = SingleActions[i];
345
346    // Make sure we can lipo this kind of output. If not (and it is an
347    // actual output) then we disallow, since we can't create an
348    // output file with the right name without overwriting it. We
349    // could remove this oddity by just changing the output names to
350    // include the arch, which would also fix
351    // -save-temps. Compatibility wins for now.
352
353    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
354      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
355        << types::getTypeName(Act->getType());
356
357    ActionList Inputs;
358    for (unsigned i = 0, e = Archs.size(); i != e; ++i )
359      Inputs.push_back(new BindArchAction(Act, Archs[i]));
360
361    // Lipo if necessary, We do it this way because we need to set the
362    // arch flag so that -Xarch_ gets overwritten.
363    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
364      Actions.append(Inputs.begin(), Inputs.end());
365    else
366      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
367  }
368}
369
370void Driver::BuildActions(ArgList &Args, ActionList &Actions) const {
371  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
372  // Start by constructing the list of inputs and their types.
373
374  // Track the current user specified (-x) input. We also explicitly
375  // track the argument used to set the type; we only want to claim
376  // the type when we actually use it, so we warn about unused -x
377  // arguments.
378  types::ID InputType = types::TY_Nothing;
379  Arg *InputTypeArg = 0;
380
381  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
382  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
383       it != ie; ++it) {
384    Arg *A = *it;
385
386    if (isa<InputOption>(A->getOption())) {
387      const char *Value = A->getValue(Args);
388      types::ID Ty = types::TY_INVALID;
389
390      // Infer the input type if necessary.
391      if (InputType == types::TY_Nothing) {
392        // If there was an explicit arg for this, claim it.
393        if (InputTypeArg)
394          InputTypeArg->claim();
395
396        // stdin must be handled specially.
397        if (memcmp(Value, "-", 2) == 0) {
398          // If running with -E, treat as a C input (this changes the
399          // builtin macros, for example). This may be overridden by
400          // -ObjC below.
401          //
402          // Otherwise emit an error but still use a valid type to
403          // avoid spurious errors (e.g., no inputs).
404          if (!Args.hasArg(options::OPT_E, false))
405            Diag(clang::diag::err_drv_unknown_stdin_type);
406          Ty = types::TY_C;
407        } else {
408          // Otherwise lookup by extension, and fallback to ObjectType
409          // if not found.
410          if (const char *Ext = strrchr(Value, '.'))
411            Ty = types::lookupTypeForExtension(Ext + 1);
412          if (Ty == types::TY_INVALID)
413            Ty = types::TY_Object;
414        }
415
416        // -ObjC and -ObjC++ override the default language, but only
417        // -for "source files". We just treat everything that isn't a
418        // -linker input as a source file.
419        //
420        // FIXME: Clean this up if we move the phase sequence into the
421        // type.
422        if (Ty != types::TY_Object) {
423          if (Args.hasArg(options::OPT_ObjC))
424            Ty = types::TY_ObjC;
425          else if (Args.hasArg(options::OPT_ObjCXX))
426            Ty = types::TY_ObjCXX;
427        }
428      } else {
429        assert(InputTypeArg && "InputType set w/o InputTypeArg");
430        InputTypeArg->claim();
431        Ty = InputType;
432      }
433
434      // Check that the file exists. It isn't clear this is worth
435      // doing, since the tool presumably does this anyway, and this
436      // just adds an extra stat to the equation, but this is gcc
437      // compatible.
438      A->claim();
439      if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
440        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
441      else
442        Inputs.push_back(std::make_pair(Ty, A));
443
444    } else if (A->getOption().isLinkerInput()) {
445      // Just treat as object type, we could make a special type for
446      // this if necessary.
447      A->claim();
448      Inputs.push_back(std::make_pair(types::TY_Object, A));
449
450    } else if (A->getOption().getId() == options::OPT_x) {
451      InputTypeArg = A;
452      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
453
454      // Follow gcc behavior and treat as linker input for invalid -x
455      // options. Its not clear why we shouldn't just revert to
456      // unknown; but this isn't very important, we might as well be
457      // bug comatible.
458      if (!InputType) {
459        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
460        InputType = types::TY_Object;
461      }
462    }
463  }
464
465  if (!SuppressMissingInputWarning && Inputs.empty()) {
466    Diag(clang::diag::err_drv_no_input_files);
467    return;
468  }
469
470  // Determine which compilation mode we are in. We look for options
471  // which affect the phase, starting with the earliest phases, and
472  // record which option we used to determine the final phase.
473  Arg *FinalPhaseArg = 0;
474  phases::ID FinalPhase;
475
476  // -{E,M,MM} only run the preprocessor.
477  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
478      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
479      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
480    FinalPhase = phases::Preprocess;
481
482    // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
483  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
484             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
485             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
486             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
487    FinalPhase = phases::Compile;
488
489    // -c only runs up to the assembler.
490  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
491    FinalPhase = phases::Assemble;
492
493    // Otherwise do everything.
494  } else
495    FinalPhase = phases::Link;
496
497  // Reject -Z* at the top level, these options should never have been
498  // exposed by gcc.
499  if (Arg *A = Args.getLastArg(options::OPT_Z))
500    Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
501
502  // Construct the actions to perform.
503  ActionList LinkerInputs;
504  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
505    types::ID InputType = Inputs[i].first;
506    const Arg *InputArg = Inputs[i].second;
507
508    unsigned NumSteps = types::getNumCompilationPhases(InputType);
509    assert(NumSteps && "Invalid number of steps!");
510
511    // If the first step comes after the final phase we are doing as
512    // part of this compilation, warn the user about it.
513    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
514    if (InitialPhase > FinalPhase) {
515      Diag(clang::diag::warn_drv_input_file_unused)
516        << InputArg->getValue(Args)
517        << getPhaseName(InitialPhase)
518        << FinalPhaseArg->getOption().getName();
519      continue;
520    }
521
522    // Build the pipeline for this file.
523    Action *Current = new InputAction(*InputArg, InputType);
524    for (unsigned i = 0; i != NumSteps; ++i) {
525      phases::ID Phase = types::getCompilationPhase(InputType, i);
526
527      // We are done if this step is past what the user requested.
528      if (Phase > FinalPhase)
529        break;
530
531      // Queue linker inputs.
532      if (Phase == phases::Link) {
533        assert(i + 1 == NumSteps && "linking must be final compilation step.");
534        LinkerInputs.push_back(Current);
535        Current = 0;
536        break;
537      }
538
539      // Otherwise construct the appropriate action.
540      Current = ConstructPhaseAction(Args, Phase, Current);
541      if (Current->getType() == types::TY_Nothing)
542        break;
543    }
544
545    // If we ended with something, add to the output list.
546    if (Current)
547      Actions.push_back(Current);
548  }
549
550  // Add a link action if necessary.
551  if (!LinkerInputs.empty())
552    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
553}
554
555Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
556                                     Action *Input) const {
557  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
558  // Build the appropriate action.
559  switch (Phase) {
560  case phases::Link: assert(0 && "link action invalid here.");
561  case phases::Preprocess: {
562    types::ID OutputTy = types::getPreprocessedType(Input->getType());
563    assert(OutputTy != types::TY_INVALID &&
564           "Cannot preprocess this input type!");
565    return new PreprocessJobAction(Input, OutputTy);
566  }
567  case phases::Precompile:
568    return new PrecompileJobAction(Input, types::TY_PCH);
569  case phases::Compile: {
570    if (Args.hasArg(options::OPT_fsyntax_only)) {
571      return new CompileJobAction(Input, types::TY_Nothing);
572    } else if (Args.hasArg(options::OPT__analyze)) {
573      return new AnalyzeJobAction(Input, types::TY_Plist);
574    } else if (Args.hasArg(options::OPT_emit_llvm)) {
575      types::ID Output =
576        Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
577      return new CompileJobAction(Input, Output);
578    } else {
579      return new CompileJobAction(Input, types::TY_PP_Asm);
580    }
581  }
582  case phases::Assemble:
583    return new AssembleJobAction(Input, types::TY_Object);
584  }
585
586  assert(0 && "invalid phase in ConstructPhaseAction");
587  return 0;
588}
589
590void Driver::BuildJobs(Compilation &C, const ActionList &Actions) const {
591  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
592  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
593  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
594
595  // -save-temps inhibits pipes.
596  if (SaveTemps && UsePipes) {
597    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
598    UsePipes = true;
599  }
600
601  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
602
603  // It is an error to provide a -o option if we are making multiple
604  // output files.
605  if (FinalOutput) {
606    unsigned NumOutputs = 0;
607    for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
608         it != ie; ++it)
609      if ((*it)->getType() != types::TY_Nothing)
610        ++NumOutputs;
611
612    if (NumOutputs > 1) {
613      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
614      FinalOutput = 0;
615    }
616  }
617
618  for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
619       it != ie; ++it) {
620    Action *A = *it;
621
622    // If we are linking an image for multiple archs then the linker
623    // wants -arch_multiple and -final_output <final image
624    // name>. Unfortunately, this doesn't fit in cleanly because we
625    // have to pass this information down.
626    //
627    // FIXME: This is a hack; find a cleaner way to integrate this
628    // into the process.
629    const char *LinkingOutput = 0;
630    if (isa<LinkJobAction>(A)) {
631      if (FinalOutput)
632        LinkingOutput = FinalOutput->getValue(C.getArgs());
633      else
634        LinkingOutput = DefaultImageName.c_str();
635    }
636
637    InputInfo II;
638    BuildJobsForAction(C,
639                       A, DefaultToolChain,
640                       /*CanAcceptPipe*/ true,
641                       /*AtTopLevel*/ true,
642                       /*LinkingOutput*/ LinkingOutput,
643                       II);
644  }
645
646  // If there were no errors, warn about any unused arguments.
647  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
648       it != ie; ++it) {
649    Arg *A = *it;
650
651    // FIXME: It would be nice to be able to send the argument to the
652    // Diagnostic, so that extra values, position, and so on could be
653    // printed.
654    if (!A->isClaimed())
655      Diag(clang::diag::warn_drv_unused_argument)
656        << A->getOption().getName();
657  }
658}
659
660void Driver::BuildJobsForAction(Compilation &C,
661                                const Action *A,
662                                const ToolChain *TC,
663                                bool CanAcceptPipe,
664                                bool AtTopLevel,
665                                const char *LinkingOutput,
666                                InputInfo &Result) const {
667  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
668  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
669    const char *Name = IA->getInputArg().getValue(C.getArgs());
670    Result = InputInfo(Name, A->getType(), Name);
671    return;
672  }
673
674  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
675    const char *ArchName = BAA->getArchName();
676    BuildJobsForAction(C,
677                       *BAA->begin(),
678                       Host->getToolChain(C.getArgs(), ArchName),
679                       CanAcceptPipe,
680                       AtTopLevel,
681                       LinkingOutput,
682                       Result);
683    return;
684  }
685
686  const JobAction *JA = cast<JobAction>(A);
687  const Tool &T = TC->SelectTool(C, *JA);
688
689  // See if we should use an integrated preprocessor. We do so when we
690  // have exactly one input, since this is the only use case we care
691  // about (irrelevant since we don't support combine yet).
692  bool UseIntegratedCPP = false;
693  const ActionList *Inputs = &A->getInputs();
694  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
695    if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
696        !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
697        !C.getArgs().hasArg(options::OPT_save_temps) &&
698        T.hasIntegratedCPP()) {
699      UseIntegratedCPP = true;
700      Inputs = &(*Inputs)[0]->getInputs();
701    }
702  }
703
704  // Only use pipes when there is exactly one input.
705  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
706  llvm::SmallVector<InputInfo, 4> InputInfos;
707  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
708       it != ie; ++it) {
709    InputInfo II;
710    BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
711                       /*AtTopLevel*/false,
712                       LinkingOutput,
713                       II);
714    InputInfos.push_back(II);
715  }
716
717  // Determine if we should output to a pipe.
718  bool OutputToPipe = false;
719  if (CanAcceptPipe && T.canPipeOutput()) {
720    // Some actions default to writing to a pipe if they are the top
721    // level phase and there was no user override.
722    //
723    // FIXME: Is there a better way to handle this?
724    if (AtTopLevel) {
725      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
726        OutputToPipe = true;
727    } else if (C.getArgs().hasArg(options::OPT_pipe))
728      OutputToPipe = true;
729  }
730
731  // Figure out where to put the job (pipes).
732  Job *Dest = &C.getJobs();
733  if (InputInfos[0].isPipe()) {
734    assert(TryToUsePipeInput && "Unrequested pipe!");
735    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
736    Dest = &InputInfos[0].getPipe();
737  }
738
739  // Always use the first input as the base input.
740  const char *BaseInput = InputInfos[0].getBaseInput();
741
742  // Determine the place to write output to (nothing, pipe, or
743  // filename) and where to put the new job.
744  if (JA->getType() == types::TY_Nothing) {
745    Result = InputInfo(A->getType(), BaseInput);
746  } else if (OutputToPipe) {
747    // Append to current piped job or create a new one as appropriate.
748    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
749    if (!PJ) {
750      PJ = new PipedJob();
751      cast<JobList>(Dest)->addJob(PJ);
752    }
753    Result = InputInfo(PJ, A->getType(), BaseInput);
754  } else {
755    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
756                       A->getType(), BaseInput);
757  }
758
759  if (CCCPrintBindings) {
760    llvm::errs() << "bind - \"" << T.getName() << "\", inputs: [";
761    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
762      llvm::errs() << InputInfos[i].getAsString();
763      if (i + 1 != e)
764        llvm::errs() << ", ";
765    }
766    llvm::errs() << "], output: " << Result.getAsString() << "\n";
767  } else {
768    assert(0 && "FIXME: Make the job.");
769  }
770}
771
772const char *Driver::GetNamedOutputPath(Compilation &C,
773                                       const JobAction &JA,
774                                       const char *BaseInput,
775                                       bool AtTopLevel) const {
776  llvm::PrettyStackTraceString CrashInfo("Computing output path");
777  // Output to a user requested destination?
778  if (AtTopLevel) {
779    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
780      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
781  }
782
783  // Output to a temporary file?
784  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
785    // FIXME: Get temporary name.
786    std::string Name("/tmp/foo");
787    Name += '.';
788    Name += types::getTypeTempSuffix(JA.getType());
789    return C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
790  }
791
792  llvm::sys::Path BasePath(BaseInput);
793  std::string BaseName(BasePath.getBasename());
794
795  // Determine what the derived output name should be.
796  const char *NamedOutput;
797  if (JA.getType() == types::TY_Image) {
798    NamedOutput = DefaultImageName.c_str();
799  } else {
800    const char *Suffix = types::getTypeTempSuffix(JA.getType());
801    assert(Suffix && "All types used for output should have a suffix.");
802
803    std::string::size_type End = std::string::npos;
804    if (!types::appendSuffixForType(JA.getType()))
805      End = BaseName.rfind('.');
806    std::string Suffixed(BaseName.substr(0, End));
807    Suffixed += '.';
808    Suffixed += Suffix;
809    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
810  }
811
812  // As an annoying special case, PCH generation doesn't strip the
813  // pathname.
814  if (JA.getType() == types::TY_PCH) {
815    BasePath.eraseComponent();
816    BasePath.appendComponent(NamedOutput);
817    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
818  } else {
819    return C.addResultFile(NamedOutput);
820  }
821}
822
823llvm::sys::Path Driver::GetFilePath(const char *Name,
824                                    const ToolChain *TC) const {
825  // FIXME: Implement.
826  if (!TC) TC = DefaultToolChain;
827
828  return llvm::sys::Path(Name);
829}
830
831llvm::sys::Path Driver::GetProgramPath(const char *Name,
832                                       const ToolChain *TC) const {
833  // FIXME: Implement.
834  if (!TC) TC = DefaultToolChain;
835
836  return llvm::sys::Path(Name);
837}
838
839const HostInfo *Driver::GetHostInfo(const char *Triple) const {
840  llvm::PrettyStackTraceString CrashInfo("Constructing host");
841  // Dice into arch, platform, and OS. This matches
842  //  arch,platform,os = '(.*?)-(.*?)-(.*?)'
843  // and missing fields are left empty.
844  std::string Arch, Platform, OS;
845
846  if (const char *ArchEnd = strchr(Triple, '-')) {
847    Arch = std::string(Triple, ArchEnd);
848
849    if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
850      Platform = std::string(ArchEnd+1, PlatformEnd);
851      OS = PlatformEnd+1;
852    } else
853      Platform = ArchEnd+1;
854  } else
855    Arch = Triple;
856
857  // Normalize Arch a bit.
858  //
859  // FIXME: This is very incomplete.
860  if (Arch == "i686")
861    Arch = "i386";
862  else if (Arch == "amd64")
863    Arch = "x86_64";
864
865  if (memcmp(&OS[0], "darwin", 6) == 0)
866    return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
867                                OS.c_str());
868
869  return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
870                               OS.c_str());
871}
872