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