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