driver.cpp revision 217acbfa3524d5805fda7900b26c1e779443588d
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// This is the entry point to the clang driver; it is a thin wrapper
11// for functionality in the Driver clang library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/Option.h"
18
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/OwningPtr.h"
21#include "llvm/Config/config.h"
22#include "llvm/Support/ManagedStatic.h"
23#include "llvm/Support/PrettyStackTrace.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/System/Host.h"
26#include "llvm/System/Path.h"
27#include "llvm/System/Signals.h"
28using namespace clang;
29using namespace clang::driver;
30
31class DriverDiagnosticPrinter : public DiagnosticClient {
32  std::string ProgName;
33  llvm::raw_ostream &OS;
34
35public:
36  DriverDiagnosticPrinter(const std::string _ProgName,
37                          llvm::raw_ostream &_OS)
38    : ProgName(_ProgName),
39      OS(_OS) {}
40
41  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
42                                const DiagnosticInfo &Info);
43};
44
45void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
46                                               const DiagnosticInfo &Info) {
47  OS << ProgName << ": ";
48
49  switch (Level) {
50  case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
51  case Diagnostic::Note:    OS << "note: "; break;
52  case Diagnostic::Warning: OS << "warning: "; break;
53  case Diagnostic::Error:   OS << "error: "; break;
54  case Diagnostic::Fatal:   OS << "fatal error: "; break;
55  }
56
57  llvm::SmallString<100> OutStr;
58  Info.FormatDiagnostic(OutStr);
59  OS.write(OutStr.begin(), OutStr.size());
60  OS << '\n';
61}
62
63llvm::sys::Path GetExecutablePath(const char *Argv0) {
64  // This just needs to be some symbol in the binary; C++ doesn't
65  // allow taking the address of ::main however.
66  void *P = (void*) (intptr_t) GetExecutablePath;
67  return llvm::sys::Path::GetMainExecutable(Argv0, P);
68}
69
70static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
71                                   const std::string &S) {
72  return SavedStrings.insert(S).first->c_str();
73}
74
75/// ApplyQAOverride - Apply a list of edits to the input argument lists.
76///
77/// The input string is a space separate list of edits to perform,
78/// they are applied in order to the input argument lists. Edits
79/// should be one of the following forms:
80///
81///  '#': Silence information about the changes to the command line arguments.
82///
83///  '^': Add FOO as a new argument at the beginning of the command line.
84///
85///  '+': Add FOO as a new argument at the end of the command line.
86///
87///  's/XXX/YYY/': Replace the literal argument XXX by YYY in the
88///  command line.
89///
90///  'xOPTION': Removes all instances of the literal argument OPTION.
91///
92///  'XOPTION': Removes all instances of the literal argument OPTION,
93///  and the following argument.
94///
95///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
96///  at the end of the command line.
97///
98/// \param OS - The stream to write edit information to.
99/// \param Args - The vector of command line arguments.
100/// \param Edit - The override command to perform.
101/// \param SavedStrings - Set to use for storing string representations.
102void ApplyOneQAOverride(llvm::raw_ostream &OS,
103                        std::vector<const char*> &Args,
104                        const std::string &Edit,
105                        std::set<std::string> &SavedStrings) {
106  // This does not need to be efficient.
107
108  if (Edit[0] == '^') {
109    const char *Str =
110      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
111    OS << "### Adding argument " << Str << " at beginning\n";
112    Args.insert(Args.begin() + 1, Str);
113  } else if (Edit[0] == '+') {
114    const char *Str =
115      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
116    OS << "### Adding argument " << Str << " at end\n";
117    Args.push_back(Str);
118  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
119    std::string Option = Edit.substr(1, std::string::npos);
120    for (unsigned i = 1; i < Args.size();) {
121      if (Option == Args[i]) {
122        OS << "### Deleting argument " << Args[i] << '\n';
123        Args.erase(Args.begin() + i);
124        if (Edit[0] == 'X') {
125          if (i < Args.size()) {
126            OS << "### Deleting argument " << Args[i] << '\n';
127            Args.erase(Args.begin() + i);
128          } else
129            OS << "### Invalid X edit, end of command line!\n";
130        }
131      } else
132        ++i;
133    }
134  } else if (Edit[0] == 'O') {
135    for (unsigned i = 1; i < Args.size();) {
136      const char *A = Args[i];
137      if (A[0] == '-' && A[1] == 'O' &&
138          (A[2] == '\0' ||
139           (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
140                             ('0' <= A[2] && A[2] <= '9'))))) {
141        OS << "### Deleting argument " << Args[i] << '\n';
142        Args.erase(Args.begin() + i);
143      } else
144        ++i;
145    }
146    OS << "### Adding argument " << Edit << " at end\n";
147    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));
148  } else {
149    OS << "### Unrecognized edit: " << Edit << "\n";
150  }
151}
152
153/// ApplyQAOverride - Apply a comma separate list of edits to the
154/// input argument lists. See ApplyOneQAOverride.
155void ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,
156                     std::set<std::string> &SavedStrings) {
157  llvm::raw_ostream *OS = &llvm::errs();
158
159  if (OverrideStr[0] == '#') {
160    ++OverrideStr;
161    OS = &llvm::nulls();
162  }
163
164  *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
165
166  // This does not need to be efficient.
167
168  const char *S = OverrideStr;
169  while (*S) {
170    const char *End = ::strchr(S, ' ');
171    if (!End)
172      End = S + strlen(S);
173    if (End != S)
174      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
175    S = End;
176    if (*S != '\0')
177      ++S;
178  }
179}
180
181extern int cc1_main(Diagnostic &Diags,
182                    const char **ArgBegin, const char **ArgEnd);
183
184int main(int argc, const char **argv) {
185  llvm::sys::PrintStackTraceOnErrorSignal();
186  llvm::PrettyStackTraceProgram X(argc, argv);
187
188  llvm::sys::Path Path = GetExecutablePath(argv[0]);
189  DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());
190
191  Diagnostic Diags(&DiagClient);
192
193  // Dispatch to cc1_main if appropriate.
194  if (argc > 1 && llvm::StringRef(argv[1]) == "-cc1")
195    return cc1_main(Diags, argv+2, argv+argc);
196
197#ifdef CLANG_IS_PRODUCTION
198  bool IsProduction = true;
199#else
200  bool IsProduction = false;
201#endif
202  Driver TheDriver(Path.getBasename().c_str(), Path.getDirname().c_str(),
203                   llvm::sys::getHostTriple().c_str(),
204                   "a.out", IsProduction, Diags);
205
206  // Check for ".*++" or ".*++-[^-]*" to determine if we are a C++
207  // compiler. This matches things like "c++", "clang++", and "clang++-1.1".
208  //
209  // Note that we intentionally want to use argv[0] here, to support "clang++"
210  // being a symlink.
211  std::string ProgName(llvm::sys::Path(argv[0]).getBasename());
212  if (llvm::StringRef(ProgName).endswith("++") ||
213      llvm::StringRef(ProgName).rsplit('-').first.endswith("++"))
214    TheDriver.CCCIsCXX = true;
215
216  llvm::OwningPtr<Compilation> C;
217
218  // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
219  // command line behind the scenes.
220  std::set<std::string> SavedStrings;
221  if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
222    // FIXME: Driver shouldn't take extra initial argument.
223    std::vector<const char*> StringPointers(argv, argv + argc);
224
225    ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);
226
227    C.reset(TheDriver.BuildCompilation(StringPointers.size(),
228                                       &StringPointers[0]));
229  } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
230    std::vector<const char*> StringPointers;
231
232    // FIXME: Driver shouldn't take extra initial argument.
233    StringPointers.push_back(argv[0]);
234
235    for (;;) {
236      const char *Next = strchr(Cur, ',');
237
238      if (Next) {
239        StringPointers.push_back(SaveStringInSet(SavedStrings,
240                                                 std::string(Cur, Next)));
241        Cur = Next + 1;
242      } else {
243        if (*Cur != '\0')
244          StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));
245        break;
246      }
247    }
248
249    StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);
250
251    C.reset(TheDriver.BuildCompilation(StringPointers.size(),
252                                       &StringPointers[0]));
253  } else
254    C.reset(TheDriver.BuildCompilation(argc, argv));
255
256  int Res = 0;
257  if (C.get())
258    Res = TheDriver.ExecuteCompilation(*C);
259
260  llvm::llvm_shutdown();
261
262  return Res;
263}
264
265