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