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