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