blob: ef40ae4afbb6abc0ede65378fe06f5fed3c01038 [file] [log] [blame]
Nick Lewycky3fdcc6f2010-12-31 17:31:54 +00001//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
Daniel Dunbar3ede8d02009-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 Dunbar21549232009-03-18 02:55:38 +000011#include "clang/Driver/Action.h"
Daniel Dunbare530ad42009-03-18 22:16:03 +000012#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbar265e9ef2009-11-19 04:25:22 +000014#include "clang/Driver/Options.h"
Daniel Dunbar586dc232009-03-16 06:42:30 +000015#include "clang/Driver/ToolChain.h"
Chad Rosier2b819102011-08-02 17:58:04 +000016#include "llvm/ADT/STLExtras.h"
Chad Rosierc91b41a2012-10-31 18:31:33 +000017#include "llvm/ADT/StringSwitch.h"
Reid Klecknerb1e25a12013-06-14 17:17:23 +000018#include "llvm/Option/ArgList.h"
Rafael Espindolaa372f402013-06-17 17:23:47 +000019#include "llvm/Support/PathV1.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000020#include "llvm/Support/Program.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "llvm/Support/raw_ostream.h"
Daniel Dunbare530ad42009-03-18 22:16:03 +000022#include <errno.h>
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include <sys/stat.h>
Francois Pichet1c3199a2011-07-23 11:36:43 +000024
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000025using namespace clang::driver;
Francois Pichet1c3199a2011-07-23 11:36:43 +000026using namespace clang;
Reid Klecknerb1e25a12013-06-14 17:17:23 +000027using namespace llvm::opt;
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000028
Daniel Dunbar279c1db2010-06-11 22:00:26 +000029Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
30 InputArgList *_Args, DerivedArgList *_TranslatedArgs)
31 : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
Chad Rosier2b819102011-08-02 17:58:04 +000032 TranslatedArgs(_TranslatedArgs), Redirects(0) {
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000033}
34
Mike Stump1eb44332009-09-09 15:08:12 +000035Compilation::~Compilation() {
Daniel Dunbar279c1db2010-06-11 22:00:26 +000036 delete TranslatedArgs;
Daniel Dunbar586dc232009-03-16 06:42:30 +000037 delete Args;
Mike Stump1eb44332009-09-09 15:08:12 +000038
Daniel Dunbar586dc232009-03-16 06:42:30 +000039 // Free any derived arg lists.
Daniel Dunbar49540182009-09-09 18:36:01 +000040 for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
41 DerivedArgList*>::iterator it = TCArgs.begin(),
42 ie = TCArgs.end(); it != ie; ++it)
Daniel Dunbar279c1db2010-06-11 22:00:26 +000043 if (it->second != TranslatedArgs)
44 delete it->second;
Daniel Dunbar21549232009-03-18 02:55:38 +000045
46 // Free the actions, if built.
Mike Stump1eb44332009-09-09 15:08:12 +000047 for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbar21549232009-03-18 02:55:38 +000048 it != ie; ++it)
49 delete *it;
Chad Rosier2b819102011-08-02 17:58:04 +000050
51 // Free redirections of stdout/stderr.
52 if (Redirects) {
53 delete Redirects[1];
54 delete Redirects[2];
55 delete [] Redirects;
56 }
Daniel Dunbar586dc232009-03-16 06:42:30 +000057}
58
Daniel Dunbar49540182009-09-09 18:36:01 +000059const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
60 const char *BoundArch) {
Daniel Dunbar586dc232009-03-16 06:42:30 +000061 if (!TC)
62 TC = &DefaultToolChain;
63
Daniel Dunbar49540182009-09-09 18:36:01 +000064 DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
Daniel Dunbar279c1db2010-06-11 22:00:26 +000065 if (!Entry) {
66 Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
67 if (!Entry)
68 Entry = TranslatedArgs;
69 }
Daniel Dunbar586dc232009-03-16 06:42:30 +000070
Daniel Dunbaraa3e0d22009-03-18 05:58:45 +000071 return *Entry;
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000072}
73
Chris Lattner5f9e2722011-07-23 10:55:15 +000074void Compilation::PrintJob(raw_ostream &OS, const Job &J,
Daniel Dunbar49b98e72009-03-18 22:44:24 +000075 const char *Terminator, bool Quote) const {
76 if (const Command *C = dyn_cast<Command>(&J)) {
Daniel Dunbar24b55602009-03-18 06:49:39 +000077 OS << " \"" << C->getExecutable() << '"';
78 for (ArgStringList::const_iterator it = C->getArguments().begin(),
Daniel Dunbar49b98e72009-03-18 22:44:24 +000079 ie = C->getArguments().end(); it != ie; ++it) {
Daniel Dunbarb86c5fc2010-03-20 08:01:53 +000080 OS << ' ';
Benjamin Kramer5f226142011-10-06 22:53:35 +000081 if (!Quote && !std::strpbrk(*it, " \"\\$")) {
Daniel Dunbarb86c5fc2010-03-20 08:01:53 +000082 OS << *it;
83 continue;
84 }
85
86 // Quote the argument and escape shell special characters; this isn't
87 // really complete but is good enough.
88 OS << '"';
89 for (const char *s = *it; *s; ++s) {
90 if (*s == '"' || *s == '\\' || *s == '$')
91 OS << '\\';
92 OS << *s;
93 }
94 OS << '"';
Daniel Dunbar49b98e72009-03-18 22:44:24 +000095 }
Daniel Dunbar24b55602009-03-18 06:49:39 +000096 OS << Terminator;
Daniel Dunbar24b55602009-03-18 06:49:39 +000097 } else {
Daniel Dunbar49b98e72009-03-18 22:44:24 +000098 const JobList *Jobs = cast<JobList>(&J);
Mike Stump1eb44332009-09-09 15:08:12 +000099 for (JobList::const_iterator
Daniel Dunbar24b55602009-03-18 06:49:39 +0000100 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000101 PrintJob(OS, **it, Terminator, Quote);
Daniel Dunbar24b55602009-03-18 06:49:39 +0000102 }
103}
104
Chad Rosierc91b41a2012-10-31 18:31:33 +0000105static bool skipArg(const char *Flag, bool &SkipNextArg) {
106 StringRef FlagRef(Flag);
107
108 // Assume we're going to see -Flag <Arg>.
109 SkipNextArg = true;
110
111 // These flags are all of the form -Flag <Arg> and are treated as two
112 // arguments. Therefore, we need to skip the flag and the next argument.
113 bool Res = llvm::StringSwitch<bool>(Flag)
114 .Cases("-I", "-MF", "-MT", "-MQ", true)
115 .Cases("-o", "-coverage-file", "-dependency-file", true)
Douglas Gregor250172a2013-02-07 22:59:12 +0000116 .Cases("-fdebug-compilation-dir", "-idirafter", true)
Chad Rosierc91b41a2012-10-31 18:31:33 +0000117 .Cases("-include", "-include-pch", "-internal-isystem", true)
Chad Rosier1cd46de2012-10-31 21:08:30 +0000118 .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
Chad Rosierc91b41a2012-10-31 18:31:33 +0000119 .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true)
120 .Cases("-resource-dir", "-serialize-diagnostic-file", true)
121 .Case("-dwarf-debug-flags", true)
122 .Default(false);
123
124 // Match found.
125 if (Res)
126 return Res;
127
128 // The remaining flags are treated as a single argument.
129 SkipNextArg = false;
130
131 // These flags are all of the form -Flag and have no second argument.
132 Res = llvm::StringSwitch<bool>(Flag)
133 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
134 .Case("-MMD", true)
135 .Default(false);
136
137 // Match found.
138 if (Res)
139 return Res;
140
141 // These flags are treated as a single argument (e.g., -F<Dir>).
142 if (FlagRef.startswith("-F") || FlagRef.startswith("-I"))
143 return true;
144
145 return false;
146}
147
148static bool quoteNextArg(const char *flag) {
149 return llvm::StringSwitch<bool>(flag)
150 .Case("-D", true)
151 .Default(false);
152}
153
154void Compilation::PrintDiagnosticJob(raw_ostream &OS, const Job &J) const {
155 if (const Command *C = dyn_cast<Command>(&J)) {
156 OS << C->getExecutable();
157 unsigned QuoteNextArg = 0;
158 for (ArgStringList::const_iterator it = C->getArguments().begin(),
159 ie = C->getArguments().end(); it != ie; ++it) {
160
161 bool SkipNext;
162 if (skipArg(*it, SkipNext)) {
163 if (SkipNext) ++it;
164 continue;
165 }
166
167 if (!QuoteNextArg)
168 QuoteNextArg = quoteNextArg(*it) ? 2 : 0;
169
170 OS << ' ';
171
172 if (QuoteNextArg == 1)
173 OS << '"';
174
175 if (!std::strpbrk(*it, " \"\\$")) {
176 OS << *it;
177 } else {
178 // Quote the argument and escape shell special characters; this isn't
179 // really complete but is good enough.
180 OS << '"';
181 for (const char *s = *it; *s; ++s) {
182 if (*s == '"' || *s == '\\' || *s == '$')
183 OS << '\\';
184 OS << *s;
185 }
186 OS << '"';
187 }
188
189 if (QuoteNextArg) {
190 if (QuoteNextArg == 1)
191 OS << '"';
192 --QuoteNextArg;
193 }
194 }
195 OS << '\n';
196 } else {
197 const JobList *Jobs = cast<JobList>(&J);
198 for (JobList::const_iterator
199 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
200 PrintDiagnosticJob(OS, **it);
201 }
202}
203
Chad Rosier9d718632013-01-24 19:14:47 +0000204bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
205 llvm::sys::Path P(File);
206 std::string Error;
207
208 // Don't try to remove files which we don't have write access to (but may be
209 // able to remove), or non-regular files. Underlying tools may have
210 // intentionally not overwritten them.
211 if (!P.canWrite() || !P.isRegularFile())
212 return true;
213
214 if (P.eraseFromDisk(false, &Error)) {
215 // Failure is only failure if the file exists and is "regular". There is
216 // a race condition here due to the limited interface of
217 // llvm::sys::Path, we want to know if the removal gave ENOENT.
218
219 // FIXME: Grumble, P.exists() is broken. PR3837.
220 struct stat buf;
221 if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
222 (errno != ENOENT)) {
223 if (IssueErrors)
224 getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
225 << Error;
226 return false;
227 }
228 }
229 return true;
230}
231
Mike Stump1eb44332009-09-09 15:08:12 +0000232bool Compilation::CleanupFileList(const ArgStringList &Files,
Daniel Dunbare530ad42009-03-18 22:16:03 +0000233 bool IssueErrors) const {
234 bool Success = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000235 for (ArgStringList::const_iterator
Chad Rosier9d718632013-01-24 19:14:47 +0000236 it = Files.begin(), ie = Files.end(); it != ie; ++it)
237 Success &= CleanupFile(*it, IssueErrors);
238 return Success;
239}
240
241bool Compilation::CleanupFileMap(const ArgStringMap &Files,
242 const JobAction *JA,
243 bool IssueErrors) const {
244 bool Success = true;
245 for (ArgStringMap::const_iterator
Daniel Dunbare530ad42009-03-18 22:16:03 +0000246 it = Files.begin(), ie = Files.end(); it != ie; ++it) {
Edward O'Callaghan56eec2b2009-11-24 15:23:21 +0000247
Chad Rosier9d718632013-01-24 19:14:47 +0000248 // If specified, only delete the files associated with the JobAction.
249 // Otherwise, delete all files in the map.
250 if (JA && it->first != JA)
Daniel Dunbar8ac127a2011-04-25 20:43:05 +0000251 continue;
Chad Rosier9d718632013-01-24 19:14:47 +0000252 Success &= CleanupFile(it->second, IssueErrors);
Daniel Dunbare530ad42009-03-18 22:16:03 +0000253 }
Daniel Dunbare530ad42009-03-18 22:16:03 +0000254 return Success;
255}
256
Daniel Dunbar31c11eb2009-07-01 19:14:39 +0000257int Compilation::ExecuteCommand(const Command &C,
258 const Command *&FailingCommand) const {
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000259 llvm::sys::Path Prog(C.getExecutable());
260 const char **Argv = new const char*[C.getArguments().size() + 2];
261 Argv[0] = C.getExecutable();
262 std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
263 Argv[C.getArguments().size() + 1] = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chad Rosier2b819102011-08-02 17:58:04 +0000265 if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
266 getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000267 raw_ostream *OS = &llvm::errs();
Daniel Dunbar4c00fcd2010-03-20 08:01:59 +0000268
269 // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
270 // output stream.
271 if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
272 std::string Error;
273 OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
274 Error,
275 llvm::raw_fd_ostream::F_Append);
276 if (!Error.empty()) {
277 getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
278 << Error;
279 FailingCommand = &C;
280 delete OS;
281 return 1;
282 }
283 }
284
285 if (getDriver().CCPrintOptions)
286 *OS << "[Logging clang options]";
287
288 PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
289
290 if (OS != &llvm::errs())
291 delete OS;
292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000294 std::string Error;
Chad Rosierc48d5752013-03-26 23:41:30 +0000295 bool ExecutionFailed;
Rafael Espindola57a3bbf2013-06-13 20:08:52 +0000296 int Res = llvm::sys::ExecuteAndWait(Prog.str(), Argv, /*env*/ 0, Redirects,
Rafael Espindolaa6035692013-06-12 20:44:26 +0000297 /*secondsToWait*/ 0, /*memoryLimit*/ 0,
298 &Error, &ExecutionFailed);
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000299 if (!Error.empty()) {
300 assert(Res && "Error string set with 0 result code!");
301 getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Daniel Dunbar31c11eb2009-07-01 19:14:39 +0000304 if (Res)
305 FailingCommand = &C;
306
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000307 delete[] Argv;
Chad Rosierc48d5752013-03-26 23:41:30 +0000308 return ExecutionFailed ? 1 : Res;
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000309}
310
Chad Rosier4c4df452013-02-27 18:46:04 +0000311typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
312
313static bool ActionFailed(const Action *A,
314 const FailingCommandList &FailingCommands) {
315
316 if (FailingCommands.empty())
317 return false;
318
319 for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
320 CE = FailingCommands.end(); CI != CE; ++CI)
321 if (A == &(CI->second->getSource()))
322 return true;
323
324 for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
325 if (ActionFailed(*AI, FailingCommands))
326 return true;
327
328 return false;
329}
330
331static bool InputsOk(const Command &C,
332 const FailingCommandList &FailingCommands) {
333 return !ActionFailed(&C.getSource(), FailingCommands);
334}
335
Chad Rosiera16355c2013-01-29 20:15:05 +0000336void Compilation::ExecuteJob(const Job &J,
Chad Rosier4c4df452013-02-27 18:46:04 +0000337 FailingCommandList &FailingCommands) const {
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000338 if (const Command *C = dyn_cast<Command>(&J)) {
Chad Rosier4c4df452013-02-27 18:46:04 +0000339 if (!InputsOk(*C, FailingCommands))
340 return;
Chad Rosiera16355c2013-01-29 20:15:05 +0000341 const Command *FailingCommand = 0;
342 if (int Res = ExecuteCommand(*C, FailingCommand))
343 FailingCommands.push_back(std::make_pair(Res, FailingCommand));
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000344 } else {
345 const JobList *Jobs = cast<JobList>(&J);
Chad Rosiera16355c2013-01-29 20:15:05 +0000346 for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end();
347 it != ie; ++it)
348 ExecuteJob(**it, FailingCommands);
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000349 }
350}
Chad Rosier2b819102011-08-02 17:58:04 +0000351
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000352void Compilation::initCompilationForDiagnostics() {
Chad Rosier2b819102011-08-02 17:58:04 +0000353 // Free actions and jobs.
354 DeleteContainerPointers(Actions);
355 Jobs.clear();
356
357 // Clear temporary/results file lists.
358 TempFiles.clear();
359 ResultFiles.clear();
Chad Rosier8425a542013-01-29 23:57:10 +0000360 FailureResultFiles.clear();
Chad Rosier2b819102011-08-02 17:58:04 +0000361
362 // Remove any user specified output. Claim any unclaimed arguments, so as
363 // to avoid emitting warnings about unused args.
Peter Collingbourne54db68b2011-11-06 00:40:05 +0000364 OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
365 options::OPT_MMD };
Chad Rosierf9e156c2012-05-03 21:25:34 +0000366 for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
Peter Collingbourne54db68b2011-11-06 00:40:05 +0000367 if (TranslatedArgs->hasArg(OutputOpts[i]))
368 TranslatedArgs->eraseArg(OutputOpts[i]);
369 }
Chad Rosier2b819102011-08-02 17:58:04 +0000370 TranslatedArgs->ClaimAllArgs();
371
372 // Redirect stdout/stderr to /dev/null.
Rafael Espindola57a3bbf2013-06-13 20:08:52 +0000373 Redirects = new const StringRef*[3]();
374 Redirects[0] = 0;
375 Redirects[1] = new const StringRef();
376 Redirects[2] = new const StringRef();
Chad Rosier2b819102011-08-02 17:58:04 +0000377}
Sebastian Pop4762a2d2012-04-16 04:16:43 +0000378
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000379StringRef Compilation::getSysRoot() const {
Sebastian Pop4762a2d2012-04-16 04:16:43 +0000380 return getDriver().SysRoot;
381}