xref: /llvm-project/clang/lib/Interpreter/Interpreter.cpp (revision aec92830b79a8c49cdce0d592627d5f18bb6370b)
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 "DeviceOffload.h"
15 #include "IncrementalExecutor.h"
16 #include "IncrementalParser.h"
17 #include "InterpreterUtils.h"
18 
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Mangle.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/DiagnosticSema.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/CodeGen/CodeGenAction.h"
25 #include "clang/CodeGen/ModuleBuilder.h"
26 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
27 #include "clang/Driver/Compilation.h"
28 #include "clang/Driver/Driver.h"
29 #include "clang/Driver/Job.h"
30 #include "clang/Driver/Options.h"
31 #include "clang/Driver/Tool.h"
32 #include "clang/Frontend/CompilerInstance.h"
33 #include "clang/Frontend/TextDiagnosticBuffer.h"
34 #include "clang/Interpreter/Interpreter.h"
35 #include "clang/Interpreter/Value.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "clang/Sema/Lookup.h"
38 #include "llvm/ExecutionEngine/JITSymbol.h"
39 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Support/Errc.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/TargetParser/Host.h"
45 using namespace clang;
46 
47 // FIXME: Figure out how to unify with namespace init_convenience from
48 //        tools/clang-import-test/clang-import-test.cpp
49 namespace {
50 /// Retrieves the clang CC1 specific flags out of the compilation's jobs.
51 /// \returns NULL on error.
52 static llvm::Expected<const llvm::opt::ArgStringList *>
53 GetCC1Arguments(DiagnosticsEngine *Diagnostics,
54                 driver::Compilation *Compilation) {
55   // We expect to get back exactly one Command job, if we didn't something
56   // failed. Extract that job from the Compilation.
57   const driver::JobList &Jobs = Compilation->getJobs();
58   if (!Jobs.size() || !isa<driver::Command>(*Jobs.begin()))
59     return llvm::createStringError(llvm::errc::not_supported,
60                                    "Driver initialization failed. "
61                                    "Unable to create a driver job");
62 
63   // The one job we find should be to invoke clang again.
64   const driver::Command *Cmd = cast<driver::Command>(&(*Jobs.begin()));
65   if (llvm::StringRef(Cmd->getCreator().getName()) != "clang")
66     return llvm::createStringError(llvm::errc::not_supported,
67                                    "Driver initialization failed");
68 
69   return &Cmd->getArguments();
70 }
71 
72 static llvm::Expected<std::unique_ptr<CompilerInstance>>
73 CreateCI(const llvm::opt::ArgStringList &Argv) {
74   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
75   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
76 
77   // Register the support for object-file-wrapped Clang modules.
78   // FIXME: Clang should register these container operations automatically.
79   auto PCHOps = Clang->getPCHContainerOperations();
80   PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
81   PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
82 
83   // Buffer diagnostics from argument parsing so that we can output them using
84   // a well formed diagnostic object.
85   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
86   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
87   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
88   bool Success = CompilerInvocation::CreateFromArgs(
89       Clang->getInvocation(), llvm::ArrayRef(Argv.begin(), Argv.size()), Diags);
90 
91   // Infer the builtin include path if unspecified.
92   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
93       Clang->getHeaderSearchOpts().ResourceDir.empty())
94     Clang->getHeaderSearchOpts().ResourceDir =
95         CompilerInvocation::GetResourcesPath(Argv[0], nullptr);
96 
97   // Create the actual diagnostics engine.
98   Clang->createDiagnostics();
99   if (!Clang->hasDiagnostics())
100     return llvm::createStringError(llvm::errc::not_supported,
101                                    "Initialization failed. "
102                                    "Unable to create diagnostics engine");
103 
104   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
105   if (!Success)
106     return llvm::createStringError(llvm::errc::not_supported,
107                                    "Initialization failed. "
108                                    "Unable to flush diagnostics");
109 
110   // FIXME: Merge with CompilerInstance::ExecuteAction.
111   llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer("").release();
112   Clang->getPreprocessorOpts().addRemappedFile("<<< inputs >>>", MB);
113 
114   Clang->setTarget(TargetInfo::CreateTargetInfo(
115       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
116   if (!Clang->hasTarget())
117     return llvm::createStringError(llvm::errc::not_supported,
118                                    "Initialization failed. "
119                                    "Target is missing");
120 
121   Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts());
122 
123   // Don't clear the AST before backend codegen since we do codegen multiple
124   // times, reusing the same AST.
125   Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
126 
127   Clang->getFrontendOpts().DisableFree = false;
128   Clang->getCodeGenOpts().DisableFree = false;
129   return std::move(Clang);
130 }
131 
132 } // anonymous namespace
133 
134 llvm::Expected<std::unique_ptr<CompilerInstance>>
135 IncrementalCompilerBuilder::create(std::string TT,
136                                    std::vector<const char *> &ClangArgv) {
137 
138   // If we don't know ClangArgv0 or the address of main() at this point, try
139   // to guess it anyway (it's possible on some platforms).
140   std::string MainExecutableName =
141       llvm::sys::fs::getMainExecutable(nullptr, nullptr);
142 
143   ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
144 
145   // Prepending -c to force the driver to do something if no action was
146   // specified. By prepending we allow users to override the default
147   // action and use other actions in incremental mode.
148   // FIXME: Print proper driver diagnostics if the driver flags are wrong.
149   // We do C++ by default; append right after argv[0] if no "-x" given
150   ClangArgv.insert(ClangArgv.end(), "-Xclang");
151   ClangArgv.insert(ClangArgv.end(), "-fincremental-extensions");
152   ClangArgv.insert(ClangArgv.end(), "-c");
153 
154   // Put a dummy C++ file on to ensure there's at least one compile job for the
155   // driver to construct.
156   ClangArgv.push_back("<<< inputs >>>");
157 
158   // Buffer diagnostics from argument parsing so that we can output them using a
159   // well formed diagnostic object.
160   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
161   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
162       CreateAndPopulateDiagOpts(ClangArgv);
163   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
164   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
165 
166   driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags);
167   Driver.setCheckInputsExist(false); // the input comes from mem buffers
168   llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv);
169   std::unique_ptr<driver::Compilation> Compilation(Driver.BuildCompilation(RF));
170 
171   if (Compilation->getArgs().hasArg(driver::options::OPT_v))
172     Compilation->getJobs().Print(llvm::errs(), "\n", /*Quote=*/false);
173 
174   auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
175   if (auto Err = ErrOrCC1Args.takeError())
176     return std::move(Err);
177 
178   return CreateCI(**ErrOrCC1Args);
179 }
180 
181 llvm::Expected<std::unique_ptr<CompilerInstance>>
182 IncrementalCompilerBuilder::CreateCpp() {
183   std::vector<const char *> Argv;
184   Argv.reserve(5 + 1 + UserArgs.size());
185   Argv.push_back("-xc++");
186   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
187 
188   std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
189   return IncrementalCompilerBuilder::create(TT, Argv);
190 }
191 
192 llvm::Expected<std::unique_ptr<CompilerInstance>>
193 IncrementalCompilerBuilder::createCuda(bool device) {
194   std::vector<const char *> Argv;
195   Argv.reserve(5 + 4 + UserArgs.size());
196 
197   Argv.push_back("-xcuda");
198   if (device)
199     Argv.push_back("--cuda-device-only");
200   else
201     Argv.push_back("--cuda-host-only");
202 
203   std::string SDKPathArg = "--cuda-path=";
204   if (!CudaSDKPath.empty()) {
205     SDKPathArg += CudaSDKPath;
206     Argv.push_back(SDKPathArg.c_str());
207   }
208 
209   std::string ArchArg = "--offload-arch=";
210   if (!OffloadArch.empty()) {
211     ArchArg += OffloadArch;
212     Argv.push_back(ArchArg.c_str());
213   }
214 
215   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
216 
217   std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
218   return IncrementalCompilerBuilder::create(TT, Argv);
219 }
220 
221 llvm::Expected<std::unique_ptr<CompilerInstance>>
222 IncrementalCompilerBuilder::CreateCudaDevice() {
223   return IncrementalCompilerBuilder::createCuda(true);
224 }
225 
226 llvm::Expected<std::unique_ptr<CompilerInstance>>
227 IncrementalCompilerBuilder::CreateCudaHost() {
228   return IncrementalCompilerBuilder::createCuda(false);
229 }
230 
231 Interpreter::Interpreter(std::unique_ptr<CompilerInstance> CI,
232                          llvm::Error &Err) {
233   llvm::ErrorAsOutParameter EAO(&Err);
234   auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
235   TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
236   IncrParser = std::make_unique<IncrementalParser>(*this, std::move(CI),
237                                                    *TSCtx->getContext(), Err);
238 }
239 
240 Interpreter::~Interpreter() {
241   if (IncrExecutor) {
242     if (llvm::Error Err = IncrExecutor->cleanUp())
243       llvm::report_fatal_error(
244           llvm::Twine("Failed to clean up IncrementalExecutor: ") +
245           toString(std::move(Err)));
246   }
247 }
248 
249 // These better to put in a runtime header but we can't. This is because we
250 // can't find the precise resource directory in unittests so we have to hard
251 // code them.
252 const char *const Runtimes = R"(
253 #ifdef __cplusplus
254     void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
255     void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
256     void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);
257     void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, float);
258     void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, double);
259     void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, long double);
260     void __clang_Interpreter_SetValueNoAlloc(void*,void*,void*,unsigned long long);
261     struct __clang_Interpreter_NewTag{} __ci_newtag;
262     void* operator new(__SIZE_TYPE__, void* __p, __clang_Interpreter_NewTag) noexcept;
263     template <class T, class = T (*)() /*disable for arrays*/>
264     void __clang_Interpreter_SetValueCopyArr(T* Src, void* Placement, unsigned long Size) {
265       for (auto Idx = 0; Idx < Size; ++Idx)
266         new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]);
267     }
268     template <class T, unsigned long N>
269     void __clang_Interpreter_SetValueCopyArr(const T (*Src)[N], void* Placement, unsigned long Size) {
270       __clang_Interpreter_SetValueCopyArr(Src[0], Placement, Size);
271     }
272 #endif // __cplusplus
273 )";
274 
275 llvm::Expected<std::unique_ptr<Interpreter>>
276 Interpreter::create(std::unique_ptr<CompilerInstance> CI) {
277   llvm::Error Err = llvm::Error::success();
278   auto Interp =
279       std::unique_ptr<Interpreter>(new Interpreter(std::move(CI), Err));
280   if (Err)
281     return std::move(Err);
282 
283   // Add runtime code and set a marker to hide it from user code. Undo will not
284   // go through that.
285   auto PTU = Interp->Parse(Runtimes);
286   if (!PTU)
287     return PTU.takeError();
288   Interp->markUserCodeStart();
289 
290   Interp->ValuePrintingInfo.resize(4);
291   return std::move(Interp);
292 }
293 
294 llvm::Expected<std::unique_ptr<Interpreter>>
295 Interpreter::createWithCUDA(std::unique_ptr<CompilerInstance> CI,
296                             std::unique_ptr<CompilerInstance> DCI) {
297   // avoid writing fat binary to disk using an in-memory virtual file system
298   llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> IMVFS =
299       std::make_unique<llvm::vfs::InMemoryFileSystem>();
300   llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayVFS =
301       std::make_unique<llvm::vfs::OverlayFileSystem>(
302           llvm::vfs::getRealFileSystem());
303   OverlayVFS->pushOverlay(IMVFS);
304   CI->createFileManager(OverlayVFS);
305 
306   auto Interp = Interpreter::create(std::move(CI));
307   if (auto E = Interp.takeError())
308     return std::move(E);
309 
310   llvm::Error Err = llvm::Error::success();
311   auto DeviceParser = std::make_unique<IncrementalCUDADeviceParser>(
312       **Interp, std::move(DCI), *(*Interp)->IncrParser.get(),
313       *(*Interp)->TSCtx->getContext(), IMVFS, Err);
314   if (Err)
315     return std::move(Err);
316 
317   (*Interp)->DeviceParser = std::move(DeviceParser);
318 
319   return Interp;
320 }
321 
322 const CompilerInstance *Interpreter::getCompilerInstance() const {
323   return IncrParser->getCI();
324 }
325 
326 CompilerInstance *Interpreter::getCompilerInstance() {
327   return IncrParser->getCI();
328 }
329 
330 llvm::Expected<llvm::orc::LLJIT &> Interpreter::getExecutionEngine() {
331   if (!IncrExecutor) {
332     if (auto Err = CreateExecutor())
333       return std::move(Err);
334   }
335 
336   return IncrExecutor->GetExecutionEngine();
337 }
338 
339 ASTContext &Interpreter::getASTContext() {
340   return getCompilerInstance()->getASTContext();
341 }
342 
343 const ASTContext &Interpreter::getASTContext() const {
344   return getCompilerInstance()->getASTContext();
345 }
346 
347 void Interpreter::markUserCodeStart() {
348   assert(!InitPTUSize && "We only do this once");
349   InitPTUSize = IncrParser->getPTUs().size();
350 }
351 
352 size_t Interpreter::getEffectivePTUSize() const {
353   std::list<PartialTranslationUnit> &PTUs = IncrParser->getPTUs();
354   assert(PTUs.size() >= InitPTUSize && "empty PTU list?");
355   return PTUs.size() - InitPTUSize;
356 }
357 
358 llvm::Expected<PartialTranslationUnit &>
359 Interpreter::Parse(llvm::StringRef Code) {
360   // If we have a device parser, parse it first.
361   // The generated code will be included in the host compilation
362   if (DeviceParser) {
363     auto DevicePTU = DeviceParser->Parse(Code);
364     if (auto E = DevicePTU.takeError())
365       return std::move(E);
366   }
367 
368   // Tell the interpreter sliently ignore unused expressions since value
369   // printing could cause it.
370   getCompilerInstance()->getDiagnostics().setSeverity(
371       clang::diag::warn_unused_expr, diag::Severity::Ignored, SourceLocation());
372   return IncrParser->Parse(Code);
373 }
374 
375 llvm::Error Interpreter::CreateExecutor() {
376   const clang::TargetInfo &TI =
377       getCompilerInstance()->getASTContext().getTargetInfo();
378   llvm::Error Err = llvm::Error::success();
379   auto Executor = std::make_unique<IncrementalExecutor>(*TSCtx, Err, TI);
380   if (!Err)
381     IncrExecutor = std::move(Executor);
382 
383   return Err;
384 }
385 
386 llvm::Error Interpreter::Execute(PartialTranslationUnit &T) {
387   assert(T.TheModule);
388   if (!IncrExecutor) {
389     auto Err = CreateExecutor();
390     if (Err)
391       return Err;
392   }
393   // FIXME: Add a callback to retain the llvm::Module once the JIT is done.
394   if (auto Err = IncrExecutor->addModule(T))
395     return Err;
396 
397   if (auto Err = IncrExecutor->runCtors())
398     return Err;
399 
400   return llvm::Error::success();
401 }
402 
403 llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) {
404 
405   auto PTU = Parse(Code);
406   if (!PTU)
407     return PTU.takeError();
408   if (PTU->TheModule)
409     if (llvm::Error Err = Execute(*PTU))
410       return Err;
411 
412   if (LastValue.isValid()) {
413     if (!V) {
414       LastValue.dump();
415       LastValue.clear();
416     } else
417       *V = std::move(LastValue);
418   }
419   return llvm::Error::success();
420 }
421 
422 llvm::Expected<llvm::orc::ExecutorAddr>
423 Interpreter::getSymbolAddress(GlobalDecl GD) const {
424   if (!IncrExecutor)
425     return llvm::make_error<llvm::StringError>("Operation failed. "
426                                                "No execution engine",
427                                                std::error_code());
428   llvm::StringRef MangledName = IncrParser->GetMangledName(GD);
429   return getSymbolAddress(MangledName);
430 }
431 
432 llvm::Expected<llvm::orc::ExecutorAddr>
433 Interpreter::getSymbolAddress(llvm::StringRef IRName) const {
434   if (!IncrExecutor)
435     return llvm::make_error<llvm::StringError>("Operation failed. "
436                                                "No execution engine",
437                                                std::error_code());
438 
439   return IncrExecutor->getSymbolAddress(IRName, IncrementalExecutor::IRName);
440 }
441 
442 llvm::Expected<llvm::orc::ExecutorAddr>
443 Interpreter::getSymbolAddressFromLinkerName(llvm::StringRef Name) const {
444   if (!IncrExecutor)
445     return llvm::make_error<llvm::StringError>("Operation failed. "
446                                                "No execution engine",
447                                                std::error_code());
448 
449   return IncrExecutor->getSymbolAddress(Name, IncrementalExecutor::LinkerName);
450 }
451 
452 llvm::Error Interpreter::Undo(unsigned N) {
453 
454   std::list<PartialTranslationUnit> &PTUs = IncrParser->getPTUs();
455   if (N > getEffectivePTUSize())
456     return llvm::make_error<llvm::StringError>("Operation failed. "
457                                                "Too many undos",
458                                                std::error_code());
459   for (unsigned I = 0; I < N; I++) {
460     if (IncrExecutor) {
461       if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back()))
462         return Err;
463     }
464 
465     IncrParser->CleanUpPTU(PTUs.back());
466     PTUs.pop_back();
467   }
468   return llvm::Error::success();
469 }
470 
471 llvm::Error Interpreter::LoadDynamicLibrary(const char *name) {
472   auto EE = getExecutionEngine();
473   if (!EE)
474     return EE.takeError();
475 
476   auto &DL = EE->getDataLayout();
477 
478   if (auto DLSG = llvm::orc::DynamicLibrarySearchGenerator::Load(
479           name, DL.getGlobalPrefix()))
480     EE->getMainJITDylib().addGenerator(std::move(*DLSG));
481   else
482     return DLSG.takeError();
483 
484   return llvm::Error::success();
485 }
486 
487 llvm::Expected<llvm::orc::ExecutorAddr>
488 Interpreter::CompileDtorCall(CXXRecordDecl *CXXRD) {
489   assert(CXXRD && "Cannot compile a destructor for a nullptr");
490   if (auto Dtor = Dtors.find(CXXRD); Dtor != Dtors.end())
491     return Dtor->getSecond();
492 
493   if (CXXRD->hasIrrelevantDestructor())
494     return llvm::orc::ExecutorAddr{};
495 
496   CXXDestructorDecl *DtorRD =
497       getCompilerInstance()->getSema().LookupDestructor(CXXRD);
498 
499   llvm::StringRef Name =
500       IncrParser->GetMangledName(GlobalDecl(DtorRD, Dtor_Base));
501   auto AddrOrErr = getSymbolAddress(Name);
502   if (!AddrOrErr)
503     return AddrOrErr.takeError();
504 
505   Dtors[CXXRD] = *AddrOrErr;
506   return AddrOrErr;
507 }
508 
509 static constexpr llvm::StringRef MagicRuntimeInterface[] = {
510     "__clang_Interpreter_SetValueNoAlloc",
511     "__clang_Interpreter_SetValueWithAlloc",
512     "__clang_Interpreter_SetValueCopyArr", "__ci_newtag"};
513 
514 static std::unique_ptr<RuntimeInterfaceBuilder>
515 createInProcessRuntimeInterfaceBuilder(Interpreter &Interp, ASTContext &Ctx,
516                                        Sema &S);
517 
518 std::unique_ptr<RuntimeInterfaceBuilder> Interpreter::FindRuntimeInterface() {
519   if (llvm::all_of(ValuePrintingInfo, [](Expr *E) { return E != nullptr; }))
520     return nullptr;
521 
522   Sema &S = getCompilerInstance()->getSema();
523   ASTContext &Ctx = S.getASTContext();
524 
525   auto LookupInterface = [&](Expr *&Interface, llvm::StringRef Name) {
526     LookupResult R(S, &Ctx.Idents.get(Name), SourceLocation(),
527                    Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
528     S.LookupQualifiedName(R, Ctx.getTranslationUnitDecl());
529     if (R.empty())
530       return false;
531 
532     CXXScopeSpec CSS;
533     Interface = S.BuildDeclarationNameExpr(CSS, R, /*ADL=*/false).get();
534     return true;
535   };
536 
537   if (!LookupInterface(ValuePrintingInfo[NoAlloc],
538                        MagicRuntimeInterface[NoAlloc]))
539     return nullptr;
540   if (!LookupInterface(ValuePrintingInfo[WithAlloc],
541                        MagicRuntimeInterface[WithAlloc]))
542     return nullptr;
543   if (!LookupInterface(ValuePrintingInfo[CopyArray],
544                        MagicRuntimeInterface[CopyArray]))
545     return nullptr;
546   if (!LookupInterface(ValuePrintingInfo[NewTag],
547                        MagicRuntimeInterface[NewTag]))
548     return nullptr;
549 
550   return createInProcessRuntimeInterfaceBuilder(*this, Ctx, S);
551 }
552 
553 namespace {
554 
555 class InterfaceKindVisitor
556     : public TypeVisitor<InterfaceKindVisitor, Interpreter::InterfaceKind> {
557   friend class InProcessRuntimeInterfaceBuilder;
558 
559   ASTContext &Ctx;
560   Sema &S;
561   Expr *E;
562   llvm::SmallVector<Expr *, 3> Args;
563 
564 public:
565   InterfaceKindVisitor(ASTContext &Ctx, Sema &S, Expr *E)
566       : Ctx(Ctx), S(S), E(E) {}
567 
568   Interpreter::InterfaceKind VisitRecordType(const RecordType *Ty) {
569     return Interpreter::InterfaceKind::WithAlloc;
570   }
571 
572   Interpreter::InterfaceKind
573   VisitMemberPointerType(const MemberPointerType *Ty) {
574     return Interpreter::InterfaceKind::WithAlloc;
575   }
576 
577   Interpreter::InterfaceKind
578   VisitConstantArrayType(const ConstantArrayType *Ty) {
579     return Interpreter::InterfaceKind::CopyArray;
580   }
581 
582   Interpreter::InterfaceKind
583   VisitFunctionProtoType(const FunctionProtoType *Ty) {
584     HandlePtrType(Ty);
585     return Interpreter::InterfaceKind::NoAlloc;
586   }
587 
588   Interpreter::InterfaceKind VisitPointerType(const PointerType *Ty) {
589     HandlePtrType(Ty);
590     return Interpreter::InterfaceKind::NoAlloc;
591   }
592 
593   Interpreter::InterfaceKind VisitReferenceType(const ReferenceType *Ty) {
594     ExprResult AddrOfE = S.CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, E);
595     assert(!AddrOfE.isInvalid() && "Can not create unary expression");
596     Args.push_back(AddrOfE.get());
597     return Interpreter::InterfaceKind::NoAlloc;
598   }
599 
600   Interpreter::InterfaceKind VisitBuiltinType(const BuiltinType *Ty) {
601     if (Ty->isNullPtrType())
602       Args.push_back(E);
603     else if (Ty->isFloatingType())
604       Args.push_back(E);
605     else if (Ty->isIntegralOrEnumerationType())
606       HandleIntegralOrEnumType(Ty);
607     else if (Ty->isVoidType()) {
608       // Do we need to still run `E`?
609     }
610 
611     return Interpreter::InterfaceKind::NoAlloc;
612   }
613 
614   Interpreter::InterfaceKind VisitEnumType(const EnumType *Ty) {
615     HandleIntegralOrEnumType(Ty);
616     return Interpreter::InterfaceKind::NoAlloc;
617   }
618 
619 private:
620   // Force cast these types to uint64 to reduce the number of overloads of
621   // `__clang_Interpreter_SetValueNoAlloc`.
622   void HandleIntegralOrEnumType(const Type *Ty) {
623     TypeSourceInfo *TSI = Ctx.getTrivialTypeSourceInfo(Ctx.UnsignedLongLongTy);
624     ExprResult CastedExpr =
625         S.BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(), E);
626     assert(!CastedExpr.isInvalid() && "Cannot create cstyle cast expr");
627     Args.push_back(CastedExpr.get());
628   }
629 
630   void HandlePtrType(const Type *Ty) {
631     TypeSourceInfo *TSI = Ctx.getTrivialTypeSourceInfo(Ctx.VoidPtrTy);
632     ExprResult CastedExpr =
633         S.BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(), E);
634     assert(!CastedExpr.isInvalid() && "Can not create cstyle cast expression");
635     Args.push_back(CastedExpr.get());
636   }
637 };
638 
639 class InProcessRuntimeInterfaceBuilder : public RuntimeInterfaceBuilder {
640   Interpreter &Interp;
641   ASTContext &Ctx;
642   Sema &S;
643 
644 public:
645   InProcessRuntimeInterfaceBuilder(Interpreter &Interp, ASTContext &C, Sema &S)
646       : Interp(Interp), Ctx(C), S(S) {}
647 
648   TransformExprFunction *getPrintValueTransformer() override {
649     return &transformForValuePrinting;
650   }
651 
652 private:
653   static ExprResult transformForValuePrinting(RuntimeInterfaceBuilder *Builder,
654                                               Expr *E,
655                                               ArrayRef<Expr *> FixedArgs) {
656     auto *B = static_cast<InProcessRuntimeInterfaceBuilder *>(Builder);
657 
658     // Get rid of ExprWithCleanups.
659     if (auto *EWC = llvm::dyn_cast_if_present<ExprWithCleanups>(E))
660       E = EWC->getSubExpr();
661 
662     InterfaceKindVisitor Visitor(B->Ctx, B->S, E);
663 
664     // The Interpreter* parameter and the out parameter `OutVal`.
665     for (Expr *E : FixedArgs)
666       Visitor.Args.push_back(E);
667 
668     QualType Ty = E->getType();
669     QualType DesugaredTy = Ty.getDesugaredType(B->Ctx);
670 
671     // For lvalue struct, we treat it as a reference.
672     if (DesugaredTy->isRecordType() && E->isLValue()) {
673       DesugaredTy = B->Ctx.getLValueReferenceType(DesugaredTy);
674       Ty = B->Ctx.getLValueReferenceType(Ty);
675     }
676 
677     Expr *TypeArg = CStyleCastPtrExpr(B->S, B->Ctx.VoidPtrTy,
678                                       (uintptr_t)Ty.getAsOpaquePtr());
679     // The QualType parameter `OpaqueType`, represented as `void*`.
680     Visitor.Args.push_back(TypeArg);
681 
682     // We push the last parameter based on the type of the Expr. Note we need
683     // special care for rvalue struct.
684     Interpreter::InterfaceKind Kind = Visitor.Visit(&*DesugaredTy);
685     switch (Kind) {
686     case Interpreter::InterfaceKind::WithAlloc:
687     case Interpreter::InterfaceKind::CopyArray: {
688       // __clang_Interpreter_SetValueWithAlloc.
689       ExprResult AllocCall = B->S.ActOnCallExpr(
690           /*Scope=*/nullptr,
691           B->Interp
692               .getValuePrintingInfo()[Interpreter::InterfaceKind::WithAlloc],
693           E->getBeginLoc(), Visitor.Args, E->getEndLoc());
694       assert(!AllocCall.isInvalid() && "Can't create runtime interface call!");
695 
696       TypeSourceInfo *TSI =
697           B->Ctx.getTrivialTypeSourceInfo(Ty, SourceLocation());
698 
699       // Force CodeGen to emit destructor.
700       if (auto *RD = Ty->getAsCXXRecordDecl()) {
701         auto *Dtor = B->S.LookupDestructor(RD);
702         Dtor->addAttr(UsedAttr::CreateImplicit(B->Ctx));
703         B->Interp.getCompilerInstance()->getASTConsumer().HandleTopLevelDecl(
704             DeclGroupRef(Dtor));
705       }
706 
707       // __clang_Interpreter_SetValueCopyArr.
708       if (Kind == Interpreter::InterfaceKind::CopyArray) {
709         const auto *ConstantArrTy =
710             cast<ConstantArrayType>(DesugaredTy.getTypePtr());
711         size_t ArrSize = B->Ctx.getConstantArrayElementCount(ConstantArrTy);
712         Expr *ArrSizeExpr = IntegerLiteralExpr(B->Ctx, ArrSize);
713         Expr *Args[] = {E, AllocCall.get(), ArrSizeExpr};
714         return B->S.ActOnCallExpr(
715             /*Scope *=*/nullptr,
716             B->Interp
717                 .getValuePrintingInfo()[Interpreter::InterfaceKind::CopyArray],
718             SourceLocation(), Args, SourceLocation());
719       }
720       Expr *Args[] = {
721           AllocCall.get(),
722           B->Interp.getValuePrintingInfo()[Interpreter::InterfaceKind::NewTag]};
723       ExprResult CXXNewCall = B->S.BuildCXXNew(
724           E->getSourceRange(),
725           /*UseGlobal=*/true, /*PlacementLParen=*/SourceLocation(), Args,
726           /*PlacementRParen=*/SourceLocation(),
727           /*TypeIdParens=*/SourceRange(), TSI->getType(), TSI, std::nullopt,
728           E->getSourceRange(), E);
729 
730       assert(!CXXNewCall.isInvalid() &&
731              "Can't create runtime placement new call!");
732 
733       return B->S.ActOnFinishFullExpr(CXXNewCall.get(),
734                                       /*DiscardedValue=*/false);
735     }
736       // __clang_Interpreter_SetValueNoAlloc.
737     case Interpreter::InterfaceKind::NoAlloc: {
738       return B->S.ActOnCallExpr(
739           /*Scope=*/nullptr,
740           B->Interp.getValuePrintingInfo()[Interpreter::InterfaceKind::NoAlloc],
741           E->getBeginLoc(), Visitor.Args, E->getEndLoc());
742     }
743     default:
744       llvm_unreachable("Unhandled Interpreter::InterfaceKind");
745     }
746   }
747 };
748 } // namespace
749 
750 static std::unique_ptr<RuntimeInterfaceBuilder>
751 createInProcessRuntimeInterfaceBuilder(Interpreter &Interp, ASTContext &Ctx,
752                                        Sema &S) {
753   return std::make_unique<InProcessRuntimeInterfaceBuilder>(Interp, Ctx, S);
754 }
755 
756 // This synthesizes a call expression to a speciall
757 // function that is responsible for generating the Value.
758 // In general, we transform:
759 //   clang-repl> x
760 // To:
761 //   // 1. If x is a built-in type like int, float.
762 //   __clang_Interpreter_SetValueNoAlloc(ThisInterp, OpaqueValue, xQualType, x);
763 //   // 2. If x is a struct, and a lvalue.
764 //   __clang_Interpreter_SetValueNoAlloc(ThisInterp, OpaqueValue, xQualType,
765 //   &x);
766 //   // 3. If x is a struct, but a rvalue.
767 //   new (__clang_Interpreter_SetValueWithAlloc(ThisInterp, OpaqueValue,
768 //   xQualType)) (x);
769 
770 Expr *Interpreter::SynthesizeExpr(Expr *E) {
771   Sema &S = getCompilerInstance()->getSema();
772   ASTContext &Ctx = S.getASTContext();
773 
774   if (!RuntimeIB) {
775     RuntimeIB = FindRuntimeInterface();
776     AddPrintValueCall = RuntimeIB->getPrintValueTransformer();
777   }
778 
779   assert(AddPrintValueCall &&
780          "We don't have a runtime interface for pretty print!");
781 
782   // Create parameter `ThisInterp`.
783   auto *ThisInterp = CStyleCastPtrExpr(S, Ctx.VoidPtrTy, (uintptr_t)this);
784 
785   // Create parameter `OutVal`.
786   auto *OutValue = CStyleCastPtrExpr(S, Ctx.VoidPtrTy, (uintptr_t)&LastValue);
787 
788   // Build `__clang_Interpreter_SetValue*` call.
789   ExprResult Result =
790       AddPrintValueCall(RuntimeIB.get(), E, {ThisInterp, OutValue});
791 
792   // It could fail, like printing an array type in C. (not supported)
793   if (Result.isInvalid())
794     return E;
795   return Result.get();
796 }
797 
798 // Temporary rvalue struct that need special care.
799 REPL_EXTERNAL_VISIBILITY void *
800 __clang_Interpreter_SetValueWithAlloc(void *This, void *OutVal,
801                                       void *OpaqueType) {
802   Value &VRef = *(Value *)OutVal;
803   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
804   return VRef.getPtr();
805 }
806 
807 // Pointers, lvalue struct that can take as a reference.
808 REPL_EXTERNAL_VISIBILITY void
809 __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType,
810                                     void *Val) {
811   Value &VRef = *(Value *)OutVal;
812   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
813   VRef.setPtr(Val);
814 }
815 
816 REPL_EXTERNAL_VISIBILITY void
817 __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal,
818                                     void *OpaqueType) {
819   Value &VRef = *(Value *)OutVal;
820   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
821 }
822 
823 static void SetValueDataBasedOnQualType(Value &V, unsigned long long Data) {
824   QualType QT = V.getType();
825   if (const auto *ET = QT->getAs<EnumType>())
826     QT = ET->getDecl()->getIntegerType();
827 
828   switch (QT->castAs<BuiltinType>()->getKind()) {
829   default:
830     llvm_unreachable("unknown type kind!");
831 #define X(type, name)                                                          \
832   case BuiltinType::name:                                                      \
833     V.set##name(Data);                                                         \
834     break;
835     REPL_BUILTIN_TYPES
836 #undef X
837   }
838 }
839 
840 REPL_EXTERNAL_VISIBILITY void
841 __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType,
842                                     unsigned long long Val) {
843   Value &VRef = *(Value *)OutVal;
844   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
845   SetValueDataBasedOnQualType(VRef, Val);
846 }
847 
848 REPL_EXTERNAL_VISIBILITY void
849 __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType,
850                                     float Val) {
851   Value &VRef = *(Value *)OutVal;
852   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
853   VRef.setFloat(Val);
854 }
855 
856 REPL_EXTERNAL_VISIBILITY void
857 __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType,
858                                     double Val) {
859   Value &VRef = *(Value *)OutVal;
860   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
861   VRef.setDouble(Val);
862 }
863 
864 REPL_EXTERNAL_VISIBILITY void
865 __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType,
866                                     long double Val) {
867   Value &VRef = *(Value *)OutVal;
868   VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
869   VRef.setLongDouble(Val);
870 }
871 
872 // A trampoline to work around the fact that operator placement new cannot
873 // really be forward declared due to libc++ and libstdc++ declaration mismatch.
874 // FIXME: __clang_Interpreter_NewTag is ODR violation because we get the same
875 // definition in the interpreter runtime. We should move it in a runtime header
876 // which gets included by the interpreter and here.
877 struct __clang_Interpreter_NewTag {};
878 REPL_EXTERNAL_VISIBILITY void *
879 operator new(size_t __sz, void *__p, __clang_Interpreter_NewTag) noexcept {
880   // Just forward to the standard operator placement new.
881   return operator new(__sz, __p);
882 }
883