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