blob: 32d687e5ca8ff17c4f786cb457108c850e06b977 [file] [log] [blame]
Nick Lewycky6da90772010-12-31 17:31:54 +00001//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
Daniel Dunbar544ecd12009-03-02 19:59:07 +00002//
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/Compilation.h"
Daniel Dunbarf0eddb82009-03-18 02:55:38 +000011#include "clang/Driver/Action.h"
Daniel Dunbar6c17bfd2009-03-18 22:16:03 +000012#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbarda13faf2009-11-19 04:25:22 +000014#include "clang/Driver/Options.h"
Daniel Dunbar3ce436d2009-03-16 06:42:30 +000015#include "clang/Driver/ToolChain.h"
Chad Rosierbe10f982011-08-02 17:58:04 +000016#include "llvm/ADT/STLExtras.h"
Chad Rosier83f16bf2012-10-31 18:31:33 +000017#include "llvm/ADT/StringSwitch.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000018#include "llvm/Option/ArgList.h"
Rafael Espindolafc92e842013-06-18 20:58:25 +000019#include "llvm/Support/FileSystem.h"
Rafael Espindola1600a532013-06-17 17:23:47 +000020#include "llvm/Support/PathV1.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000021#include "llvm/Support/Program.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/raw_ostream.h"
Daniel Dunbar6c17bfd2009-03-18 22:16:03 +000023#include <errno.h>
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include <sys/stat.h>
Francois Pichet24fc69e2011-07-23 11:36:43 +000025
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000026using namespace clang::driver;
Francois Pichet24fc69e2011-07-23 11:36:43 +000027using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000028using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000029
Daniel Dunbar775d4062010-06-11 22:00:26 +000030Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
31 InputArgList *_Args, DerivedArgList *_TranslatedArgs)
32 : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
Chad Rosierbe10f982011-08-02 17:58:04 +000033 TranslatedArgs(_TranslatedArgs), Redirects(0) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +000034}
35
Mike Stump11289f42009-09-09 15:08:12 +000036Compilation::~Compilation() {
Daniel Dunbar775d4062010-06-11 22:00:26 +000037 delete TranslatedArgs;
Daniel Dunbar3ce436d2009-03-16 06:42:30 +000038 delete Args;
Mike Stump11289f42009-09-09 15:08:12 +000039
Daniel Dunbar3ce436d2009-03-16 06:42:30 +000040 // Free any derived arg lists.
Daniel Dunbarb5d86bb2009-09-09 18:36:01 +000041 for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
42 DerivedArgList*>::iterator it = TCArgs.begin(),
43 ie = TCArgs.end(); it != ie; ++it)
Daniel Dunbar775d4062010-06-11 22:00:26 +000044 if (it->second != TranslatedArgs)
45 delete it->second;
Daniel Dunbarf0eddb82009-03-18 02:55:38 +000046
47 // Free the actions, if built.
Mike Stump11289f42009-09-09 15:08:12 +000048 for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbarf0eddb82009-03-18 02:55:38 +000049 it != ie; ++it)
50 delete *it;
Chad Rosierbe10f982011-08-02 17:58:04 +000051
52 // Free redirections of stdout/stderr.
53 if (Redirects) {
54 delete Redirects[1];
55 delete Redirects[2];
56 delete [] Redirects;
57 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +000058}
59
Daniel Dunbarb5d86bb2009-09-09 18:36:01 +000060const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
61 const char *BoundArch) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +000062 if (!TC)
63 TC = &DefaultToolChain;
64
Daniel Dunbarb5d86bb2009-09-09 18:36:01 +000065 DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
Daniel Dunbar775d4062010-06-11 22:00:26 +000066 if (!Entry) {
67 Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
68 if (!Entry)
69 Entry = TranslatedArgs;
70 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +000071
Daniel Dunbaraabaac42009-03-18 05:58:45 +000072 return *Entry;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000073}
74
Chris Lattner0e62c1c2011-07-23 10:55:15 +000075void Compilation::PrintJob(raw_ostream &OS, const Job &J,
Daniel Dunbar64316c42009-03-18 22:44:24 +000076 const char *Terminator, bool Quote) const {
77 if (const Command *C = dyn_cast<Command>(&J)) {
Daniel Dunbar0928b312009-03-18 06:49:39 +000078 OS << " \"" << C->getExecutable() << '"';
79 for (ArgStringList::const_iterator it = C->getArguments().begin(),
Daniel Dunbar64316c42009-03-18 22:44:24 +000080 ie = C->getArguments().end(); it != ie; ++it) {
Daniel Dunbar7c4de042010-03-20 08:01:53 +000081 OS << ' ';
Benjamin Kramer8c26d442011-10-06 22:53:35 +000082 if (!Quote && !std::strpbrk(*it, " \"\\$")) {
Daniel Dunbar7c4de042010-03-20 08:01:53 +000083 OS << *it;
84 continue;
85 }
86
87 // Quote the argument and escape shell special characters; this isn't
88 // really complete but is good enough.
89 OS << '"';
90 for (const char *s = *it; *s; ++s) {
91 if (*s == '"' || *s == '\\' || *s == '$')
92 OS << '\\';
93 OS << *s;
94 }
95 OS << '"';
Daniel Dunbar64316c42009-03-18 22:44:24 +000096 }
Daniel Dunbar0928b312009-03-18 06:49:39 +000097 OS << Terminator;
Daniel Dunbar0928b312009-03-18 06:49:39 +000098 } else {
Daniel Dunbar64316c42009-03-18 22:44:24 +000099 const JobList *Jobs = cast<JobList>(&J);
Mike Stump11289f42009-09-09 15:08:12 +0000100 for (JobList::const_iterator
Daniel Dunbar0928b312009-03-18 06:49:39 +0000101 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
Daniel Dunbar64316c42009-03-18 22:44:24 +0000102 PrintJob(OS, **it, Terminator, Quote);
Daniel Dunbar0928b312009-03-18 06:49:39 +0000103 }
104}
105
Chad Rosier83f16bf2012-10-31 18:31:33 +0000106static bool skipArg(const char *Flag, bool &SkipNextArg) {
107 StringRef FlagRef(Flag);
108
109 // Assume we're going to see -Flag <Arg>.
110 SkipNextArg = true;
111
112 // These flags are all of the form -Flag <Arg> and are treated as two
113 // arguments. Therefore, we need to skip the flag and the next argument.
114 bool Res = llvm::StringSwitch<bool>(Flag)
115 .Cases("-I", "-MF", "-MT", "-MQ", true)
116 .Cases("-o", "-coverage-file", "-dependency-file", true)
Douglas Gregor4bedb492013-02-07 22:59:12 +0000117 .Cases("-fdebug-compilation-dir", "-idirafter", true)
Chad Rosier83f16bf2012-10-31 18:31:33 +0000118 .Cases("-include", "-include-pch", "-internal-isystem", true)
Chad Rosier37756b02012-10-31 21:08:30 +0000119 .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
Chad Rosier83f16bf2012-10-31 18:31:33 +0000120 .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true)
121 .Cases("-resource-dir", "-serialize-diagnostic-file", true)
122 .Case("-dwarf-debug-flags", true)
123 .Default(false);
124
125 // Match found.
126 if (Res)
127 return Res;
128
129 // The remaining flags are treated as a single argument.
130 SkipNextArg = false;
131
132 // These flags are all of the form -Flag and have no second argument.
133 Res = llvm::StringSwitch<bool>(Flag)
134 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
135 .Case("-MMD", true)
136 .Default(false);
137
138 // Match found.
139 if (Res)
140 return Res;
141
142 // These flags are treated as a single argument (e.g., -F<Dir>).
143 if (FlagRef.startswith("-F") || FlagRef.startswith("-I"))
144 return true;
145
146 return false;
147}
148
149static bool quoteNextArg(const char *flag) {
150 return llvm::StringSwitch<bool>(flag)
151 .Case("-D", true)
152 .Default(false);
153}
154
155void Compilation::PrintDiagnosticJob(raw_ostream &OS, const Job &J) const {
156 if (const Command *C = dyn_cast<Command>(&J)) {
157 OS << C->getExecutable();
158 unsigned QuoteNextArg = 0;
159 for (ArgStringList::const_iterator it = C->getArguments().begin(),
160 ie = C->getArguments().end(); it != ie; ++it) {
161
162 bool SkipNext;
163 if (skipArg(*it, SkipNext)) {
164 if (SkipNext) ++it;
165 continue;
166 }
167
168 if (!QuoteNextArg)
169 QuoteNextArg = quoteNextArg(*it) ? 2 : 0;
170
171 OS << ' ';
172
173 if (QuoteNextArg == 1)
174 OS << '"';
175
176 if (!std::strpbrk(*it, " \"\\$")) {
177 OS << *it;
178 } else {
179 // Quote the argument and escape shell special characters; this isn't
180 // really complete but is good enough.
181 OS << '"';
182 for (const char *s = *it; *s; ++s) {
183 if (*s == '"' || *s == '\\' || *s == '$')
184 OS << '\\';
185 OS << *s;
186 }
187 OS << '"';
188 }
189
190 if (QuoteNextArg) {
191 if (QuoteNextArg == 1)
192 OS << '"';
193 --QuoteNextArg;
194 }
195 }
196 OS << '\n';
197 } else {
198 const JobList *Jobs = cast<JobList>(&J);
199 for (JobList::const_iterator
200 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
201 PrintDiagnosticJob(OS, **it);
202 }
203}
204
Chad Rosier633dcdc2013-01-24 19:14:47 +0000205bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
206 llvm::sys::Path P(File);
207 std::string Error;
208
209 // Don't try to remove files which we don't have write access to (but may be
210 // able to remove), or non-regular files. Underlying tools may have
211 // intentionally not overwritten them.
Rafael Espindolafc92e842013-06-18 20:58:25 +0000212 if (!llvm::sys::fs::can_write(File) || !P.isRegularFile())
Chad Rosier633dcdc2013-01-24 19:14:47 +0000213 return true;
214
215 if (P.eraseFromDisk(false, &Error)) {
216 // Failure is only failure if the file exists and is "regular". There is
217 // a race condition here due to the limited interface of
218 // llvm::sys::Path, we want to know if the removal gave ENOENT.
219
220 // FIXME: Grumble, P.exists() is broken. PR3837.
221 struct stat buf;
222 if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
223 (errno != ENOENT)) {
224 if (IssueErrors)
225 getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
226 << Error;
227 return false;
228 }
229 }
230 return true;
231}
232
Mike Stump11289f42009-09-09 15:08:12 +0000233bool Compilation::CleanupFileList(const ArgStringList &Files,
Daniel Dunbar6c17bfd2009-03-18 22:16:03 +0000234 bool IssueErrors) const {
235 bool Success = true;
Mike Stump11289f42009-09-09 15:08:12 +0000236 for (ArgStringList::const_iterator
Chad Rosier633dcdc2013-01-24 19:14:47 +0000237 it = Files.begin(), ie = Files.end(); it != ie; ++it)
238 Success &= CleanupFile(*it, IssueErrors);
239 return Success;
240}
241
242bool Compilation::CleanupFileMap(const ArgStringMap &Files,
243 const JobAction *JA,
244 bool IssueErrors) const {
245 bool Success = true;
246 for (ArgStringMap::const_iterator
Daniel Dunbar6c17bfd2009-03-18 22:16:03 +0000247 it = Files.begin(), ie = Files.end(); it != ie; ++it) {
Edward O'Callaghandb521ec2009-11-24 15:23:21 +0000248
Chad Rosier633dcdc2013-01-24 19:14:47 +0000249 // If specified, only delete the files associated with the JobAction.
250 // Otherwise, delete all files in the map.
251 if (JA && it->first != JA)
Daniel Dunbar462e7ed2011-04-25 20:43:05 +0000252 continue;
Chad Rosier633dcdc2013-01-24 19:14:47 +0000253 Success &= CleanupFile(it->second, IssueErrors);
Daniel Dunbar6c17bfd2009-03-18 22:16:03 +0000254 }
Daniel Dunbar6c17bfd2009-03-18 22:16:03 +0000255 return Success;
256}
257
Daniel Dunbaraa246ca2009-07-01 19:14:39 +0000258int Compilation::ExecuteCommand(const Command &C,
259 const Command *&FailingCommand) const {
Daniel Dunbar1da82ae2009-03-19 08:01:45 +0000260 llvm::sys::Path Prog(C.getExecutable());
261 const char **Argv = new const char*[C.getArguments().size() + 2];
262 Argv[0] = C.getExecutable();
263 std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
264 Argv[C.getArguments().size() + 1] = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000265
Chad Rosierbe10f982011-08-02 17:58:04 +0000266 if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
267 getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000268 raw_ostream *OS = &llvm::errs();
Daniel Dunbar6a8efa82010-03-20 08:01:59 +0000269
270 // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
271 // output stream.
272 if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
273 std::string Error;
274 OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
275 Error,
276 llvm::raw_fd_ostream::F_Append);
277 if (!Error.empty()) {
278 getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
279 << Error;
280 FailingCommand = &C;
281 delete OS;
282 return 1;
283 }
284 }
285
286 if (getDriver().CCPrintOptions)
287 *OS << "[Logging clang options]";
288
289 PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
290
291 if (OS != &llvm::errs())
292 delete OS;
293 }
Mike Stump11289f42009-09-09 15:08:12 +0000294
Daniel Dunbar1da82ae2009-03-19 08:01:45 +0000295 std::string Error;
Chad Rosierd1475772013-03-26 23:41:30 +0000296 bool ExecutionFailed;
Rafael Espindolacb4bb192013-06-13 20:08:52 +0000297 int Res = llvm::sys::ExecuteAndWait(Prog.str(), Argv, /*env*/ 0, Redirects,
Rafael Espindolaa3346d82013-06-12 20:44:26 +0000298 /*secondsToWait*/ 0, /*memoryLimit*/ 0,
299 &Error, &ExecutionFailed);
Daniel Dunbar1da82ae2009-03-19 08:01:45 +0000300 if (!Error.empty()) {
301 assert(Res && "Error string set with 0 result code!");
302 getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
303 }
Mike Stump11289f42009-09-09 15:08:12 +0000304
Daniel Dunbaraa246ca2009-07-01 19:14:39 +0000305 if (Res)
306 FailingCommand = &C;
307
Daniel Dunbar1da82ae2009-03-19 08:01:45 +0000308 delete[] Argv;
Chad Rosierd1475772013-03-26 23:41:30 +0000309 return ExecutionFailed ? 1 : Res;
Daniel Dunbar1da82ae2009-03-19 08:01:45 +0000310}
311
Chad Rosier6a1de5c2013-02-27 18:46:04 +0000312typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
313
314static bool ActionFailed(const Action *A,
315 const FailingCommandList &FailingCommands) {
316
317 if (FailingCommands.empty())
318 return false;
319
320 for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
321 CE = FailingCommands.end(); CI != CE; ++CI)
322 if (A == &(CI->second->getSource()))
323 return true;
324
325 for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
326 if (ActionFailed(*AI, FailingCommands))
327 return true;
328
329 return false;
330}
331
332static bool InputsOk(const Command &C,
333 const FailingCommandList &FailingCommands) {
334 return !ActionFailed(&C.getSource(), FailingCommands);
335}
336
Chad Rosierdd60e092013-01-29 20:15:05 +0000337void Compilation::ExecuteJob(const Job &J,
Chad Rosier6a1de5c2013-02-27 18:46:04 +0000338 FailingCommandList &FailingCommands) const {
Daniel Dunbar64316c42009-03-18 22:44:24 +0000339 if (const Command *C = dyn_cast<Command>(&J)) {
Chad Rosier6a1de5c2013-02-27 18:46:04 +0000340 if (!InputsOk(*C, FailingCommands))
341 return;
Chad Rosierdd60e092013-01-29 20:15:05 +0000342 const Command *FailingCommand = 0;
343 if (int Res = ExecuteCommand(*C, FailingCommand))
344 FailingCommands.push_back(std::make_pair(Res, FailingCommand));
Daniel Dunbar64316c42009-03-18 22:44:24 +0000345 } else {
346 const JobList *Jobs = cast<JobList>(&J);
Chad Rosierdd60e092013-01-29 20:15:05 +0000347 for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end();
348 it != ie; ++it)
349 ExecuteJob(**it, FailingCommands);
Daniel Dunbar64316c42009-03-18 22:44:24 +0000350 }
351}
Chad Rosierbe10f982011-08-02 17:58:04 +0000352
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000353void Compilation::initCompilationForDiagnostics() {
Chad Rosierbe10f982011-08-02 17:58:04 +0000354 // Free actions and jobs.
355 DeleteContainerPointers(Actions);
356 Jobs.clear();
357
358 // Clear temporary/results file lists.
359 TempFiles.clear();
360 ResultFiles.clear();
Chad Rosierc5103c32013-01-29 23:57:10 +0000361 FailureResultFiles.clear();
Chad Rosierbe10f982011-08-02 17:58:04 +0000362
363 // Remove any user specified output. Claim any unclaimed arguments, so as
364 // to avoid emitting warnings about unused args.
Peter Collingbourne9b515cb2011-11-06 00:40:05 +0000365 OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
366 options::OPT_MMD };
Chad Rosier45cf50f2012-05-03 21:25:34 +0000367 for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
Peter Collingbourne9b515cb2011-11-06 00:40:05 +0000368 if (TranslatedArgs->hasArg(OutputOpts[i]))
369 TranslatedArgs->eraseArg(OutputOpts[i]);
370 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000371 TranslatedArgs->ClaimAllArgs();
372
373 // Redirect stdout/stderr to /dev/null.
Rafael Espindolacb4bb192013-06-13 20:08:52 +0000374 Redirects = new const StringRef*[3]();
375 Redirects[0] = 0;
376 Redirects[1] = new const StringRef();
377 Redirects[2] = new const StringRef();
Chad Rosierbe10f982011-08-02 17:58:04 +0000378}
Sebastian Pop980920a2012-04-16 04:16:43 +0000379
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000380StringRef Compilation::getSysRoot() const {
Sebastian Pop980920a2012-04-16 04:16:43 +0000381 return getDriver().SysRoot;
382}