Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/Compilation.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Compilation.cpp - Compilation Task Implementation ------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "clang/Driver/Compilation.h"
10
#include "clang/Basic/LLVM.h"
11
#include "clang/Driver/Action.h"
12
#include "clang/Driver/Driver.h"
13
#include "clang/Driver/DriverDiagnostic.h"
14
#include "clang/Driver/Job.h"
15
#include "clang/Driver/Options.h"
16
#include "clang/Driver/ToolChain.h"
17
#include "clang/Driver/Util.h"
18
#include "llvm/ADT/None.h"
19
#include "llvm/ADT/STLExtras.h"
20
#include "llvm/ADT/SmallVector.h"
21
#include "llvm/ADT/Triple.h"
22
#include "llvm/Option/ArgList.h"
23
#include "llvm/Option/OptSpecifier.h"
24
#include "llvm/Option/Option.h"
25
#include "llvm/Support/FileSystem.h"
26
#include "llvm/Support/raw_ostream.h"
27
#include <cassert>
28
#include <string>
29
#include <system_error>
30
#include <utility>
31
32
using namespace clang;
33
using namespace driver;
34
using namespace llvm::opt;
35
36
Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
37
                         InputArgList *_Args, DerivedArgList *_TranslatedArgs,
38
                         bool ContainsError)
39
    : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
40
47.4k
      TranslatedArgs(_TranslatedArgs), ContainsError(ContainsError) {
41
  // The offloading host toolchain is the default toolchain.
42
47.4k
  OrderedOffloadingToolchains.insert(
43
47.4k
      std::make_pair(Action::OFK_Host, &DefaultToolChain));
44
47.4k
}
45
46
47.4k
Compilation::~Compilation() {
47
  // Remove temporary files. This must be done before arguments are freed, as
48
  // the file names might be derived from the input arguments.
49
47.4k
  if (!TheDriver.isSaveTempsEnabled() && 
!ForceKeepTempFiles47.3k
)
50
47.2k
    CleanupFileList(TempFiles);
51
52
47.4k
  delete TranslatedArgs;
53
47.4k
  delete Args;
54
55
  // Free any derived arg lists.
56
47.4k
  for (auto Arg : TCArgs)
57
47.3k
    if (Arg.second != TranslatedArgs)
58
30.1k
      delete Arg.second;
59
47.4k
}
60
61
const DerivedArgList &
62
Compilation::getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,
63
106k
                                 Action::OffloadKind DeviceOffloadKind) {
64
106k
  if (!TC)
65
484
    TC = &DefaultToolChain;
66
67
106k
  DerivedArgList *&Entry = TCArgs[{TC, BoundArch, DeviceOffloadKind}];
68
106k
  if (!Entry) {
69
47.4k
    SmallVector<Arg *, 4> AllocatedArgs;
70
47.4k
    DerivedArgList *OpenMPArgs = nullptr;
71
    // Translate OpenMP toolchain arguments provided via the -Xopenmp-target flags.
72
47.4k
    if (DeviceOffloadKind == Action::OFK_OpenMP) {
73
85
      const ToolChain *HostTC = getSingleOffloadToolChain<Action::OFK_Host>();
74
85
      bool SameTripleAsHost = (TC->getTriple() == HostTC->getTriple());
75
85
      OpenMPArgs = TC->TranslateOpenMPTargetArgs(
76
85
          *TranslatedArgs, SameTripleAsHost, AllocatedArgs);
77
85
    }
78
79
47.4k
    DerivedArgList *NewDAL = nullptr;
80
47.4k
    if (!OpenMPArgs) {
81
47.3k
      NewDAL = TC->TranslateXarchArgs(*TranslatedArgs, BoundArch,
82
47.3k
                                      DeviceOffloadKind, &AllocatedArgs);
83
45
    } else {
84
45
      NewDAL = TC->TranslateXarchArgs(*OpenMPArgs, BoundArch, DeviceOffloadKind,
85
45
                                      &AllocatedArgs);
86
45
      if (!NewDAL)
87
45
        NewDAL = OpenMPArgs;
88
0
      else
89
0
        delete OpenMPArgs;
90
45
    }
91
92
47.4k
    if (!NewDAL) {
93
47.3k
      Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch, DeviceOffloadKind);
94
47.3k
      if (!Entry)
95
17.2k
        Entry = TranslatedArgs;
96
50
    } else {
97
50
      Entry = TC->TranslateArgs(*NewDAL, BoundArch, DeviceOffloadKind);
98
50
      if (!Entry)
99
0
        Entry = NewDAL;
100
50
      else
101
50
        delete NewDAL;
102
50
    }
103
104
    // Add allocated arguments to the final DAL.
105
47.4k
    for (auto ArgPtr : AllocatedArgs)
106
53
      Entry->AddSynthesizedArg(ArgPtr);
107
47.4k
  }
108
109
106k
  return *Entry;
110
106k
}
111
112
5.95k
bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
113
  // FIXME: Why are we trying to remove files that we have not created? For
114
  // example we should only try to remove a temporary assembly file if
115
  // "clang -cc1" succeed in writing it. Was this a workaround for when
116
  // clang was writing directly to a .s file and sometimes leaving it behind
117
  // during a failure?
118
119
  // FIXME: If this is necessary, we can still try to split
120
  // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
121
  // duplicated stat from is_regular_file.
122
123
  // Don't try to remove files which we don't have write access to (but may be
124
  // able to remove), or non-regular files. Underlying tools may have
125
  // intentionally not overwritten them.
126
5.95k
  if (!llvm::sys::fs::can_write(File) || 
!llvm::sys::fs::is_regular_file(File)5.84k
)
127
137
    return true;
128
129
5.82k
  if (std::error_code EC = llvm::sys::fs::remove(File)) {
130
    // Failure is only failure if the file exists and is "regular". We checked
131
    // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
132
    // so we don't need to check again.
133
134
0
    if (IssueErrors)
135
0
      getDriver().Diag(diag::err_drv_unable_to_remove_file)
136
0
        << EC.message();
137
0
    return false;
138
0
  }
139
5.82k
  return true;
140
5.82k
}
141
142
bool Compilation::CleanupFileList(const llvm::opt::ArgStringList &Files,
143
47.3k
                                  bool IssueErrors) const {
144
47.3k
  bool Success = true;
145
47.3k
  for (const auto &File: Files)
146
5.82k
    Success &= CleanupFile(File, IssueErrors);
147
47.3k
  return Success;
148
47.3k
}
149
150
bool Compilation::CleanupFileMap(const ArgStringMap &Files,
151
                                 const JobAction *JA,
152
254
                                 bool IssueErrors) const {
153
254
  bool Success = true;
154
194
  for (const auto &File : Files) {
155
    // If specified, only delete the files associated with the JobAction.
156
    // Otherwise, delete all files in the map.
157
194
    if (JA && File.first != JA)
158
63
      continue;
159
131
    Success &= CleanupFile(File.second, IssueErrors);
160
131
  }
161
254
  return Success;
162
254
}
163
164
int Compilation::ExecuteCommand(const Command &C,
165
11.2k
                                const Command *&FailingCommand) const {
166
11.2k
  if ((getDriver().CCPrintOptions ||
167
11.2k
       getArgs().hasArg(options::OPT_v)) && 
!getDriver().CCGenDiagnostics40
) {
168
40
    raw_ostream *OS = &llvm::errs();
169
40
    std::unique_ptr<llvm::raw_fd_ostream> OwnedStream;
170
171
    // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
172
    // output stream.
173
40
    if (getDriver().CCPrintOptions && 
getDriver().CCPrintOptionsFilename1
) {
174
1
      std::error_code EC;
175
1
      OwnedStream.reset(new llvm::raw_fd_ostream(
176
1
          getDriver().CCPrintOptionsFilename, EC,
177
1
          llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text));
178
1
      if (EC) {
179
0
        getDriver().Diag(diag::err_drv_cc_print_options_failure)
180
0
            << EC.message();
181
0
        FailingCommand = &C;
182
0
        return 1;
183
0
      }
184
1
      OS = OwnedStream.get();
185
1
    }
186
187
40
    if (getDriver().CCPrintOptions)
188
1
      *OS << "[Logging clang options]\n";
189
190
40
    C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
191
40
  }
192
193
11.2k
  std::string Error;
194
11.2k
  bool ExecutionFailed;
195
11.2k
  int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
196
11.2k
  if (PostCallback)
197
3
    PostCallback(C, Res);
198
11.2k
  if (!Error.empty()) {
199
2
    assert(Res && "Error string set with 0 result code!");
200
2
    getDriver().Diag(diag::err_drv_command_failure) << Error;
201
2
  }
202
203
11.2k
  if (Res)
204
257
    FailingCommand = &C;
205
206
11.2k
  return ExecutionFailed ? 
12
: Res;
207
11.2k
}
208
209
using FailingCommandList = SmallVectorImpl<std::pair<int, const Command *>>;
210
211
static bool ActionFailed(const Action *A,
212
11.3k
                         const FailingCommandList &FailingCommands) {
213
11.3k
  if (FailingCommands.empty())
214
11.2k
    return false;
215
216
  // CUDA/HIP can have the same input source code compiled multiple times so do
217
  // not compiled again if there are already failures. It is OK to abort the
218
  // CUDA pipeline on errors.
219
144
  if (A->isOffloading(Action::OFK_Cuda) || 
A->isOffloading(Action::OFK_HIP)129
)
220
15
    return true;
221
222
129
  for (const auto &CI : FailingCommands)
223
147
    if (A == &(CI.second->getSource()))
224
35
      return true;
225
226
94
  for (const auto *AI : A->inputs())
227
75
    if (ActionFailed(AI, FailingCommands))
228
41
      return true;
229
230
53
  return false;
231
94
}
232
233
static bool InputsOk(const Command &C,
234
11.2k
                     const FailingCommandList &FailingCommands) {
235
11.2k
  return !ActionFailed(&C.getSource(), FailingCommands);
236
11.2k
}
237
238
void Compilation::ExecuteJobs(const JobList &Jobs,
239
12.3k
                              FailingCommandList &FailingCommands) const {
240
  // According to UNIX standard, driver need to continue compiling all the
241
  // inputs on the command line even one of them failed.
242
  // In all but CLMode, execute all the jobs unless the necessary inputs for the
243
  // job is missing due to previous failures.
244
11.2k
  for (const auto &Job : Jobs) {
245
11.2k
    if (!InputsOk(Job, FailingCommands))
246
50
      continue;
247
11.2k
    const Command *FailingCommand = nullptr;
248
11.2k
    if (int Res = ExecuteCommand(Job, FailingCommand)) {
249
256
      FailingCommands.push_back(std::make_pair(Res, FailingCommand));
250
      // Bail as soon as one command fails in cl driver mode.
251
256
      if (TheDriver.IsCLMode())
252
4
        return;
253
256
    }
254
11.2k
  }
255
12.3k
}
256
257
30
void Compilation::initCompilationForDiagnostics() {
258
30
  ForDiagnostics = true;
259
260
  // Free actions and jobs.
261
30
  Actions.clear();
262
30
  AllActions.clear();
263
30
  Jobs.clear();
264
265
  // Remove temporary files.
266
30
  if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
267
30
    CleanupFileList(TempFiles);
268
269
  // Clear temporary/results file lists.
270
30
  TempFiles.clear();
271
30
  ResultFiles.clear();
272
30
  FailureResultFiles.clear();
273
274
  // Remove any user specified output.  Claim any unclaimed arguments, so as
275
  // to avoid emitting warnings about unused args.
276
30
  OptSpecifier OutputOpts[] = {
277
30
      options::OPT_o,  options::OPT_MD, options::OPT_MMD, options::OPT_M,
278
30
      options::OPT_MM, options::OPT_MF, options::OPT_MG,  options::OPT_MJ,
279
30
      options::OPT_MQ, options::OPT_MT, options::OPT_MV};
280
360
  for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; 
++i330
) {
281
330
    if (TranslatedArgs->hasArg(OutputOpts[i]))
282
8
      TranslatedArgs->eraseArg(OutputOpts[i]);
283
330
  }
284
30
  TranslatedArgs->ClaimAllArgs();
285
286
  // Force re-creation of the toolchain Args, otherwise our modifications just
287
  // above will have no effect.
288
30
  for (auto Arg : TCArgs)
289
30
    if (Arg.second != TranslatedArgs)
290
30
      delete Arg.second;
291
30
  TCArgs.clear();
292
293
  // Redirect stdout/stderr to /dev/null.
294
30
  Redirects = {None, {""}, {""}};
295
296
  // Temporary files added by diagnostics should be kept.
297
30
  ForceKeepTempFiles = true;
298
30
}
299
300
46.9k
StringRef Compilation::getSysRoot() const {
301
46.9k
  return getDriver().SysRoot;
302
46.9k
}
303
304
0
void Compilation::Redirect(ArrayRef<Optional<StringRef>> Redirects) {
305
0
  this->Redirects = Redirects;
306
0
}