1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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/DiagnosticIDs.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Basic/TargetInfo.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/CodeGen/CodeGenAction.h"
18 #include "clang/CodeGen/ModuleBuilder.h"
19 #include "clang/Edit/Commit.h"
20 #include "clang/Edit/EditedSource.h"
21 #include "clang/Edit/EditsReceiver.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/CompilerInvocation.h"
24 #include "clang/Frontend/FrontendActions.h"
25 #include "clang/Frontend/FrontendDiagnostic.h"
26 #include "clang/Frontend/FrontendPluginRegistry.h"
27 #include "clang/Frontend/TextDiagnosticBuffer.h"
28 #include "clang/Frontend/TextDiagnosticPrinter.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Parse/ParseAST.h"
31 #include "clang/Rewrite/Core/Rewriter.h"
32 #include "clang/Rewrite/Frontend/FrontendActions.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaConsumer.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ExecutionEngine/ExecutionEngine.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/DynamicLibrary.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Signals.h"
52 #include "ClangDiagnostic.h"
53 #include "ClangExpressionParser.h"
54 #include "ClangUserExpression.h"
57 #include "ClangASTSource.h"
58 #include "ClangDiagnostic.h"
59 #include "ClangExpressionDeclMap.h"
60 #include "ClangExpressionHelper.h"
61 #include "ClangExpressionParser.h"
62 #include "ClangHost.h"
63 #include "ClangModulesDeclVendor.h"
64 #include "ClangPersistentVariables.h"
65 #include "IRDynamicChecks.h"
66 #include "IRForTarget.h"
67 #include "ModuleDependencyCollector.h"
69 #include "lldb/Core/Debugger.h"
70 #include "lldb/Core/Disassembler.h"
71 #include "lldb/Core/Module.h"
72 #include "lldb/Core/StreamFile.h"
73 #include "lldb/Expression/IRExecutionUnit.h"
74 #include "lldb/Expression/IRInterpreter.h"
75 #include "lldb/Host/File.h"
76 #include "lldb/Host/HostInfo.h"
77 #include "lldb/Symbol/ClangASTContext.h"
78 #include "lldb/Symbol/SymbolVendor.h"
79 #include "lldb/Target/ExecutionContext.h"
80 #include "lldb/Target/Language.h"
81 #include "lldb/Target/Process.h"
82 #include "lldb/Target/Target.h"
83 #include "lldb/Target/ThreadPlanCallFunction.h"
84 #include "lldb/Utility/DataBufferHeap.h"
85 #include "lldb/Utility/LLDBAssert.h"
86 #include "lldb/Utility/Log.h"
87 #include "lldb/Utility/Reproducer.h"
88 #include "lldb/Utility/Stream.h"
89 #include "lldb/Utility/StreamString.h"
90 #include "lldb/Utility/StringList.h"
92 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
97 using namespace clang;
99 using namespace lldb_private;
101 //===----------------------------------------------------------------------===//
102 // Utility Methods for Clang
103 //===----------------------------------------------------------------------===//
105 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
106 ClangModulesDeclVendor &m_decl_vendor;
107 ClangPersistentVariables &m_persistent_vars;
108 StreamString m_error_stream;
109 bool m_has_errors = false;
112 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
113 ClangPersistentVariables &persistent_vars)
114 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
116 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
117 const clang::Module * /*null*/) override {
120 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
121 module.path.push_back(ConstString(component.first->getName()));
123 StreamString error_stream;
125 ClangModulesDeclVendor::ModuleVector exported_modules;
126 if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
129 for (ClangModulesDeclVendor::ModuleID module : exported_modules)
130 m_persistent_vars.AddHandLoadedClangModule(module);
133 bool hasErrors() { return m_has_errors; }
135 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
138 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
140 ClangDiagnosticManagerAdapter()
141 : m_passthrough(new clang::TextDiagnosticBuffer) {}
143 ClangDiagnosticManagerAdapter(
144 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
145 : m_passthrough(passthrough) {}
147 void ResetManager(DiagnosticManager *manager = nullptr) {
151 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
152 const clang::Diagnostic &Info) override {
154 llvm::SmallVector<char, 32> diag_str;
155 Info.FormatDiagnostic(diag_str);
156 diag_str.push_back('\0');
157 const char *data = diag_str.data();
159 lldb_private::DiagnosticSeverity severity;
160 bool make_new_diagnostic = true;
163 case DiagnosticsEngine::Level::Fatal:
164 case DiagnosticsEngine::Level::Error:
165 severity = eDiagnosticSeverityError;
167 case DiagnosticsEngine::Level::Warning:
168 severity = eDiagnosticSeverityWarning;
170 case DiagnosticsEngine::Level::Remark:
171 case DiagnosticsEngine::Level::Ignored:
172 severity = eDiagnosticSeverityRemark;
174 case DiagnosticsEngine::Level::Note:
175 m_manager->AppendMessageToDiagnostic(data);
176 make_new_diagnostic = false;
178 if (make_new_diagnostic) {
179 ClangDiagnostic *new_diagnostic =
180 new ClangDiagnostic(data, severity, Info.getID());
181 m_manager->AddDiagnostic(new_diagnostic);
183 // Don't store away warning fixits, since the compiler doesn't have
184 // enough context in an expression for the warning to be useful.
185 // FIXME: Should we try to filter out FixIts that apply to our generated
186 // code, and not the user's expression?
187 if (severity == eDiagnosticSeverityError) {
188 size_t num_fixit_hints = Info.getNumFixItHints();
189 for (size_t i = 0; i < num_fixit_hints; i++) {
190 const clang::FixItHint &fixit = Info.getFixItHint(i);
192 new_diagnostic->AddFixitHint(fixit);
198 m_passthrough->HandleDiagnostic(DiagLevel, Info);
201 void FlushDiagnostics(DiagnosticsEngine &Diags) {
202 m_passthrough->FlushDiagnostics(Diags);
205 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
206 return new ClangDiagnosticManagerAdapter(m_passthrough);
209 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
212 DiagnosticManager *m_manager = nullptr;
213 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
217 SetupModuleHeaderPaths(CompilerInstance *compiler,
218 std::vector<ConstString> include_directories,
219 lldb::TargetSP target_sp) {
220 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
222 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
224 for (ConstString dir : include_directories) {
225 search_opts.AddPath(dir.AsCString(), frontend::System, false, true);
226 LLDB_LOG(log, "Added user include dir: {0}", dir);
229 llvm::SmallString<128> module_cache;
230 auto props = ModuleList::GetGlobalModuleListProperties();
231 props.GetClangModulesCachePath().GetPath(module_cache);
232 search_opts.ModuleCachePath = module_cache.str();
233 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
235 FileSpec clang_resource_dir = GetClangResourceDir();
236 std::string resource_dir = clang_resource_dir.GetPath();
237 if (FileSystem::Instance().IsDirectory(resource_dir)) {
238 search_opts.ResourceDir = resource_dir;
239 std::string resource_include = resource_dir + "/include";
240 search_opts.AddPath(resource_include, frontend::System, false, true);
242 LLDB_LOG(log, "Added resource include dir: {0}", resource_include);
245 search_opts.ImplicitModuleMaps = true;
247 std::vector<std::string> system_include_directories =
248 target_sp->GetPlatform()->GetSystemIncludeDirectories(
249 lldb::eLanguageTypeC_plus_plus);
251 for (const std::string &include_dir : system_include_directories) {
252 search_opts.AddPath(include_dir, frontend::System, false, true);
254 LLDB_LOG(log, "Added system include dir: {0}", include_dir);
258 //===----------------------------------------------------------------------===//
259 // Implementation of ClangExpressionParser
260 //===----------------------------------------------------------------------===//
262 ClangExpressionParser::ClangExpressionParser(
263 ExecutionContextScope *exe_scope, Expression &expr,
264 bool generate_debug_info, std::vector<ConstString> include_directories)
265 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
266 m_pp_callbacks(nullptr),
267 m_include_directories(std::move(include_directories)) {
268 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
270 // We can't compile expressions without a target. So if the exe_scope is
271 // null or doesn't have a target, then we just need to get out of here. I'll
272 // lldb_assert and not make any of the compiler objects since
273 // I can't return errors directly from the constructor. Further calls will
274 // check if the compiler was made and
275 // bag out if it wasn't.
278 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
279 __FUNCTION__, __FILE__, __LINE__);
283 lldb::TargetSP target_sp;
284 target_sp = exe_scope->CalculateTarget();
286 lldb_assert(target_sp.get(),
287 "Can't make an expression parser with a null target.",
288 __FUNCTION__, __FILE__, __LINE__);
292 // 1. Create a new compiler instance.
293 m_compiler.reset(new CompilerInstance());
295 // When capturing a reproducer, hook up the file collector with clang to
296 // collector modules and headers.
297 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
298 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
299 m_compiler->setModuleDepCollector(
300 std::make_shared<ModuleDependencyCollectorAdaptor>(
301 fp.GetFileCollector()));
302 DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
303 opts.IncludeSystemHeaders = true;
304 opts.IncludeModuleFiles = true;
307 // Make sure clang uses the same VFS as LLDB.
308 m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
310 lldb::LanguageType frame_lang =
311 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
312 bool overridden_target_opts = false;
313 lldb_private::LanguageRuntime *lang_rt = nullptr;
316 ArchSpec target_arch;
317 target_arch = target_sp->GetArchitecture();
319 const auto target_machine = target_arch.GetMachine();
321 // If the expression is being evaluated in the context of an existing stack
322 // frame, we introspect to see if the language runtime is available.
324 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
325 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
327 // Make sure the user hasn't provided a preferred execution language with
328 // `expression --language X -- ...`
329 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
330 frame_lang = frame_sp->GetLanguage();
332 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
333 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
335 log->Printf("Frame has language of type %s",
336 Language::GetNameForLanguageType(frame_lang));
339 // 2. Configure the compiler with a set of default options that are
340 // appropriate for most situations.
341 if (target_arch.IsValid()) {
342 std::string triple = target_arch.GetTriple().str();
343 m_compiler->getTargetOpts().Triple = triple;
345 log->Printf("Using %s as the target triple",
346 m_compiler->getTargetOpts().Triple.c_str());
348 // If we get here we don't have a valid target and just have to guess.
349 // Sometimes this will be ok to just use the host target triple (when we
350 // evaluate say "2+3", but other expressions like breakpoint conditions and
351 // other things that _are_ target specific really shouldn't just be using
352 // the host triple. In such a case the language runtime should expose an
353 // overridden options set (3), below.
354 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
356 log->Printf("Using default target triple of %s",
357 m_compiler->getTargetOpts().Triple.c_str());
359 // Now add some special fixes for known architectures: Any arm32 iOS
360 // environment, but not on arm64
361 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
362 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
363 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
364 m_compiler->getTargetOpts().ABI = "apcs-gnu";
366 // Supported subsets of x86
367 if (target_machine == llvm::Triple::x86 ||
368 target_machine == llvm::Triple::x86_64) {
369 m_compiler->getTargetOpts().Features.push_back("+sse");
370 m_compiler->getTargetOpts().Features.push_back("+sse2");
373 // Set the target CPU to generate code for. This will be empty for any CPU
374 // that doesn't really need to make a special
376 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
378 // Set the target ABI
379 abi = GetClangTargetABI(target_arch);
381 m_compiler->getTargetOpts().ABI = abi;
383 // 3. Now allow the runtime to provide custom configuration options for the
384 // target. In this case, a specialized language runtime is available and we
385 // can query it for extra options. For 99% of use cases, this will not be
386 // needed and should be provided when basic platform detection is not enough.
388 overridden_target_opts =
389 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
391 if (overridden_target_opts)
392 if (log && log->GetVerbose()) {
394 log, "Using overridden target options for the expression evaluation");
396 auto opts = m_compiler->getTargetOpts();
397 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
398 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
399 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
400 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
401 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
402 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
403 StringList::LogDump(log, opts.Features, "Features");
406 // 4. Create and install the target on the compiler.
407 m_compiler->createDiagnostics();
408 auto target_info = TargetInfo::CreateTargetInfo(
409 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
411 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
412 log->Printf("Target datalayout string: '%s'",
413 target_info->getDataLayout().getStringRepresentation().c_str());
414 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
415 log->Printf("Target vector alignment: %d",
416 target_info->getMaxVectorAlign());
418 m_compiler->setTarget(target_info);
420 assert(m_compiler->hasTarget());
422 // 5. Set language options.
423 lldb::LanguageType language = expr.Language();
424 LangOptions &lang_opts = m_compiler->getLangOpts();
427 case lldb::eLanguageTypeC:
428 case lldb::eLanguageTypeC89:
429 case lldb::eLanguageTypeC99:
430 case lldb::eLanguageTypeC11:
431 // FIXME: the following language option is a temporary workaround,
432 // to "ask for C, get C++."
433 // For now, the expression parser must use C++ anytime the language is a C
434 // family language, because the expression parser uses features of C++ to
436 lang_opts.CPlusPlus = true;
438 case lldb::eLanguageTypeObjC:
439 lang_opts.ObjC = true;
440 // FIXME: the following language option is a temporary workaround,
441 // to "ask for ObjC, get ObjC++" (see comment above).
442 lang_opts.CPlusPlus = true;
444 // Clang now sets as default C++14 as the default standard (with
445 // GNU extensions), so we do the same here to avoid mismatches that
446 // cause compiler error when evaluating expressions (e.g. nullptr not found
447 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
448 // two lines below) so we decide to be consistent with that, but this could
449 // be re-evaluated in the future.
450 lang_opts.CPlusPlus11 = true;
452 case lldb::eLanguageTypeC_plus_plus:
453 case lldb::eLanguageTypeC_plus_plus_11:
454 case lldb::eLanguageTypeC_plus_plus_14:
455 lang_opts.CPlusPlus11 = true;
456 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
458 case lldb::eLanguageTypeC_plus_plus_03:
459 lang_opts.CPlusPlus = true;
462 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
464 case lldb::eLanguageTypeObjC_plus_plus:
465 case lldb::eLanguageTypeUnknown:
467 lang_opts.ObjC = true;
468 lang_opts.CPlusPlus = true;
469 lang_opts.CPlusPlus11 = true;
470 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
474 lang_opts.Bool = true;
475 lang_opts.WChar = true;
476 lang_opts.Blocks = true;
477 lang_opts.DebuggerSupport =
478 true; // Features specifically for debugger clients
479 if (expr.DesiredResultType() == Expression::eResultTypeId)
480 lang_opts.DebuggerCastResultToId = true;
482 lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
483 .CharIsSignedByDefault();
485 // Spell checking is a nice feature, but it ends up completing a lot of types
486 // that we didn't strictly speaking need to complete. As a result, we spend a
487 // long time parsing and importing debug information.
488 lang_opts.SpellChecking = false;
490 auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
491 if (clang_expr && clang_expr->DidImportCxxModules()) {
492 LLDB_LOG(log, "Adding lang options for importing C++ modules");
494 lang_opts.Modules = true;
495 // We want to implicitly build modules.
496 lang_opts.ImplicitModules = true;
497 // To automatically import all submodules when we import 'std'.
498 lang_opts.ModulesLocalVisibility = false;
500 // We use the @import statements, so we need this:
501 // FIXME: We could use the modules-ts, but that currently doesn't work.
502 lang_opts.ObjC = true;
504 // Options we need to parse libc++ code successfully.
505 // FIXME: We should ask the driver for the appropriate default flags.
506 lang_opts.GNUMode = true;
507 lang_opts.GNUKeywords = true;
508 lang_opts.DoubleSquareBracketAttributes = true;
509 lang_opts.CPlusPlus11 = true;
511 SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
515 if (process_sp && lang_opts.ObjC) {
516 if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
517 if (runtime->GetRuntimeVersion() ==
518 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
519 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
521 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
522 VersionTuple(10, 7));
524 if (runtime->HasNewLiteralsAndIndexing())
525 lang_opts.DebuggerObjCLiteral = true;
529 lang_opts.ThreadsafeStatics = false;
530 lang_opts.AccessControl = false; // Debuggers get universal access
531 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
532 // We enable all builtin functions beside the builtins from libc/libm (e.g.
533 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
534 // additionally enabling them as expandable builtins is breaking Clang.
535 lang_opts.NoBuiltin = true;
537 // Set CodeGen options
538 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
539 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
540 m_compiler->getCodeGenOpts().DisableFPElim = true;
541 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
542 if (generate_debug_info)
543 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
545 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
547 // Disable some warnings.
548 m_compiler->getDiagnostics().setSeverityForGroup(
549 clang::diag::Flavor::WarningOrError, "unused-value",
550 clang::diag::Severity::Ignored, SourceLocation());
551 m_compiler->getDiagnostics().setSeverityForGroup(
552 clang::diag::Flavor::WarningOrError, "odr",
553 clang::diag::Severity::Ignored, SourceLocation());
555 // Inform the target of the language options
557 // FIXME: We shouldn't need to do this, the target should be immutable once
558 // created. This complexity should be lifted elsewhere.
559 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
561 // 6. Set up the diagnostic buffer for reporting errors
563 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
565 // 7. Set up the source management objects inside the compiler
566 m_compiler->createFileManager();
567 if (!m_compiler->hasSourceManager())
568 m_compiler->createSourceManager(m_compiler->getFileManager());
569 m_compiler->createPreprocessor(TU_Complete);
571 if (ClangModulesDeclVendor *decl_vendor =
572 target_sp->GetClangModulesDeclVendor()) {
573 ClangPersistentVariables *clang_persistent_vars =
574 llvm::cast<ClangPersistentVariables>(
575 target_sp->GetPersistentExpressionStateForLanguage(
576 lldb::eLanguageTypeC));
577 std::unique_ptr<PPCallbacks> pp_callbacks(
578 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
580 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
581 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
584 // 8. Most of this we get from the CompilerInstance, but we also want to give
585 // the context an ExternalASTSource.
587 auto &PP = m_compiler->getPreprocessor();
588 auto &builtin_context = PP.getBuiltinInfo();
589 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
590 m_compiler->getLangOpts());
592 m_compiler->createASTContext();
593 clang::ASTContext &ast_context = m_compiler->getASTContext();
596 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
597 m_ast_context->setASTContext(&ast_context);
599 std::string module_name("$__lldb_module");
601 m_llvm_context.reset(new LLVMContext());
602 m_code_generator.reset(CreateLLVMCodeGen(
603 m_compiler->getDiagnostics(), module_name,
604 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
605 m_compiler->getCodeGenOpts(), *m_llvm_context));
608 ClangExpressionParser::~ClangExpressionParser() {}
612 /// \class CodeComplete
614 /// A code completion consumer for the clang Sema that is responsible for
615 /// creating the completion suggestions when a user requests completion
616 /// of an incomplete `expr` invocation.
617 class CodeComplete : public CodeCompleteConsumer {
618 CodeCompletionTUInfo m_info;
621 unsigned m_position = 0;
622 CompletionRequest &m_request;
623 /// The printing policy we use when printing declarations for our completion
625 clang::PrintingPolicy m_desc_policy;
627 /// Returns true if the given character can be used in an identifier.
628 /// This also returns true for numbers because for completion we usually
629 /// just iterate backwards over iterators.
631 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
632 static bool IsIdChar(char c) {
633 return c == '_' || std::isalnum(c) || c == '$';
636 /// Returns true if the given character is used to separate arguments
637 /// in the command line of lldb.
638 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
640 /// Drops all tokens in front of the expression that are unrelated for
641 /// the completion of the cmd line. 'unrelated' means here that the token
642 /// is not interested for the lldb completion API result.
643 StringRef dropUnrelatedFrontTokens(StringRef cmd) {
647 // If we are at the start of a word, then all tokens are unrelated to
648 // the current completion logic.
649 if (IsTokenSeparator(cmd.back()))
652 // Remove all previous tokens from the string as they are unrelated
653 // to completing the current token.
654 StringRef to_remove = cmd;
655 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
656 to_remove = to_remove.drop_back();
658 cmd = cmd.drop_front(to_remove.size());
663 /// Removes the last identifier token from the given cmd line.
664 StringRef removeLastToken(StringRef cmd) {
665 while (!cmd.empty() && IsIdChar(cmd.back())) {
666 cmd = cmd.drop_back();
671 /// Attemps to merge the given completion from the given position into the
672 /// existing command. Returns the completion string that can be returned to
673 /// the lldb completion API.
674 std::string mergeCompletion(StringRef existing, unsigned pos,
675 StringRef completion) {
676 StringRef existing_command = existing.substr(0, pos);
677 // We rewrite the last token with the completion, so let's drop that
678 // token from the command.
679 existing_command = removeLastToken(existing_command);
680 // We also should remove all previous tokens from the command as they
681 // would otherwise be added to the completion that already has the
683 existing_command = dropUnrelatedFrontTokens(existing_command);
684 return existing_command.str() + completion.str();
688 /// Constructs a CodeComplete consumer that can be attached to a Sema.
689 /// \param[out] matches
690 /// The list of matches that the lldb completion API expects as a result.
691 /// This may already contain matches, so it's only allowed to append
692 /// to this variable.
694 /// The whole expression string that we are currently parsing. This
695 /// string needs to be equal to the input the user typed, and NOT the
696 /// final code that Clang is parsing.
697 /// \param[out] position
698 /// The character position of the user cursor in the `expr` parameter.
700 CodeComplete(CompletionRequest &request, clang::LangOptions ops,
701 std::string expr, unsigned position)
702 : CodeCompleteConsumer(CodeCompleteOptions()),
703 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
704 m_position(position), m_request(request), m_desc_policy(ops) {
706 // Ensure that the printing policy is producing a description that is as
707 // short as possible.
708 m_desc_policy.SuppressScope = true;
709 m_desc_policy.SuppressTagKeyword = true;
710 m_desc_policy.FullyQualifiedName = false;
711 m_desc_policy.TerseOutput = true;
712 m_desc_policy.IncludeNewlines = false;
713 m_desc_policy.UseVoidForZeroParams = false;
714 m_desc_policy.Bool = true;
717 /// Deregisters and destroys this code-completion consumer.
718 ~CodeComplete() override {}
720 /// \name Code-completion filtering
721 /// Check if the result should be filtered out.
722 bool isResultFilteredOut(StringRef Filter,
723 CodeCompletionResult Result) override {
724 // This code is mostly copied from CodeCompleteConsumer.
725 switch (Result.Kind) {
726 case CodeCompletionResult::RK_Declaration:
728 Result.Declaration->getIdentifier() &&
729 Result.Declaration->getIdentifier()->getName().startswith(Filter));
730 case CodeCompletionResult::RK_Keyword:
731 return !StringRef(Result.Keyword).startswith(Filter);
732 case CodeCompletionResult::RK_Macro:
733 return !Result.Macro->getName().startswith(Filter);
734 case CodeCompletionResult::RK_Pattern:
735 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
737 // If we trigger this assert or the above switch yields a warning, then
738 // CodeCompletionResult has been enhanced with more kinds of completion
739 // results. Expand the switch above in this case.
740 assert(false && "Unknown completion result type?");
741 // If we reach this, then we should just ignore whatever kind of unknown
742 // result we got back. We probably can't turn it into any kind of useful
743 // completion suggestion with the existing code.
747 /// \name Code-completion callbacks
748 /// Process the finalized code-completion results.
749 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
750 CodeCompletionResult *Results,
751 unsigned NumResults) override {
753 // The Sema put the incomplete token we try to complete in here during
754 // lexing, so we need to retrieve it here to know what we are completing.
755 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
757 // Iterate over all the results. Filter out results we don't want and
759 for (unsigned I = 0; I != NumResults; ++I) {
760 // Filter the results with the information from the Sema.
761 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
764 CodeCompletionResult &R = Results[I];
765 std::string ToInsert;
766 std::string Description;
767 // Handle the different completion kinds that come from the Sema.
769 case CodeCompletionResult::RK_Declaration: {
770 const NamedDecl *D = R.Declaration;
771 ToInsert = R.Declaration->getNameAsString();
772 // If we have a function decl that has no arguments we want to
773 // complete the empty parantheses for the user. If the function has
774 // arguments, we at least complete the opening bracket.
775 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
776 if (F->getNumParams() == 0)
780 raw_string_ostream OS(Description);
781 F->print(OS, m_desc_policy, false);
783 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
784 Description = V->getType().getAsString(m_desc_policy);
785 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
786 Description = F->getType().getAsString(m_desc_policy);
787 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
788 // If we try to complete a namespace, then we can directly append
790 if (!N->isAnonymousNamespace())
795 case CodeCompletionResult::RK_Keyword:
796 ToInsert = R.Keyword;
798 case CodeCompletionResult::RK_Macro:
799 ToInsert = R.Macro->getName().str();
801 case CodeCompletionResult::RK_Pattern:
802 ToInsert = R.Pattern->getTypedText();
805 // At this point all information is in the ToInsert string.
807 // We also filter some internal lldb identifiers here. The user
808 // shouldn't see these.
809 if (StringRef(ToInsert).startswith("$__lldb_"))
811 if (!ToInsert.empty()) {
812 // Merge the suggested Token into the existing command line to comply
813 // with the kind of result the lldb API expects.
814 std::string CompletionSuggestion =
815 mergeCompletion(m_expr, m_position, ToInsert);
816 m_request.AddCompletion(CompletionSuggestion, Description);
821 /// \param S the semantic-analyzer object for which code-completion is being
824 /// \param CurrentArg the index of the current argument.
826 /// \param Candidates an array of overload candidates.
828 /// \param NumCandidates the number of overload candidates
829 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
830 OverloadCandidate *Candidates,
831 unsigned NumCandidates,
832 SourceLocation OpenParLoc) override {
833 // At the moment we don't filter out any overloaded candidates.
836 CodeCompletionAllocator &getAllocator() override {
837 return m_info.getAllocator();
840 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
844 bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
845 unsigned pos, unsigned typed_pos) {
846 DiagnosticManager mgr;
847 // We need the raw user expression here because that's what the CodeComplete
848 // class uses to provide completion suggestions.
849 // However, the `Text` method only gives us the transformed expression here.
850 // To actually get the raw user input here, we have to cast our expression to
851 // the LLVMUserExpression which exposes the right API. This should never fail
852 // as we always have a ClangUserExpression whenever we call this.
853 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
854 CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr->GetUserText(),
856 // We don't need a code generator for parsing.
857 m_code_generator.reset();
858 // Start parsing the expression with our custom code completion consumer.
859 ParseInternal(mgr, &CC, line, pos);
863 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
864 return ParseInternal(diagnostic_manager);
868 ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
869 CodeCompleteConsumer *completion_consumer,
870 unsigned completion_line,
871 unsigned completion_column) {
872 ClangDiagnosticManagerAdapter *adapter =
873 static_cast<ClangDiagnosticManagerAdapter *>(
874 m_compiler->getDiagnostics().getClient());
875 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
876 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
878 adapter->ResetManager(&diagnostic_manager);
880 const char *expr_text = m_expr.Text();
882 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
883 bool created_main_file = false;
885 // Clang wants to do completion on a real file known by Clang's file manager,
886 // so we have to create one to make this work.
887 // TODO: We probably could also simulate to Clang's file manager that there
888 // is a real file that contains our code.
889 bool should_create_file = completion_consumer != nullptr;
891 // We also want a real file on disk if we generate full debug info.
892 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
893 codegenoptions::FullDebugInfo;
895 if (should_create_file) {
897 llvm::SmallString<128> result_path;
898 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
899 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
900 std::string temp_source_path = tmpdir_file_spec.GetPath();
901 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
903 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
907 lldb_private::File file(temp_fd, true);
908 const size_t expr_text_len = strlen(expr_text);
909 size_t bytes_written = expr_text_len;
910 if (file.Write(expr_text, bytes_written).Success()) {
911 if (bytes_written == expr_text_len) {
913 source_mgr.setMainFileID(source_mgr.createFileID(
914 m_compiler->getFileManager().getFile(result_path),
915 SourceLocation(), SrcMgr::C_User));
916 created_main_file = true;
922 if (!created_main_file) {
923 std::unique_ptr<MemoryBuffer> memory_buffer =
924 MemoryBuffer::getMemBufferCopy(expr_text, "<lldb-expr>");
925 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
928 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
929 &m_compiler->getPreprocessor());
931 ClangExpressionHelper *type_system_helper =
932 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
934 // If we want to parse for code completion, we need to attach our code
935 // completion consumer to the Sema and specify a completion position.
936 // While parsing the Sema will call this consumer with the provided
937 // completion suggestions.
938 if (completion_consumer) {
939 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
940 auto &PP = m_compiler->getPreprocessor();
941 // Lines and columns start at 1 in Clang, but code completion positions are
942 // indexed from 0, so we need to add 1 to the line and column here.
945 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
948 ASTConsumer *ast_transformer =
949 type_system_helper->ASTTransformer(m_code_generator.get());
951 std::unique_ptr<clang::ASTConsumer> Consumer;
952 if (ast_transformer) {
953 Consumer.reset(new ASTConsumerForwarder(ast_transformer));
954 } else if (m_code_generator) {
955 Consumer.reset(new ASTConsumerForwarder(m_code_generator.get()));
957 Consumer.reset(new ASTConsumer());
960 clang::ASTContext &ast_context = m_compiler->getASTContext();
962 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
963 *Consumer, TU_Complete, completion_consumer));
964 m_compiler->setASTConsumer(std::move(Consumer));
966 if (ast_context.getLangOpts().Modules) {
967 m_compiler->createModuleManager();
968 m_ast_context->setSema(&m_compiler->getSema());
971 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
973 decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
975 clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
977 if (ast_context.getExternalSource()) {
978 auto module_wrapper =
979 new ExternalASTSourceWrapper(ast_context.getExternalSource());
981 auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
984 new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
985 IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
986 ast_context.setExternalSource(Source);
988 ast_context.setExternalSource(ast_source);
990 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
993 // Check that the ASTReader is properly attached to ASTContext and Sema.
994 if (ast_context.getLangOpts().Modules) {
995 assert(m_compiler->getASTContext().getExternalSource() &&
996 "ASTContext doesn't know about the ASTReader?");
997 assert(m_compiler->getSema().getExternalSource() &&
998 "Sema doesn't know about the ASTReader?");
1002 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1003 &m_compiler->getSema());
1004 ParseAST(m_compiler->getSema(), false, false);
1007 // Make sure we have no pointer to the Sema we are about to destroy.
1008 if (ast_context.getLangOpts().Modules)
1009 m_ast_context->setSema(nullptr);
1010 // Destroy the Sema. This is necessary because we want to emulate the
1011 // original behavior of ParseAST (which also destroys the Sema after parsing).
1012 m_compiler->setSema(nullptr);
1014 diag_buf->EndSourceFile();
1016 unsigned num_errors = diag_buf->getNumErrors();
1018 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1020 diagnostic_manager.PutString(eDiagnosticSeverityError,
1021 "while importing modules:");
1022 diagnostic_manager.AppendMessageToDiagnostic(
1023 m_pp_callbacks->getErrorString());
1027 if (type_system_helper->DeclMap() &&
1028 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
1029 diagnostic_manager.Printf(eDiagnosticSeverityError,
1030 "Couldn't infer the type of a variable");
1036 type_system_helper->CommitPersistentDecls();
1039 adapter->ResetManager();
1045 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1048 if (target_arch.IsMIPS()) {
1049 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1050 case ArchSpec::eMIPSABI_N64:
1053 case ArchSpec::eMIPSABI_N32:
1056 case ArchSpec::eMIPSABI_O32:
1066 bool ClangExpressionParser::RewriteExpression(
1067 DiagnosticManager &diagnostic_manager) {
1068 clang::SourceManager &source_manager = m_compiler->getSourceManager();
1069 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1071 clang::edit::Commit commit(editor);
1072 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1074 class RewritesReceiver : public edit::EditsReceiver {
1078 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1080 void insert(SourceLocation loc, StringRef text) override {
1081 rewrite.InsertText(loc, text);
1083 void replace(CharSourceRange range, StringRef text) override {
1084 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1088 RewritesReceiver rewrites_receiver(rewriter);
1090 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1091 size_t num_diags = diagnostics.size();
1095 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
1096 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
1097 if (diagnostic && diagnostic->HasFixIts()) {
1098 for (const FixItHint &fixit : diagnostic->FixIts()) {
1099 // This is cobbed from clang::Rewrite::FixItRewriter.
1100 if (fixit.CodeToInsert.empty()) {
1101 if (fixit.InsertFromRange.isValid()) {
1102 commit.insertFromRange(fixit.RemoveRange.getBegin(),
1103 fixit.InsertFromRange, /*afterToken=*/false,
1104 fixit.BeforePreviousInsertions);
1106 commit.remove(fixit.RemoveRange);
1108 if (fixit.RemoveRange.isTokenRange() ||
1109 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
1110 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1112 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1113 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1119 // FIXME - do we want to try to propagate specific errors here?
1120 if (!commit.isCommitable())
1122 else if (!editor.commit(commit))
1125 // Now play all the edits, and stash the result in the diagnostic manager.
1126 editor.applyRewrites(rewrites_receiver);
1127 RewriteBuffer &main_file_buffer =
1128 rewriter.getEditBuffer(source_manager.getMainFileID());
1130 std::string fixed_expression;
1131 llvm::raw_string_ostream out_stream(fixed_expression);
1133 main_file_buffer.write(out_stream);
1135 diagnostic_manager.SetFixedExpression(fixed_expression);
1140 static bool FindFunctionInModule(ConstString &mangled_name,
1141 llvm::Module *module, const char *orig_name) {
1142 for (const auto &func : module->getFunctionList()) {
1143 const StringRef &name = func.getName();
1144 if (name.find(orig_name) != StringRef::npos) {
1145 mangled_name.SetString(name);
1153 lldb_private::Status ClangExpressionParser::PrepareForExecution(
1154 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1155 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1156 bool &can_interpret, ExecutionPolicy execution_policy) {
1157 func_addr = LLDB_INVALID_ADDRESS;
1158 func_end = LLDB_INVALID_ADDRESS;
1159 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1161 lldb_private::Status err;
1163 std::unique_ptr<llvm::Module> llvm_module_up(
1164 m_code_generator->ReleaseModule());
1166 if (!llvm_module_up) {
1167 err.SetErrorToGenericError();
1168 err.SetErrorString("IR doesn't contain a module");
1172 ConstString function_name;
1174 if (execution_policy != eExecutionPolicyTopLevel) {
1175 // Find the actual name of the function (it's often mangled somehow)
1177 if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1178 m_expr.FunctionName())) {
1179 err.SetErrorToGenericError();
1180 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1181 m_expr.FunctionName());
1185 log->Printf("Found function %s for %s", function_name.AsCString(),
1186 m_expr.FunctionName());
1192 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1193 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1194 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1195 sc.target_sp = target_sp;
1198 LLVMUserExpression::IRPasses custom_passes;
1200 auto lang = m_expr.Language();
1202 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
1203 Language::GetNameForLanguageType(lang));
1204 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1205 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1206 auto runtime = process_sp->GetLanguageRuntime(lang);
1208 runtime->GetIRPasses(custom_passes);
1212 if (custom_passes.EarlyPasses) {
1214 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1215 "expression module '%s'",
1216 __FUNCTION__, m_expr.FunctionName());
1218 custom_passes.EarlyPasses->run(*llvm_module_up);
1221 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1222 m_llvm_context, // handed off here
1223 llvm_module_up, // handed off here
1224 function_name, exe_ctx.GetTargetSP(), sc,
1225 m_compiler->getTargetOpts().Features);
1227 ClangExpressionHelper *type_system_helper =
1228 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1229 ClangExpressionDeclMap *decl_map =
1230 type_system_helper->DeclMap(); // result can be NULL
1233 Stream *error_stream = nullptr;
1234 Target *target = exe_ctx.GetTargetPtr();
1235 error_stream = target->GetDebugger().GetErrorFile().get();
1237 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1238 *execution_unit_sp, *error_stream,
1239 function_name.AsCString());
1242 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1246 "The expression could not be prepared to run in the target");
1250 Process *process = exe_ctx.GetProcessPtr();
1252 if (execution_policy != eExecutionPolicyAlways &&
1253 execution_policy != eExecutionPolicyTopLevel) {
1254 lldb_private::Status interpret_error;
1256 bool interpret_function_calls =
1257 !process ? false : process->CanInterpretFunctionCalls();
1258 can_interpret = IRInterpreter::CanInterpret(
1259 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1260 interpret_error, interpret_function_calls);
1262 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1263 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1264 interpret_error.AsCString());
1269 if (!process && execution_policy == eExecutionPolicyAlways) {
1270 err.SetErrorString("Expression needed to run in the target, but the "
1271 "target can't be run");
1275 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1276 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1277 "target, but the target can't be run");
1281 if (execution_policy == eExecutionPolicyAlways ||
1282 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1283 if (m_expr.NeedsValidation() && process) {
1284 if (!process->GetDynamicCheckers()) {
1285 ClangDynamicCheckerFunctions *dynamic_checkers =
1286 new ClangDynamicCheckerFunctions();
1288 DiagnosticManager install_diagnostics;
1290 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1291 if (install_diagnostics.Diagnostics().size())
1292 err.SetErrorString(install_diagnostics.GetString().c_str());
1294 err.SetErrorString("couldn't install checkers, unknown error");
1299 process->SetDynamicCheckers(dynamic_checkers);
1302 log->Printf("== [ClangExpressionParser::PrepareForExecution] "
1303 "Finished installing dynamic checkers ==");
1306 if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1307 process->GetDynamicCheckers())) {
1308 IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1309 function_name.AsCString());
1311 llvm::Module *module = execution_unit_sp->GetModule();
1312 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1313 err.SetErrorToGenericError();
1314 err.SetErrorString("Couldn't add dynamic checks to the expression");
1318 if (custom_passes.LatePasses) {
1320 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1321 "expression module '%s'",
1322 __FUNCTION__, m_expr.FunctionName());
1324 custom_passes.LatePasses->run(*module);
1330 if (execution_policy == eExecutionPolicyAlways ||
1331 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1332 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1335 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1341 lldb_private::Status ClangExpressionParser::RunStaticInitializers(
1342 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
1343 lldb_private::Status err;
1345 lldbassert(execution_unit_sp.get());
1346 lldbassert(exe_ctx.HasThreadScope());
1348 if (!execution_unit_sp.get()) {
1350 "can't run static initializers for a NULL execution unit");
1354 if (!exe_ctx.HasThreadScope()) {
1355 err.SetErrorString("can't run static initializers without a thread");
1359 std::vector<lldb::addr_t> static_initializers;
1361 execution_unit_sp->GetStaticInitializers(static_initializers);
1363 for (lldb::addr_t static_initializer : static_initializers) {
1364 EvaluateExpressionOptions options;
1366 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1367 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1368 llvm::ArrayRef<lldb::addr_t>(), options));
1370 DiagnosticManager execution_errors;
1371 lldb::ExpressionResults results =
1372 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1373 exe_ctx, call_static_initializer, options, execution_errors);
1375 if (results != lldb::eExpressionCompleted) {
1376 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1377 execution_errors.GetString().c_str());