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