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