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