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