Coverage Report

Created: 2022-01-15 10:30

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Interpreter/Interpreter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ Interpreter.cpp - Incremental Compilation and Execution -------===//
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
// This file implements the component which performs incremental code
10
// compilation and execution.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Interpreter/Interpreter.h"
15
16
#include "IncrementalExecutor.h"
17
#include "IncrementalParser.h"
18
19
#include "clang/AST/ASTContext.h"
20
#include "clang/Basic/TargetInfo.h"
21
#include "clang/CodeGen/ModuleBuilder.h"
22
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
23
#include "clang/Driver/Compilation.h"
24
#include "clang/Driver/Driver.h"
25
#include "clang/Driver/Job.h"
26
#include "clang/Driver/Options.h"
27
#include "clang/Driver/Tool.h"
28
#include "clang/Frontend/CompilerInstance.h"
29
#include "clang/Frontend/TextDiagnosticBuffer.h"
30
#include "clang/Lex/PreprocessorOptions.h"
31
32
#include "llvm/IR/Module.h"
33
#include "llvm/Support/Errc.h"
34
#include "llvm/Support/Host.h"
35
36
using namespace clang;
37
38
// FIXME: Figure out how to unify with namespace init_convenience from
39
//        tools/clang-import-test/clang-import-test.cpp
40
namespace {
41
/// Retrieves the clang CC1 specific flags out of the compilation's jobs.
42
/// \returns NULL on error.
43
static llvm::Expected<const llvm::opt::ArgStringList *>
44
GetCC1Arguments(DiagnosticsEngine *Diagnostics,
45
11
                driver::Compilation *Compilation) {
46
  // We expect to get back exactly one Command job, if we didn't something
47
  // failed. Extract that job from the Compilation.
48
11
  const driver::JobList &Jobs = Compilation->getJobs();
49
11
  if (!Jobs.size() || !isa<driver::Command>(*Jobs.begin()))
50
0
    return llvm::createStringError(llvm::errc::not_supported,
51
0
                                   "Driver initialization failed. "
52
0
                                   "Unable to create a driver job");
53
54
  // The one job we find should be to invoke clang again.
55
11
  const driver::Command *Cmd = cast<driver::Command>(&(*Jobs.begin()));
56
11
  if (llvm::StringRef(Cmd->getCreator().getName()) != "clang")
57
0
    return llvm::createStringError(llvm::errc::not_supported,
58
0
                                   "Driver initialization failed");
59
60
11
  return &Cmd->getArguments();
61
11
}
62
63
static llvm::Expected<std::unique_ptr<CompilerInstance>>
64
11
CreateCI(const llvm::opt::ArgStringList &Argv) {
65
11
  std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
66
11
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
67
68
  // Register the support for object-file-wrapped Clang modules.
69
  // FIXME: Clang should register these container operations automatically.
70
11
  auto PCHOps = Clang->getPCHContainerOperations();
71
11
  PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
72
11
  PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
73
74
  // Buffer diagnostics from argument parsing so that we can output them using
75
  // a well formed diagnostic object.
76
11
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
77
11
  TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
78
11
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
79
11
  bool Success = CompilerInvocation::CreateFromArgs(
80
11
      Clang->getInvocation(), llvm::makeArrayRef(Argv.begin(), Argv.size()),
81
11
      Diags);
82
83
  // Infer the builtin include path if unspecified.
84
11
  if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
85
11
      Clang->getHeaderSearchOpts().ResourceDir.empty())
86
0
    Clang->getHeaderSearchOpts().ResourceDir =
87
0
        CompilerInvocation::GetResourcesPath(Argv[0], nullptr);
88
89
  // Create the actual diagnostics engine.
90
11
  Clang->createDiagnostics();
91
11
  if (!Clang->hasDiagnostics())
92
0
    return llvm::createStringError(llvm::errc::not_supported,
93
0
                                   "Initialization failed. "
94
0
                                   "Unable to create diagnostics engine");
95
96
11
  DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
97
11
  if (!Success)
98
0
    return llvm::createStringError(llvm::errc::not_supported,
99
0
                                   "Initialization failed. "
100
0
                                   "Unable to flush diagnostics");
101
102
  // FIXME: Merge with CompilerInstance::ExecuteAction.
103
11
  llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer("").release();
104
11
  Clang->getPreprocessorOpts().addRemappedFile("<<< inputs >>>", MB);
105
106
11
  Clang->setTarget(TargetInfo::CreateTargetInfo(
107
11
      Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
108
11
  if (!Clang->hasTarget())
109
0
    return llvm::createStringError(llvm::errc::not_supported,
110
0
                                   "Initialization failed. "
111
0
                                   "Target is missing");
112
113
11
  Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts());
114
115
  // Don't clear the AST before backend codegen since we do codegen multiple
116
  // times, reusing the same AST.
117
11
  Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
118
119
11
  return std::move(Clang);
120
11
}
121
122
} // anonymous namespace
123
124
llvm::Expected<std::unique_ptr<CompilerInstance>>
125
11
IncrementalCompilerBuilder::create(std::vector<const char *> &ClangArgv) {
126
127
  // If we don't know ClangArgv0 or the address of main() at this point, try
128
  // to guess it anyway (it's possible on some platforms).
129
11
  std::string MainExecutableName =
130
11
      llvm::sys::fs::getMainExecutable(nullptr, nullptr);
131
132
11
  ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
133
134
  // Prepending -c to force the driver to do something if no action was
135
  // specified. By prepending we allow users to override the default
136
  // action and use other actions in incremental mode.
137
  // FIXME: Print proper driver diagnostics if the driver flags are wrong.
138
11
  ClangArgv.insert(ClangArgv.begin() + 1, "-c");
139
140
11
  if (!llvm::is_contained(ClangArgv, " -x")) {
141
    // We do C++ by default; append right after argv[0] if no "-x" given
142
11
    ClangArgv.push_back("-x");
143
11
    ClangArgv.push_back("c++");
144
11
  }
145
146
  // Put a dummy C++ file on to ensure there's at least one compile job for the
147
  // driver to construct.
148
11
  ClangArgv.push_back("<<< inputs >>>");
149
150
  // Buffer diagnostics from argument parsing so that we can output them using a
151
  // well formed diagnostic object.
152
11
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
153
11
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
154
11
      CreateAndPopulateDiagOpts(ClangArgv);
155
11
  TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
156
11
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
157
158
11
  driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0],
159
11
                        llvm::sys::getProcessTriple(), Diags);
160
11
  Driver.setCheckInputsExist(false); // the input comes from mem buffers
161
11
  llvm::ArrayRef<const char *> RF = llvm::makeArrayRef(ClangArgv);
162
11
  std::unique_ptr<driver::Compilation> Compilation(Driver.BuildCompilation(RF));
163
164
11
  if (Compilation->getArgs().hasArg(driver::options::OPT_v))
165
0
    Compilation->getJobs().Print(llvm::errs(), "\n", /*Quote=*/false);
166
167
11
  auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
168
11
  if (auto Err = ErrOrCC1Args.takeError())
169
0
    return std::move(Err);
170
171
11
  return CreateCI(**ErrOrCC1Args);
172
11
}
173
174
Interpreter::Interpreter(std::unique_ptr<CompilerInstance> CI,
175
11
                         llvm::Error &Err) {
176
11
  llvm::ErrorAsOutParameter EAO(&Err);
177
11
  auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
178
11
  TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
179
11
  IncrParser = std::make_unique<IncrementalParser>(std::move(CI),
180
11
                                                   *TSCtx->getContext(), Err);
181
11
}
182
183
11
Interpreter::~Interpreter() {}
184
185
llvm::Expected<std::unique_ptr<Interpreter>>
186
11
Interpreter::create(std::unique_ptr<CompilerInstance> CI) {
187
11
  llvm::Error Err = llvm::Error::success();
188
11
  auto Interp =
189
11
      std::unique_ptr<Interpreter>(new Interpreter(std::move(CI), Err));
190
11
  if (Err)
191
0
    return std::move(Err);
192
11
  return std::move(Interp);
193
11
}
194
195
8
const CompilerInstance *Interpreter::getCompilerInstance() const {
196
8
  return IncrParser->getCI();
197
8
}
198
199
llvm::Expected<PartialTranslationUnit &>
200
51
Interpreter::Parse(llvm::StringRef Code) {
201
51
  return IncrParser->Parse(Code);
202
51
}
203
204
23
llvm::Error Interpreter::Execute(PartialTranslationUnit &T) {
205
23
  assert(T.TheModule);
206
23
  if (!IncrExecutor) {
207
5
    const llvm::Triple &Triple =
208
5
        getCompilerInstance()->getASTContext().getTargetInfo().getTriple();
209
5
    llvm::Error Err = llvm::Error::success();
210
5
    IncrExecutor = std::make_unique<IncrementalExecutor>(*TSCtx, Err, Triple);
211
212
5
    if (Err)
213
0
      return Err;
214
5
  }
215
  // FIXME: Add a callback to retain the llvm::Module once the JIT is done.
216
23
  if (auto Err = IncrExecutor->addModule(std::move(T.TheModule)))
217
0
    return Err;
218
219
23
  if (auto Err = IncrExecutor->runCtors())
220
0
    return Err;
221
222
23
  return llvm::Error::success();
223
23
}
224
225
llvm::Expected<llvm::JITTargetAddress>
226
1
Interpreter::getSymbolAddress(GlobalDecl GD) const {
227
1
  if (!IncrExecutor)
228
0
    return llvm::make_error<llvm::StringError>("Operation failed. "
229
0
                                               "No execution engine",
230
0
                                               std::error_code());
231
1
  llvm::StringRef MangledName = IncrParser->GetMangledName(GD);
232
1
  return getSymbolAddress(MangledName);
233
1
}
234
235
llvm::Expected<llvm::JITTargetAddress>
236
5
Interpreter::getSymbolAddress(llvm::StringRef IRName) const {
237
5
  if (!IncrExecutor)
238
0
    return llvm::make_error<llvm::StringError>("Operation failed. "
239
0
                                               "No execution engine",
240
0
                                               std::error_code());
241
242
5
  return IncrExecutor->getSymbolAddress(IRName, IncrementalExecutor::IRName);
243
5
}
244
245
llvm::Expected<llvm::JITTargetAddress>
246
0
Interpreter::getSymbolAddressFromLinkerName(llvm::StringRef Name) const {
247
0
  if (!IncrExecutor)
248
0
    return llvm::make_error<llvm::StringError>("Operation failed. "
249
0
                                               "No execution engine",
250
0
                                               std::error_code());
251
252
0
  return IncrExecutor->getSymbolAddress(Name, IncrementalExecutor::LinkerName);
253
0
}