1 //===- Compilation.cpp - Compilation Task Implementation ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Compilation.h"
11 #include "clang/Basic/LLVM.h"
12 #include "clang/Driver/Action.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Job.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "clang/Driver/Util.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/OptSpecifier.h"
25 #include "llvm/Option/Option.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/raw_ostream.h"
30 #include <system_error>
33 using namespace clang;
34 using namespace driver;
35 using namespace llvm::opt;
37 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
38 InputArgList *_Args, DerivedArgList *_TranslatedArgs,
40 : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
41 TranslatedArgs(_TranslatedArgs), ContainsError(ContainsError) {
42 // The offloading host toolchain is the default toolchain.
43 OrderedOffloadingToolchains.insert(
44 std::make_pair(Action::OFK_Host, &DefaultToolChain));
47 Compilation::~Compilation() {
48 // Remove temporary files. This must be done before arguments are freed, as
49 // the file names might be derived from the input arguments.
50 if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
51 CleanupFileList(TempFiles);
53 delete TranslatedArgs;
56 // Free any derived arg lists.
57 for (auto Arg : TCArgs)
58 if (Arg.second != TranslatedArgs)
62 const DerivedArgList &
63 Compilation::getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,
64 Action::OffloadKind DeviceOffloadKind) {
66 TC = &DefaultToolChain;
68 DerivedArgList *&Entry = TCArgs[{TC, BoundArch, DeviceOffloadKind}];
70 SmallVector<Arg *, 4> AllocatedArgs;
71 DerivedArgList *OpenMPArgs = nullptr;
72 // Translate OpenMP toolchain arguments provided via the -Xopenmp-target flags.
73 if (DeviceOffloadKind == Action::OFK_OpenMP) {
74 const ToolChain *HostTC = getSingleOffloadToolChain<Action::OFK_Host>();
75 bool SameTripleAsHost = (TC->getTriple() == HostTC->getTriple());
76 OpenMPArgs = TC->TranslateOpenMPTargetArgs(
77 *TranslatedArgs, SameTripleAsHost, AllocatedArgs);
81 Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch, DeviceOffloadKind);
83 Entry = TranslatedArgs;
85 Entry = TC->TranslateArgs(*OpenMPArgs, BoundArch, DeviceOffloadKind);
92 // Add allocated arguments to the final DAL.
93 for (auto ArgPtr : AllocatedArgs)
94 Entry->AddSynthesizedArg(ArgPtr);
100 bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
101 // FIXME: Why are we trying to remove files that we have not created? For
102 // example we should only try to remove a temporary assembly file if
103 // "clang -cc1" succeed in writing it. Was this a workaround for when
104 // clang was writing directly to a .s file and sometimes leaving it behind
107 // FIXME: If this is necessary, we can still try to split
108 // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
109 // duplicated stat from is_regular_file.
111 // Don't try to remove files which we don't have write access to (but may be
112 // able to remove), or non-regular files. Underlying tools may have
113 // intentionally not overwritten them.
114 if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
117 if (std::error_code EC = llvm::sys::fs::remove(File)) {
118 // Failure is only failure if the file exists and is "regular". We checked
119 // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
120 // so we don't need to check again.
123 getDriver().Diag(diag::err_drv_unable_to_remove_file)
130 bool Compilation::CleanupFileList(const ArgStringList &Files,
131 bool IssueErrors) const {
133 for (const auto &File: Files)
134 Success &= CleanupFile(File, IssueErrors);
138 bool Compilation::CleanupFileMap(const ArgStringMap &Files,
140 bool IssueErrors) const {
142 for (const auto &File : Files) {
143 // If specified, only delete the files associated with the JobAction.
144 // Otherwise, delete all files in the map.
145 if (JA && File.first != JA)
147 Success &= CleanupFile(File.second, IssueErrors);
152 int Compilation::ExecuteCommand(const Command &C,
153 const Command *&FailingCommand) const {
154 if ((getDriver().CCPrintOptions ||
155 getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
156 raw_ostream *OS = &llvm::errs();
158 // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
160 if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
162 OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC,
163 llvm::sys::fs::F_Append |
164 llvm::sys::fs::F_Text);
166 getDriver().Diag(diag::err_drv_cc_print_options_failure)
174 if (getDriver().CCPrintOptions)
175 *OS << "[Logging clang options]";
177 C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
179 if (OS != &llvm::errs())
184 bool ExecutionFailed;
185 int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
186 if (!Error.empty()) {
187 assert(Res && "Error string set with 0 result code!");
188 getDriver().Diag(diag::err_drv_command_failure) << Error;
194 return ExecutionFailed ? 1 : Res;
197 using FailingCommandList = SmallVectorImpl<std::pair<int, const Command *>>;
199 static bool ActionFailed(const Action *A,
200 const FailingCommandList &FailingCommands) {
201 if (FailingCommands.empty())
204 // CUDA/HIP can have the same input source code compiled multiple times so do
205 // not compiled again if there are already failures. It is OK to abort the
206 // CUDA pipeline on errors.
207 if (A->isOffloading(Action::OFK_Cuda) || A->isOffloading(Action::OFK_HIP))
210 for (const auto &CI : FailingCommands)
211 if (A == &(CI.second->getSource()))
214 for (const auto *AI : A->inputs())
215 if (ActionFailed(AI, FailingCommands))
221 static bool InputsOk(const Command &C,
222 const FailingCommandList &FailingCommands) {
223 return !ActionFailed(&C.getSource(), FailingCommands);
226 void Compilation::ExecuteJobs(const JobList &Jobs,
227 FailingCommandList &FailingCommands) const {
228 // According to UNIX standard, driver need to continue compiling all the
229 // inputs on the command line even one of them failed.
230 // In all but CLMode, execute all the jobs unless the necessary inputs for the
231 // job is missing due to previous failures.
232 for (const auto &Job : Jobs) {
233 if (!InputsOk(Job, FailingCommands))
235 const Command *FailingCommand = nullptr;
236 if (int Res = ExecuteCommand(Job, FailingCommand)) {
237 FailingCommands.push_back(std::make_pair(Res, FailingCommand));
238 // Bail as soon as one command fails in cl driver mode.
239 if (TheDriver.IsCLMode())
245 void Compilation::initCompilationForDiagnostics() {
246 ForDiagnostics = true;
248 // Free actions and jobs.
253 // Remove temporary files.
254 if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
255 CleanupFileList(TempFiles);
257 // Clear temporary/results file lists.
260 FailureResultFiles.clear();
262 // Remove any user specified output. Claim any unclaimed arguments, so as
263 // to avoid emitting warnings about unused args.
264 OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
266 for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
267 if (TranslatedArgs->hasArg(OutputOpts[i]))
268 TranslatedArgs->eraseArg(OutputOpts[i]);
270 TranslatedArgs->ClaimAllArgs();
272 // Redirect stdout/stderr to /dev/null.
273 Redirects = {None, {""}, {""}};
275 // Temporary files added by diagnostics should be kept.
276 ForceKeepTempFiles = true;
279 StringRef Compilation::getSysRoot() const {
280 return getDriver().SysRoot;
283 void Compilation::Redirect(ArrayRef<Optional<StringRef>> Redirects) {
284 this->Redirects = Redirects;