1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
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/AST/ASTContext.h"
10 #include "clang/AST/ASTDiagnostic.h"
11 #include "clang/AST/ExternalASTSource.h"
12 #include "clang/AST/PrettyPrinter.h"
13 #include "clang/Basic/DiagnosticIDs.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Basic/TargetInfo.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/CodeGen/CodeGenAction.h"
18 #include "clang/CodeGen/ModuleBuilder.h"
19 #include "clang/Edit/Commit.h"
20 #include "clang/Edit/EditedSource.h"
21 #include "clang/Edit/EditsReceiver.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/CompilerInvocation.h"
24 #include "clang/Frontend/FrontendActions.h"
25 #include "clang/Frontend/FrontendDiagnostic.h"
26 #include "clang/Frontend/FrontendPluginRegistry.h"
27 #include "clang/Frontend/TextDiagnosticBuffer.h"
28 #include "clang/Frontend/TextDiagnosticPrinter.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Parse/ParseAST.h"
31 #include "clang/Rewrite/Core/Rewriter.h"
32 #include "clang/Rewrite/Frontend/FrontendActions.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaConsumer.h"
36 
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ExecutionEngine/ExecutionEngine.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/TargetSelect.h"
43 
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/DynamicLibrary.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Signals.h"
51 
52 #include "ClangDiagnostic.h"
53 #include "ClangExpressionParser.h"
54 #include "ClangUserExpression.h"
55 
56 #include "ASTUtils.h"
57 #include "ClangASTSource.h"
58 #include "ClangDiagnostic.h"
59 #include "ClangExpressionDeclMap.h"
60 #include "ClangExpressionHelper.h"
61 #include "ClangExpressionParser.h"
62 #include "ClangHost.h"
63 #include "ClangModulesDeclVendor.h"
64 #include "ClangPersistentVariables.h"
65 #include "IRDynamicChecks.h"
66 #include "IRForTarget.h"
67 #include "ModuleDependencyCollector.h"
68 
69 #include "lldb/Core/Debugger.h"
70 #include "lldb/Core/Disassembler.h"
71 #include "lldb/Core/Module.h"
72 #include "lldb/Core/StreamFile.h"
73 #include "lldb/Expression/IRExecutionUnit.h"
74 #include "lldb/Expression/IRInterpreter.h"
75 #include "lldb/Host/File.h"
76 #include "lldb/Host/HostInfo.h"
77 #include "lldb/Symbol/ClangASTContext.h"
78 #include "lldb/Symbol/SymbolVendor.h"
79 #include "lldb/Target/ExecutionContext.h"
80 #include "lldb/Target/Language.h"
81 #include "lldb/Target/Process.h"
82 #include "lldb/Target/Target.h"
83 #include "lldb/Target/ThreadPlanCallFunction.h"
84 #include "lldb/Utility/DataBufferHeap.h"
85 #include "lldb/Utility/LLDBAssert.h"
86 #include "lldb/Utility/Log.h"
87 #include "lldb/Utility/Reproducer.h"
88 #include "lldb/Utility/Stream.h"
89 #include "lldb/Utility/StreamString.h"
90 #include "lldb/Utility/StringList.h"
91 
92 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
93 
94 #include <cctype>
95 #include <memory>
96 
97 using namespace clang;
98 using namespace llvm;
99 using namespace lldb_private;
100 
101 //===----------------------------------------------------------------------===//
102 // Utility Methods for Clang
103 //===----------------------------------------------------------------------===//
104 
105 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
106   ClangModulesDeclVendor &m_decl_vendor;
107   ClangPersistentVariables &m_persistent_vars;
108   clang::SourceManager &m_source_mgr;
109   StreamString m_error_stream;
110   bool m_has_errors = false;
111 
112 public:
113   LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
114                             ClangPersistentVariables &persistent_vars,
115                             clang::SourceManager &source_mgr)
116       : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
117         m_source_mgr(source_mgr) {}
118 
119   void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
120                     const clang::Module * /*null*/) override {
121     // Ignore modules that are imported in the wrapper code as these are not
122     // loaded by the user.
123     llvm::StringRef filename =
124         m_source_mgr.getPresumedLoc(import_location).getFilename();
125     if (filename == ClangExpressionSourceCode::g_prefix_file_name)
126       return;
127 
128     SourceModule module;
129 
130     for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
131       module.path.push_back(ConstString(component.first->getName()));
132 
133     StreamString error_stream;
134 
135     ClangModulesDeclVendor::ModuleVector exported_modules;
136     if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
137       m_has_errors = true;
138 
139     for (ClangModulesDeclVendor::ModuleID module : exported_modules)
140       m_persistent_vars.AddHandLoadedClangModule(module);
141   }
142 
143   bool hasErrors() { return m_has_errors; }
144 
145   llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
146 };
147 
148 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
149 public:
150   ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) {
151     DiagnosticOptions *m_options = new DiagnosticOptions(opts);
152     m_options->ShowPresumedLoc = true;
153     m_options->ShowLevel = false;
154     m_os.reset(new llvm::raw_string_ostream(m_output));
155     m_passthrough.reset(
156         new clang::TextDiagnosticPrinter(*m_os, m_options, false));
157   }
158 
159   void ResetManager(DiagnosticManager *manager = nullptr) {
160     m_manager = manager;
161   }
162 
163   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
164                         const clang::Diagnostic &Info) override {
165     // Render diagnostic message to m_output.
166     m_output.clear();
167     m_passthrough->HandleDiagnostic(DiagLevel, Info);
168     m_os->flush();
169 
170     if (m_manager) {
171       lldb_private::DiagnosticSeverity severity;
172       bool make_new_diagnostic = true;
173 
174       switch (DiagLevel) {
175       case DiagnosticsEngine::Level::Fatal:
176       case DiagnosticsEngine::Level::Error:
177         severity = eDiagnosticSeverityError;
178         break;
179       case DiagnosticsEngine::Level::Warning:
180         severity = eDiagnosticSeverityWarning;
181         break;
182       case DiagnosticsEngine::Level::Remark:
183       case DiagnosticsEngine::Level::Ignored:
184         severity = eDiagnosticSeverityRemark;
185         break;
186       case DiagnosticsEngine::Level::Note:
187         m_manager->AppendMessageToDiagnostic(m_output);
188         make_new_diagnostic = false;
189       }
190       if (make_new_diagnostic) {
191         // ClangDiagnostic messages are expected to have no whitespace/newlines
192         // around them.
193         std::string stripped_output = llvm::StringRef(m_output).trim();
194 
195         ClangDiagnostic *new_diagnostic =
196             new ClangDiagnostic(stripped_output, severity, Info.getID());
197         m_manager->AddDiagnostic(new_diagnostic);
198 
199         // Don't store away warning fixits, since the compiler doesn't have
200         // enough context in an expression for the warning to be useful.
201         // FIXME: Should we try to filter out FixIts that apply to our generated
202         // code, and not the user's expression?
203         if (severity == eDiagnosticSeverityError) {
204           size_t num_fixit_hints = Info.getNumFixItHints();
205           for (size_t i = 0; i < num_fixit_hints; i++) {
206             const clang::FixItHint &fixit = Info.getFixItHint(i);
207             if (!fixit.isNull())
208               new_diagnostic->AddFixitHint(fixit);
209           }
210         }
211       }
212     }
213   }
214 
215   clang::TextDiagnosticPrinter *GetPassthrough() { return m_passthrough.get(); }
216 
217 private:
218   DiagnosticManager *m_manager = nullptr;
219   std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
220   /// Output stream of m_passthrough.
221   std::shared_ptr<llvm::raw_string_ostream> m_os;
222   /// Output string filled by m_os.
223   std::string m_output;
224 };
225 
226 static void SetupModuleHeaderPaths(CompilerInstance *compiler,
227                                    std::vector<std::string> include_directories,
228                                    lldb::TargetSP target_sp) {
229   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
230 
231   HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
232 
233   for (const std::string &dir : include_directories) {
234     search_opts.AddPath(dir, frontend::System, false, true);
235     LLDB_LOG(log, "Added user include dir: {0}", dir);
236   }
237 
238   llvm::SmallString<128> module_cache;
239   auto props = ModuleList::GetGlobalModuleListProperties();
240   props.GetClangModulesCachePath().GetPath(module_cache);
241   search_opts.ModuleCachePath = module_cache.str();
242   LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
243 
244   search_opts.ResourceDir = GetClangResourceDir().GetPath();
245 
246   search_opts.ImplicitModuleMaps = true;
247 }
248 
249 //===----------------------------------------------------------------------===//
250 // Implementation of ClangExpressionParser
251 //===----------------------------------------------------------------------===//
252 
253 ClangExpressionParser::ClangExpressionParser(
254     ExecutionContextScope *exe_scope, Expression &expr,
255     bool generate_debug_info, std::vector<std::string> include_directories,
256     std::string filename)
257     : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
258       m_pp_callbacks(nullptr),
259       m_include_directories(std::move(include_directories)),
260       m_filename(std::move(filename)) {
261   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
262 
263   // We can't compile expressions without a target.  So if the exe_scope is
264   // null or doesn't have a target, then we just need to get out of here.  I'll
265   // lldb_assert and not make any of the compiler objects since
266   // I can't return errors directly from the constructor.  Further calls will
267   // check if the compiler was made and
268   // bag out if it wasn't.
269 
270   if (!exe_scope) {
271     lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
272                 __FUNCTION__, __FILE__, __LINE__);
273     return;
274   }
275 
276   lldb::TargetSP target_sp;
277   target_sp = exe_scope->CalculateTarget();
278   if (!target_sp) {
279     lldb_assert(target_sp.get(),
280                 "Can't make an expression parser with a null target.",
281                 __FUNCTION__, __FILE__, __LINE__);
282     return;
283   }
284 
285   // 1. Create a new compiler instance.
286   m_compiler.reset(new CompilerInstance());
287 
288   // When capturing a reproducer, hook up the file collector with clang to
289   // collector modules and headers.
290   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
291     repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
292     m_compiler->setModuleDepCollector(
293         std::make_shared<ModuleDependencyCollectorAdaptor>(
294             fp.GetFileCollector()));
295     DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
296     opts.IncludeSystemHeaders = true;
297     opts.IncludeModuleFiles = true;
298   }
299 
300   // Make sure clang uses the same VFS as LLDB.
301   m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
302 
303   lldb::LanguageType frame_lang =
304       expr.Language(); // defaults to lldb::eLanguageTypeUnknown
305   bool overridden_target_opts = false;
306   lldb_private::LanguageRuntime *lang_rt = nullptr;
307 
308   std::string abi;
309   ArchSpec target_arch;
310   target_arch = target_sp->GetArchitecture();
311 
312   const auto target_machine = target_arch.GetMachine();
313 
314   // If the expression is being evaluated in the context of an existing stack
315   // frame, we introspect to see if the language runtime is available.
316 
317   lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
318   lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
319 
320   // Make sure the user hasn't provided a preferred execution language with
321   // `expression --language X -- ...`
322   if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
323     frame_lang = frame_sp->GetLanguage();
324 
325   if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
326     lang_rt = process_sp->GetLanguageRuntime(frame_lang);
327     LLDB_LOGF(log, "Frame has language of type %s",
328               Language::GetNameForLanguageType(frame_lang));
329   }
330 
331   // 2. Configure the compiler with a set of default options that are
332   // appropriate for most situations.
333   if (target_arch.IsValid()) {
334     std::string triple = target_arch.GetTriple().str();
335     m_compiler->getTargetOpts().Triple = triple;
336     LLDB_LOGF(log, "Using %s as the target triple",
337               m_compiler->getTargetOpts().Triple.c_str());
338   } else {
339     // If we get here we don't have a valid target and just have to guess.
340     // Sometimes this will be ok to just use the host target triple (when we
341     // evaluate say "2+3", but other expressions like breakpoint conditions and
342     // other things that _are_ target specific really shouldn't just be using
343     // the host triple. In such a case the language runtime should expose an
344     // overridden options set (3), below.
345     m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
346     LLDB_LOGF(log, "Using default target triple of %s",
347               m_compiler->getTargetOpts().Triple.c_str());
348   }
349   // Now add some special fixes for known architectures: Any arm32 iOS
350   // environment, but not on arm64
351   if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
352       m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
353       m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
354     m_compiler->getTargetOpts().ABI = "apcs-gnu";
355   }
356   // Supported subsets of x86
357   if (target_machine == llvm::Triple::x86 ||
358       target_machine == llvm::Triple::x86_64) {
359     m_compiler->getTargetOpts().Features.push_back("+sse");
360     m_compiler->getTargetOpts().Features.push_back("+sse2");
361   }
362 
363   // Set the target CPU to generate code for. This will be empty for any CPU
364   // that doesn't really need to make a special
365   // CPU string.
366   m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
367 
368   // Set the target ABI
369   abi = GetClangTargetABI(target_arch);
370   if (!abi.empty())
371     m_compiler->getTargetOpts().ABI = abi;
372 
373   // 3. Now allow the runtime to provide custom configuration options for the
374   // target. In this case, a specialized language runtime is available and we
375   // can query it for extra options. For 99% of use cases, this will not be
376   // needed and should be provided when basic platform detection is not enough.
377   if (lang_rt)
378     overridden_target_opts =
379         lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
380 
381   if (overridden_target_opts)
382     if (log && log->GetVerbose()) {
383       LLDB_LOGV(
384           log, "Using overridden target options for the expression evaluation");
385 
386       auto opts = m_compiler->getTargetOpts();
387       LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
388       LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
389       LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
390       LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
391       LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
392       StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
393       StringList::LogDump(log, opts.Features, "Features");
394     }
395 
396   // 4. Create and install the target on the compiler.
397   m_compiler->createDiagnostics();
398   auto target_info = TargetInfo::CreateTargetInfo(
399       m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
400   if (log) {
401     LLDB_LOGF(log, "Using SIMD alignment: %d",
402               target_info->getSimdDefaultAlign());
403     LLDB_LOGF(log, "Target datalayout string: '%s'",
404               target_info->getDataLayout().getStringRepresentation().c_str());
405     LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
406     LLDB_LOGF(log, "Target vector alignment: %d",
407               target_info->getMaxVectorAlign());
408   }
409   m_compiler->setTarget(target_info);
410 
411   assert(m_compiler->hasTarget());
412 
413   // 5. Set language options.
414   lldb::LanguageType language = expr.Language();
415   LangOptions &lang_opts = m_compiler->getLangOpts();
416 
417   switch (language) {
418   case lldb::eLanguageTypeC:
419   case lldb::eLanguageTypeC89:
420   case lldb::eLanguageTypeC99:
421   case lldb::eLanguageTypeC11:
422     // FIXME: the following language option is a temporary workaround,
423     // to "ask for C, get C++."
424     // For now, the expression parser must use C++ anytime the language is a C
425     // family language, because the expression parser uses features of C++ to
426     // capture values.
427     lang_opts.CPlusPlus = true;
428     break;
429   case lldb::eLanguageTypeObjC:
430     lang_opts.ObjC = true;
431     // FIXME: the following language option is a temporary workaround,
432     // to "ask for ObjC, get ObjC++" (see comment above).
433     lang_opts.CPlusPlus = true;
434 
435     // Clang now sets as default C++14 as the default standard (with
436     // GNU extensions), so we do the same here to avoid mismatches that
437     // cause compiler error when evaluating expressions (e.g. nullptr not found
438     // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
439     // two lines below) so we decide to be consistent with that, but this could
440     // be re-evaluated in the future.
441     lang_opts.CPlusPlus11 = true;
442     break;
443   case lldb::eLanguageTypeC_plus_plus:
444   case lldb::eLanguageTypeC_plus_plus_11:
445   case lldb::eLanguageTypeC_plus_plus_14:
446     lang_opts.CPlusPlus11 = true;
447     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
448     LLVM_FALLTHROUGH;
449   case lldb::eLanguageTypeC_plus_plus_03:
450     lang_opts.CPlusPlus = true;
451     if (process_sp)
452       lang_opts.ObjC =
453           process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
454     break;
455   case lldb::eLanguageTypeObjC_plus_plus:
456   case lldb::eLanguageTypeUnknown:
457   default:
458     lang_opts.ObjC = true;
459     lang_opts.CPlusPlus = true;
460     lang_opts.CPlusPlus11 = true;
461     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
462     break;
463   }
464 
465   lang_opts.Bool = true;
466   lang_opts.WChar = true;
467   lang_opts.Blocks = true;
468   lang_opts.DebuggerSupport =
469       true; // Features specifically for debugger clients
470   if (expr.DesiredResultType() == Expression::eResultTypeId)
471     lang_opts.DebuggerCastResultToId = true;
472 
473   lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
474                                .CharIsSignedByDefault();
475 
476   // Spell checking is a nice feature, but it ends up completing a lot of types
477   // that we didn't strictly speaking need to complete. As a result, we spend a
478   // long time parsing and importing debug information.
479   lang_opts.SpellChecking = false;
480 
481   auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
482   if (clang_expr && clang_expr->DidImportCxxModules()) {
483     LLDB_LOG(log, "Adding lang options for importing C++ modules");
484 
485     lang_opts.Modules = true;
486     // We want to implicitly build modules.
487     lang_opts.ImplicitModules = true;
488     // To automatically import all submodules when we import 'std'.
489     lang_opts.ModulesLocalVisibility = false;
490 
491     // We use the @import statements, so we need this:
492     // FIXME: We could use the modules-ts, but that currently doesn't work.
493     lang_opts.ObjC = true;
494 
495     // Options we need to parse libc++ code successfully.
496     // FIXME: We should ask the driver for the appropriate default flags.
497     lang_opts.GNUMode = true;
498     lang_opts.GNUKeywords = true;
499     lang_opts.DoubleSquareBracketAttributes = true;
500     lang_opts.CPlusPlus11 = true;
501 
502     SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
503                            target_sp);
504   }
505 
506   if (process_sp && lang_opts.ObjC) {
507     if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
508       if (runtime->GetRuntimeVersion() ==
509           ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
510         lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
511       else
512         lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
513                                   VersionTuple(10, 7));
514 
515       if (runtime->HasNewLiteralsAndIndexing())
516         lang_opts.DebuggerObjCLiteral = true;
517     }
518   }
519 
520   lang_opts.ThreadsafeStatics = false;
521   lang_opts.AccessControl = false; // Debuggers get universal access
522   lang_opts.DollarIdents = true;   // $ indicates a persistent variable name
523   // We enable all builtin functions beside the builtins from libc/libm (e.g.
524   // 'fopen'). Those libc functions are already correctly handled by LLDB, and
525   // additionally enabling them as expandable builtins is breaking Clang.
526   lang_opts.NoBuiltin = true;
527 
528   // Set CodeGen options
529   m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
530   m_compiler->getCodeGenOpts().InstrumentFunctions = false;
531   m_compiler->getCodeGenOpts().setFramePointer(
532                                     CodeGenOptions::FramePointerKind::All);
533   if (generate_debug_info)
534     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
535   else
536     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
537 
538   // Disable some warnings.
539   m_compiler->getDiagnostics().setSeverityForGroup(
540       clang::diag::Flavor::WarningOrError, "unused-value",
541       clang::diag::Severity::Ignored, SourceLocation());
542   m_compiler->getDiagnostics().setSeverityForGroup(
543       clang::diag::Flavor::WarningOrError, "odr",
544       clang::diag::Severity::Ignored, SourceLocation());
545 
546   // Inform the target of the language options
547   //
548   // FIXME: We shouldn't need to do this, the target should be immutable once
549   // created. This complexity should be lifted elsewhere.
550   m_compiler->getTarget().adjust(m_compiler->getLangOpts());
551 
552   // 6. Set up the diagnostic buffer for reporting errors
553 
554   auto diag_mgr = new ClangDiagnosticManagerAdapter(
555       m_compiler->getDiagnostics().getDiagnosticOptions());
556   m_compiler->getDiagnostics().setClient(diag_mgr);
557 
558   // 7. Set up the source management objects inside the compiler
559   m_compiler->createFileManager();
560   if (!m_compiler->hasSourceManager())
561     m_compiler->createSourceManager(m_compiler->getFileManager());
562   m_compiler->createPreprocessor(TU_Complete);
563 
564   if (ClangModulesDeclVendor *decl_vendor =
565           target_sp->GetClangModulesDeclVendor()) {
566     ClangPersistentVariables *clang_persistent_vars =
567         llvm::cast<ClangPersistentVariables>(
568             target_sp->GetPersistentExpressionStateForLanguage(
569                 lldb::eLanguageTypeC));
570     std::unique_ptr<PPCallbacks> pp_callbacks(new LLDBPreprocessorCallbacks(
571         *decl_vendor, *clang_persistent_vars, m_compiler->getSourceManager()));
572     m_pp_callbacks =
573         static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
574     m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
575   }
576 
577   // 8. Most of this we get from the CompilerInstance, but we also want to give
578   // the context an ExternalASTSource.
579 
580   auto &PP = m_compiler->getPreprocessor();
581   auto &builtin_context = PP.getBuiltinInfo();
582   builtin_context.initializeBuiltins(PP.getIdentifierTable(),
583                                      m_compiler->getLangOpts());
584 
585   m_compiler->createASTContext();
586   clang::ASTContext &ast_context = m_compiler->getASTContext();
587 
588   m_ast_context.reset(
589       new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
590   m_ast_context->setASTContext(&ast_context);
591 
592   std::string module_name("$__lldb_module");
593 
594   m_llvm_context.reset(new LLVMContext());
595   m_code_generator.reset(CreateLLVMCodeGen(
596       m_compiler->getDiagnostics(), module_name,
597       m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
598       m_compiler->getCodeGenOpts(), *m_llvm_context));
599 }
600 
601 ClangExpressionParser::~ClangExpressionParser() {}
602 
603 namespace {
604 
605 /// \class CodeComplete
606 ///
607 /// A code completion consumer for the clang Sema that is responsible for
608 /// creating the completion suggestions when a user requests completion
609 /// of an incomplete `expr` invocation.
610 class CodeComplete : public CodeCompleteConsumer {
611   CodeCompletionTUInfo m_info;
612 
613   std::string m_expr;
614   unsigned m_position = 0;
615   CompletionRequest &m_request;
616   /// The printing policy we use when printing declarations for our completion
617   /// descriptions.
618   clang::PrintingPolicy m_desc_policy;
619 
620   /// Returns true if the given character can be used in an identifier.
621   /// This also returns true for numbers because for completion we usually
622   /// just iterate backwards over iterators.
623   ///
624   /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
625   static bool IsIdChar(char c) {
626     return c == '_' || std::isalnum(c) || c == '$';
627   }
628 
629   /// Returns true if the given character is used to separate arguments
630   /// in the command line of lldb.
631   static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
632 
633   /// Drops all tokens in front of the expression that are unrelated for
634   /// the completion of the cmd line. 'unrelated' means here that the token
635   /// is not interested for the lldb completion API result.
636   StringRef dropUnrelatedFrontTokens(StringRef cmd) {
637     if (cmd.empty())
638       return cmd;
639 
640     // If we are at the start of a word, then all tokens are unrelated to
641     // the current completion logic.
642     if (IsTokenSeparator(cmd.back()))
643       return StringRef();
644 
645     // Remove all previous tokens from the string as they are unrelated
646     // to completing the current token.
647     StringRef to_remove = cmd;
648     while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
649       to_remove = to_remove.drop_back();
650     }
651     cmd = cmd.drop_front(to_remove.size());
652 
653     return cmd;
654   }
655 
656   /// Removes the last identifier token from the given cmd line.
657   StringRef removeLastToken(StringRef cmd) {
658     while (!cmd.empty() && IsIdChar(cmd.back())) {
659       cmd = cmd.drop_back();
660     }
661     return cmd;
662   }
663 
664   /// Attemps to merge the given completion from the given position into the
665   /// existing command. Returns the completion string that can be returned to
666   /// the lldb completion API.
667   std::string mergeCompletion(StringRef existing, unsigned pos,
668                               StringRef completion) {
669     StringRef existing_command = existing.substr(0, pos);
670     // We rewrite the last token with the completion, so let's drop that
671     // token from the command.
672     existing_command = removeLastToken(existing_command);
673     // We also should remove all previous tokens from the command as they
674     // would otherwise be added to the completion that already has the
675     // completion.
676     existing_command = dropUnrelatedFrontTokens(existing_command);
677     return existing_command.str() + completion.str();
678   }
679 
680 public:
681   /// Constructs a CodeComplete consumer that can be attached to a Sema.
682   /// \param[out] matches
683   ///    The list of matches that the lldb completion API expects as a result.
684   ///    This may already contain matches, so it's only allowed to append
685   ///    to this variable.
686   /// \param[out] expr
687   ///    The whole expression string that we are currently parsing. This
688   ///    string needs to be equal to the input the user typed, and NOT the
689   ///    final code that Clang is parsing.
690   /// \param[out] position
691   ///    The character position of the user cursor in the `expr` parameter.
692   ///
693   CodeComplete(CompletionRequest &request, clang::LangOptions ops,
694                std::string expr, unsigned position)
695       : CodeCompleteConsumer(CodeCompleteOptions()),
696         m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
697         m_position(position), m_request(request), m_desc_policy(ops) {
698 
699     // Ensure that the printing policy is producing a description that is as
700     // short as possible.
701     m_desc_policy.SuppressScope = true;
702     m_desc_policy.SuppressTagKeyword = true;
703     m_desc_policy.FullyQualifiedName = false;
704     m_desc_policy.TerseOutput = true;
705     m_desc_policy.IncludeNewlines = false;
706     m_desc_policy.UseVoidForZeroParams = false;
707     m_desc_policy.Bool = true;
708   }
709 
710   /// Deregisters and destroys this code-completion consumer.
711   ~CodeComplete() override {}
712 
713   /// \name Code-completion filtering
714   /// Check if the result should be filtered out.
715   bool isResultFilteredOut(StringRef Filter,
716                            CodeCompletionResult Result) override {
717     // This code is mostly copied from CodeCompleteConsumer.
718     switch (Result.Kind) {
719     case CodeCompletionResult::RK_Declaration:
720       return !(
721           Result.Declaration->getIdentifier() &&
722           Result.Declaration->getIdentifier()->getName().startswith(Filter));
723     case CodeCompletionResult::RK_Keyword:
724       return !StringRef(Result.Keyword).startswith(Filter);
725     case CodeCompletionResult::RK_Macro:
726       return !Result.Macro->getName().startswith(Filter);
727     case CodeCompletionResult::RK_Pattern:
728       return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
729     }
730     // If we trigger this assert or the above switch yields a warning, then
731     // CodeCompletionResult has been enhanced with more kinds of completion
732     // results. Expand the switch above in this case.
733     assert(false && "Unknown completion result type?");
734     // If we reach this, then we should just ignore whatever kind of unknown
735     // result we got back. We probably can't turn it into any kind of useful
736     // completion suggestion with the existing code.
737     return true;
738   }
739 
740   /// \name Code-completion callbacks
741   /// Process the finalized code-completion results.
742   void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
743                                   CodeCompletionResult *Results,
744                                   unsigned NumResults) override {
745 
746     // The Sema put the incomplete token we try to complete in here during
747     // lexing, so we need to retrieve it here to know what we are completing.
748     StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
749 
750     // Iterate over all the results. Filter out results we don't want and
751     // process the rest.
752     for (unsigned I = 0; I != NumResults; ++I) {
753       // Filter the results with the information from the Sema.
754       if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
755         continue;
756 
757       CodeCompletionResult &R = Results[I];
758       std::string ToInsert;
759       std::string Description;
760       // Handle the different completion kinds that come from the Sema.
761       switch (R.Kind) {
762       case CodeCompletionResult::RK_Declaration: {
763         const NamedDecl *D = R.Declaration;
764         ToInsert = R.Declaration->getNameAsString();
765         // If we have a function decl that has no arguments we want to
766         // complete the empty parantheses for the user. If the function has
767         // arguments, we at least complete the opening bracket.
768         if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
769           if (F->getNumParams() == 0)
770             ToInsert += "()";
771           else
772             ToInsert += "(";
773           raw_string_ostream OS(Description);
774           F->print(OS, m_desc_policy, false);
775           OS.flush();
776         } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
777           Description = V->getType().getAsString(m_desc_policy);
778         } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
779           Description = F->getType().getAsString(m_desc_policy);
780         } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
781           // If we try to complete a namespace, then we can directly append
782           // the '::'.
783           if (!N->isAnonymousNamespace())
784             ToInsert += "::";
785         }
786         break;
787       }
788       case CodeCompletionResult::RK_Keyword:
789         ToInsert = R.Keyword;
790         break;
791       case CodeCompletionResult::RK_Macro:
792         ToInsert = R.Macro->getName().str();
793         break;
794       case CodeCompletionResult::RK_Pattern:
795         ToInsert = R.Pattern->getTypedText();
796         break;
797       }
798       // At this point all information is in the ToInsert string.
799 
800       // We also filter some internal lldb identifiers here. The user
801       // shouldn't see these.
802       if (StringRef(ToInsert).startswith("$__lldb_"))
803         continue;
804       if (!ToInsert.empty()) {
805         // Merge the suggested Token into the existing command line to comply
806         // with the kind of result the lldb API expects.
807         std::string CompletionSuggestion =
808             mergeCompletion(m_expr, m_position, ToInsert);
809         m_request.AddCompletion(CompletionSuggestion, Description);
810       }
811     }
812   }
813 
814   /// \param S the semantic-analyzer object for which code-completion is being
815   /// done.
816   ///
817   /// \param CurrentArg the index of the current argument.
818   ///
819   /// \param Candidates an array of overload candidates.
820   ///
821   /// \param NumCandidates the number of overload candidates
822   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
823                                  OverloadCandidate *Candidates,
824                                  unsigned NumCandidates,
825                                  SourceLocation OpenParLoc) override {
826     // At the moment we don't filter out any overloaded candidates.
827   }
828 
829   CodeCompletionAllocator &getAllocator() override {
830     return m_info.getAllocator();
831   }
832 
833   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
834 };
835 } // namespace
836 
837 bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
838                                      unsigned pos, unsigned typed_pos) {
839   DiagnosticManager mgr;
840   // We need the raw user expression here because that's what the CodeComplete
841   // class uses to provide completion suggestions.
842   // However, the `Text` method only gives us the transformed expression here.
843   // To actually get the raw user input here, we have to cast our expression to
844   // the LLVMUserExpression which exposes the right API. This should never fail
845   // as we always have a ClangUserExpression whenever we call this.
846   ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
847   CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr->GetUserText(),
848                   typed_pos);
849   // We don't need a code generator for parsing.
850   m_code_generator.reset();
851   // Start parsing the expression with our custom code completion consumer.
852   ParseInternal(mgr, &CC, line, pos);
853   return true;
854 }
855 
856 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
857   return ParseInternal(diagnostic_manager);
858 }
859 
860 unsigned
861 ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
862                                      CodeCompleteConsumer *completion_consumer,
863                                      unsigned completion_line,
864                                      unsigned completion_column) {
865   ClangDiagnosticManagerAdapter *adapter =
866       static_cast<ClangDiagnosticManagerAdapter *>(
867           m_compiler->getDiagnostics().getClient());
868   auto diag_buf = adapter->GetPassthrough();
869 
870   adapter->ResetManager(&diagnostic_manager);
871 
872   const char *expr_text = m_expr.Text();
873 
874   clang::SourceManager &source_mgr = m_compiler->getSourceManager();
875   bool created_main_file = false;
876 
877   // Clang wants to do completion on a real file known by Clang's file manager,
878   // so we have to create one to make this work.
879   // TODO: We probably could also simulate to Clang's file manager that there
880   // is a real file that contains our code.
881   bool should_create_file = completion_consumer != nullptr;
882 
883   // We also want a real file on disk if we generate full debug info.
884   should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
885                         codegenoptions::FullDebugInfo;
886 
887   if (should_create_file) {
888     int temp_fd = -1;
889     llvm::SmallString<128> result_path;
890     if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
891       tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
892       std::string temp_source_path = tmpdir_file_spec.GetPath();
893       llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
894     } else {
895       llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
896     }
897 
898     if (temp_fd != -1) {
899       lldb_private::File file(temp_fd, File::eOpenOptionWrite, true);
900       const size_t expr_text_len = strlen(expr_text);
901       size_t bytes_written = expr_text_len;
902       if (file.Write(expr_text, bytes_written).Success()) {
903         if (bytes_written == expr_text_len) {
904           file.Close();
905           if (auto fileEntry =
906                   m_compiler->getFileManager().getFile(result_path)) {
907             source_mgr.setMainFileID(source_mgr.createFileID(
908                 *fileEntry,
909                 SourceLocation(), SrcMgr::C_User));
910             created_main_file = true;
911           }
912         }
913       }
914     }
915   }
916 
917   if (!created_main_file) {
918     std::unique_ptr<MemoryBuffer> memory_buffer =
919         MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
920     source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
921   }
922 
923   diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
924                             &m_compiler->getPreprocessor());
925 
926   ClangExpressionHelper *type_system_helper =
927       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
928 
929   // If we want to parse for code completion, we need to attach our code
930   // completion consumer to the Sema and specify a completion position.
931   // While parsing the Sema will call this consumer with the provided
932   // completion suggestions.
933   if (completion_consumer) {
934     auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
935     auto &PP = m_compiler->getPreprocessor();
936     // Lines and columns start at 1 in Clang, but code completion positions are
937     // indexed from 0, so we need to add 1 to the line and column here.
938     ++completion_line;
939     ++completion_column;
940     PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
941   }
942 
943   ASTConsumer *ast_transformer =
944       type_system_helper->ASTTransformer(m_code_generator.get());
945 
946   std::unique_ptr<clang::ASTConsumer> Consumer;
947   if (ast_transformer) {
948     Consumer.reset(new ASTConsumerForwarder(ast_transformer));
949   } else if (m_code_generator) {
950     Consumer.reset(new ASTConsumerForwarder(m_code_generator.get()));
951   } else {
952     Consumer.reset(new ASTConsumer());
953   }
954 
955   clang::ASTContext &ast_context = m_compiler->getASTContext();
956 
957   m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
958                                *Consumer, TU_Complete, completion_consumer));
959   m_compiler->setASTConsumer(std::move(Consumer));
960 
961   if (ast_context.getLangOpts().Modules) {
962     m_compiler->createModuleManager();
963     m_ast_context->setSema(&m_compiler->getSema());
964   }
965 
966   ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
967   if (decl_map) {
968     decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
969 
970     clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
971 
972     if (ast_context.getExternalSource()) {
973       auto module_wrapper =
974           new ExternalASTSourceWrapper(ast_context.getExternalSource());
975 
976       auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
977 
978       auto multiplexer =
979           new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
980       IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
981       ast_context.setExternalSource(Source);
982     } else {
983       ast_context.setExternalSource(ast_source);
984     }
985     decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
986   }
987 
988   // Check that the ASTReader is properly attached to ASTContext and Sema.
989   if (ast_context.getLangOpts().Modules) {
990     assert(m_compiler->getASTContext().getExternalSource() &&
991            "ASTContext doesn't know about the ASTReader?");
992     assert(m_compiler->getSema().getExternalSource() &&
993            "Sema doesn't know about the ASTReader?");
994   }
995 
996   {
997     llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
998         &m_compiler->getSema());
999     ParseAST(m_compiler->getSema(), false, false);
1000   }
1001 
1002   // Make sure we have no pointer to the Sema we are about to destroy.
1003   if (ast_context.getLangOpts().Modules)
1004     m_ast_context->setSema(nullptr);
1005   // Destroy the Sema. This is necessary because we want to emulate the
1006   // original behavior of ParseAST (which also destroys the Sema after parsing).
1007   m_compiler->setSema(nullptr);
1008 
1009   diag_buf->EndSourceFile();
1010 
1011   unsigned num_errors = diag_buf->getNumErrors();
1012 
1013   if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1014     num_errors++;
1015     diagnostic_manager.PutString(eDiagnosticSeverityError,
1016                                  "while importing modules:");
1017     diagnostic_manager.AppendMessageToDiagnostic(
1018         m_pp_callbacks->getErrorString());
1019   }
1020 
1021   if (!num_errors) {
1022     if (type_system_helper->DeclMap() &&
1023         !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
1024       diagnostic_manager.Printf(eDiagnosticSeverityError,
1025                                 "Couldn't infer the type of a variable");
1026       num_errors++;
1027     }
1028   }
1029 
1030   if (!num_errors) {
1031     type_system_helper->CommitPersistentDecls();
1032   }
1033 
1034   adapter->ResetManager();
1035 
1036   return num_errors;
1037 }
1038 
1039 std::string
1040 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1041   std::string abi;
1042 
1043   if (target_arch.IsMIPS()) {
1044     switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1045     case ArchSpec::eMIPSABI_N64:
1046       abi = "n64";
1047       break;
1048     case ArchSpec::eMIPSABI_N32:
1049       abi = "n32";
1050       break;
1051     case ArchSpec::eMIPSABI_O32:
1052       abi = "o32";
1053       break;
1054     default:
1055       break;
1056     }
1057   }
1058   return abi;
1059 }
1060 
1061 bool ClangExpressionParser::RewriteExpression(
1062     DiagnosticManager &diagnostic_manager) {
1063   clang::SourceManager &source_manager = m_compiler->getSourceManager();
1064   clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1065                                    nullptr);
1066   clang::edit::Commit commit(editor);
1067   clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1068 
1069   class RewritesReceiver : public edit::EditsReceiver {
1070     Rewriter &rewrite;
1071 
1072   public:
1073     RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1074 
1075     void insert(SourceLocation loc, StringRef text) override {
1076       rewrite.InsertText(loc, text);
1077     }
1078     void replace(CharSourceRange range, StringRef text) override {
1079       rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1080     }
1081   };
1082 
1083   RewritesReceiver rewrites_receiver(rewriter);
1084 
1085   const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1086   size_t num_diags = diagnostics.size();
1087   if (num_diags == 0)
1088     return false;
1089 
1090   for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
1091     const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
1092     if (diagnostic && diagnostic->HasFixIts()) {
1093       for (const FixItHint &fixit : diagnostic->FixIts()) {
1094         // This is cobbed from clang::Rewrite::FixItRewriter.
1095         if (fixit.CodeToInsert.empty()) {
1096           if (fixit.InsertFromRange.isValid()) {
1097             commit.insertFromRange(fixit.RemoveRange.getBegin(),
1098                                    fixit.InsertFromRange, /*afterToken=*/false,
1099                                    fixit.BeforePreviousInsertions);
1100           } else
1101             commit.remove(fixit.RemoveRange);
1102         } else {
1103           if (fixit.RemoveRange.isTokenRange() ||
1104               fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
1105             commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1106           else
1107             commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1108                           /*afterToken=*/false, fixit.BeforePreviousInsertions);
1109         }
1110       }
1111     }
1112   }
1113 
1114   // FIXME - do we want to try to propagate specific errors here?
1115   if (!commit.isCommitable())
1116     return false;
1117   else if (!editor.commit(commit))
1118     return false;
1119 
1120   // Now play all the edits, and stash the result in the diagnostic manager.
1121   editor.applyRewrites(rewrites_receiver);
1122   RewriteBuffer &main_file_buffer =
1123       rewriter.getEditBuffer(source_manager.getMainFileID());
1124 
1125   std::string fixed_expression;
1126   llvm::raw_string_ostream out_stream(fixed_expression);
1127 
1128   main_file_buffer.write(out_stream);
1129   out_stream.flush();
1130   diagnostic_manager.SetFixedExpression(fixed_expression);
1131 
1132   return true;
1133 }
1134 
1135 static bool FindFunctionInModule(ConstString &mangled_name,
1136                                  llvm::Module *module, const char *orig_name) {
1137   for (const auto &func : module->getFunctionList()) {
1138     const StringRef &name = func.getName();
1139     if (name.find(orig_name) != StringRef::npos) {
1140       mangled_name.SetString(name);
1141       return true;
1142     }
1143   }
1144 
1145   return false;
1146 }
1147 
1148 lldb_private::Status ClangExpressionParser::PrepareForExecution(
1149     lldb::addr_t &func_addr, lldb::addr_t &func_end,
1150     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1151     bool &can_interpret, ExecutionPolicy execution_policy) {
1152   func_addr = LLDB_INVALID_ADDRESS;
1153   func_end = LLDB_INVALID_ADDRESS;
1154   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1155 
1156   lldb_private::Status err;
1157 
1158   std::unique_ptr<llvm::Module> llvm_module_up(
1159       m_code_generator->ReleaseModule());
1160 
1161   if (!llvm_module_up) {
1162     err.SetErrorToGenericError();
1163     err.SetErrorString("IR doesn't contain a module");
1164     return err;
1165   }
1166 
1167   ConstString function_name;
1168 
1169   if (execution_policy != eExecutionPolicyTopLevel) {
1170     // Find the actual name of the function (it's often mangled somehow)
1171 
1172     if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1173                               m_expr.FunctionName())) {
1174       err.SetErrorToGenericError();
1175       err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1176                                    m_expr.FunctionName());
1177       return err;
1178     } else {
1179       LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),
1180                 m_expr.FunctionName());
1181     }
1182   }
1183 
1184   SymbolContext sc;
1185 
1186   if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1187     sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1188   } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1189     sc.target_sp = target_sp;
1190   }
1191 
1192   LLVMUserExpression::IRPasses custom_passes;
1193   {
1194     auto lang = m_expr.Language();
1195     LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,
1196               Language::GetNameForLanguageType(lang));
1197     lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1198     if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1199       auto runtime = process_sp->GetLanguageRuntime(lang);
1200       if (runtime)
1201         runtime->GetIRPasses(custom_passes);
1202     }
1203   }
1204 
1205   if (custom_passes.EarlyPasses) {
1206     LLDB_LOGF(log,
1207               "%s - Running Early IR Passes from LanguageRuntime on "
1208               "expression module '%s'",
1209               __FUNCTION__, m_expr.FunctionName());
1210 
1211     custom_passes.EarlyPasses->run(*llvm_module_up);
1212   }
1213 
1214   execution_unit_sp = std::make_shared<IRExecutionUnit>(
1215       m_llvm_context, // handed off here
1216       llvm_module_up, // handed off here
1217       function_name, exe_ctx.GetTargetSP(), sc,
1218       m_compiler->getTargetOpts().Features);
1219 
1220   ClangExpressionHelper *type_system_helper =
1221       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1222   ClangExpressionDeclMap *decl_map =
1223       type_system_helper->DeclMap(); // result can be NULL
1224 
1225   if (decl_map) {
1226     Target *target = exe_ctx.GetTargetPtr();
1227     auto &error_stream = target->GetDebugger().GetErrorStream();
1228     IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1229                               *execution_unit_sp, error_stream,
1230                               function_name.AsCString());
1231 
1232     bool ir_can_run =
1233         ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1234 
1235     if (!ir_can_run) {
1236       err.SetErrorString(
1237           "The expression could not be prepared to run in the target");
1238       return err;
1239     }
1240 
1241     Process *process = exe_ctx.GetProcessPtr();
1242 
1243     if (execution_policy != eExecutionPolicyAlways &&
1244         execution_policy != eExecutionPolicyTopLevel) {
1245       lldb_private::Status interpret_error;
1246 
1247       bool interpret_function_calls =
1248           !process ? false : process->CanInterpretFunctionCalls();
1249       can_interpret = IRInterpreter::CanInterpret(
1250           *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1251           interpret_error, interpret_function_calls);
1252 
1253       if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1254         err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1255                                      interpret_error.AsCString());
1256         return err;
1257       }
1258     }
1259 
1260     if (!process && execution_policy == eExecutionPolicyAlways) {
1261       err.SetErrorString("Expression needed to run in the target, but the "
1262                          "target can't be run");
1263       return err;
1264     }
1265 
1266     if (!process && execution_policy == eExecutionPolicyTopLevel) {
1267       err.SetErrorString("Top-level code needs to be inserted into a runnable "
1268                          "target, but the target can't be run");
1269       return err;
1270     }
1271 
1272     if (execution_policy == eExecutionPolicyAlways ||
1273         (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1274       if (m_expr.NeedsValidation() && process) {
1275         if (!process->GetDynamicCheckers()) {
1276           ClangDynamicCheckerFunctions *dynamic_checkers =
1277               new ClangDynamicCheckerFunctions();
1278 
1279           DiagnosticManager install_diagnostics;
1280 
1281           if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1282             if (install_diagnostics.Diagnostics().size())
1283               err.SetErrorString(install_diagnostics.GetString().c_str());
1284             else
1285               err.SetErrorString("couldn't install checkers, unknown error");
1286 
1287             return err;
1288           }
1289 
1290           process->SetDynamicCheckers(dynamic_checkers);
1291 
1292           LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "
1293                          "Finished installing dynamic checkers ==");
1294         }
1295 
1296         if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1297                 process->GetDynamicCheckers())) {
1298           IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1299                                             function_name.AsCString());
1300 
1301           llvm::Module *module = execution_unit_sp->GetModule();
1302           if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1303             err.SetErrorToGenericError();
1304             err.SetErrorString("Couldn't add dynamic checks to the expression");
1305             return err;
1306           }
1307 
1308           if (custom_passes.LatePasses) {
1309             LLDB_LOGF(log,
1310                       "%s - Running Late IR Passes from LanguageRuntime on "
1311                       "expression module '%s'",
1312                       __FUNCTION__, m_expr.FunctionName());
1313 
1314             custom_passes.LatePasses->run(*module);
1315           }
1316         }
1317       }
1318     }
1319 
1320     if (execution_policy == eExecutionPolicyAlways ||
1321         execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1322       execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1323     }
1324   } else {
1325     execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1326   }
1327 
1328   return err;
1329 }
1330 
1331 lldb_private::Status ClangExpressionParser::RunStaticInitializers(
1332     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
1333   lldb_private::Status err;
1334 
1335   lldbassert(execution_unit_sp.get());
1336   lldbassert(exe_ctx.HasThreadScope());
1337 
1338   if (!execution_unit_sp.get()) {
1339     err.SetErrorString(
1340         "can't run static initializers for a NULL execution unit");
1341     return err;
1342   }
1343 
1344   if (!exe_ctx.HasThreadScope()) {
1345     err.SetErrorString("can't run static initializers without a thread");
1346     return err;
1347   }
1348 
1349   std::vector<lldb::addr_t> static_initializers;
1350 
1351   execution_unit_sp->GetStaticInitializers(static_initializers);
1352 
1353   for (lldb::addr_t static_initializer : static_initializers) {
1354     EvaluateExpressionOptions options;
1355 
1356     lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1357         exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1358         llvm::ArrayRef<lldb::addr_t>(), options));
1359 
1360     DiagnosticManager execution_errors;
1361     lldb::ExpressionResults results =
1362         exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1363             exe_ctx, call_static_initializer, options, execution_errors);
1364 
1365     if (results != lldb::eExpressionCompleted) {
1366       err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1367                                    execution_errors.GetString().c_str());
1368       return err;
1369     }
1370   }
1371 
1372   return err;
1373 }
1374