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