1 //===-- ClangExpressionParser.cpp -----------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/AST/ASTContext.h" 10 #include "clang/AST/ASTDiagnostic.h" 11 #include "clang/AST/ExternalASTSource.h" 12 #include "clang/AST/PrettyPrinter.h" 13 #include "clang/Basic/Builtins.h" 14 #include "clang/Basic/DiagnosticIDs.h" 15 #include "clang/Basic/SourceLocation.h" 16 #include "clang/Basic/TargetInfo.h" 17 #include "clang/Basic/Version.h" 18 #include "clang/CodeGen/CodeGenAction.h" 19 #include "clang/CodeGen/ModuleBuilder.h" 20 #include "clang/Edit/Commit.h" 21 #include "clang/Edit/EditedSource.h" 22 #include "clang/Edit/EditsReceiver.h" 23 #include "clang/Frontend/CompilerInstance.h" 24 #include "clang/Frontend/CompilerInvocation.h" 25 #include "clang/Frontend/FrontendActions.h" 26 #include "clang/Frontend/FrontendDiagnostic.h" 27 #include "clang/Frontend/FrontendPluginRegistry.h" 28 #include "clang/Frontend/TextDiagnosticBuffer.h" 29 #include "clang/Frontend/TextDiagnosticPrinter.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Parse/ParseAST.h" 32 #include "clang/Rewrite/Core/Rewriter.h" 33 #include "clang/Rewrite/Frontend/FrontendActions.h" 34 #include "clang/Sema/CodeCompleteConsumer.h" 35 #include "clang/Sema/Sema.h" 36 #include "clang/Sema/SemaConsumer.h" 37 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ExecutionEngine/ExecutionEngine.h" 40 #include "llvm/Support/CrashRecoveryContext.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/FileSystem.h" 43 #include "llvm/Support/TargetSelect.h" 44 45 #include "llvm/IR/LLVMContext.h" 46 #include "llvm/IR/Module.h" 47 #include "llvm/Support/DynamicLibrary.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/Host.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Signals.h" 52 53 #include "ClangDiagnostic.h" 54 #include "ClangExpressionParser.h" 55 #include "ClangUserExpression.h" 56 57 #include "ASTUtils.h" 58 #include "ClangASTSource.h" 59 #include "ClangDiagnostic.h" 60 #include "ClangExpressionDeclMap.h" 61 #include "ClangExpressionHelper.h" 62 #include "ClangExpressionParser.h" 63 #include "ClangHost.h" 64 #include "ClangModulesDeclVendor.h" 65 #include "ClangPersistentVariables.h" 66 #include "IRDynamicChecks.h" 67 #include "IRForTarget.h" 68 #include "ModuleDependencyCollector.h" 69 70 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 71 #include "lldb/Core/Debugger.h" 72 #include "lldb/Core/Disassembler.h" 73 #include "lldb/Core/Module.h" 74 #include "lldb/Core/StreamFile.h" 75 #include "lldb/Expression/IRExecutionUnit.h" 76 #include "lldb/Expression/IRInterpreter.h" 77 #include "lldb/Host/File.h" 78 #include "lldb/Host/HostInfo.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 #include "Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h" 95 96 #include <cctype> 97 #include <memory> 98 99 using namespace clang; 100 using namespace llvm; 101 using namespace lldb_private; 102 103 //===----------------------------------------------------------------------===// 104 // Utility Methods for Clang 105 //===----------------------------------------------------------------------===// 106 107 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks { 108 ClangModulesDeclVendor &m_decl_vendor; 109 ClangPersistentVariables &m_persistent_vars; 110 clang::SourceManager &m_source_mgr; 111 StreamString m_error_stream; 112 bool m_has_errors = false; 113 114 public: 115 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, 116 ClangPersistentVariables &persistent_vars, 117 clang::SourceManager &source_mgr) 118 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars), 119 m_source_mgr(source_mgr) {} 120 121 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path, 122 const clang::Module * /*null*/) override { 123 // Ignore modules that are imported in the wrapper code as these are not 124 // loaded by the user. 125 llvm::StringRef filename = 126 m_source_mgr.getPresumedLoc(import_location).getFilename(); 127 if (filename == ClangExpressionSourceCode::g_prefix_file_name) 128 return; 129 130 SourceModule module; 131 132 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) 133 module.path.push_back(ConstString(component.first->getName())); 134 135 StreamString error_stream; 136 137 ClangModulesDeclVendor::ModuleVector exported_modules; 138 if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream)) 139 m_has_errors = true; 140 141 for (ClangModulesDeclVendor::ModuleID module : exported_modules) 142 m_persistent_vars.AddHandLoadedClangModule(module); 143 } 144 145 bool hasErrors() { return m_has_errors; } 146 147 llvm::StringRef getErrorString() { return m_error_stream.GetString(); } 148 }; 149 150 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer { 151 public: 152 ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) { 153 DiagnosticOptions *m_options = new DiagnosticOptions(opts); 154 m_options->ShowPresumedLoc = true; 155 m_options->ShowLevel = false; 156 m_os.reset(new llvm::raw_string_ostream(m_output)); 157 m_passthrough.reset( 158 new clang::TextDiagnosticPrinter(*m_os, m_options, false)); 159 } 160 161 void ResetManager(DiagnosticManager *manager = nullptr) { 162 m_manager = manager; 163 } 164 165 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 166 const clang::Diagnostic &Info) override { 167 if (!m_manager) { 168 // We have no DiagnosticManager before/after parsing but we still could 169 // receive diagnostics (e.g., by the ASTImporter failing to copy decls 170 // when we move the expression result ot the ScratchASTContext). Let's at 171 // least log these diagnostics until we find a way to properly render 172 // them and display them to the user. 173 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 174 if (log) { 175 llvm::SmallVector<char, 32> diag_str; 176 Info.FormatDiagnostic(diag_str); 177 diag_str.push_back('\0'); 178 const char *plain_diag = diag_str.data(); 179 LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag); 180 } 181 return; 182 } 183 184 // Render diagnostic message to m_output. 185 m_output.clear(); 186 m_passthrough->HandleDiagnostic(DiagLevel, Info); 187 m_os->flush(); 188 189 lldb_private::DiagnosticSeverity severity; 190 bool make_new_diagnostic = true; 191 192 switch (DiagLevel) { 193 case DiagnosticsEngine::Level::Fatal: 194 case DiagnosticsEngine::Level::Error: 195 severity = eDiagnosticSeverityError; 196 break; 197 case DiagnosticsEngine::Level::Warning: 198 severity = eDiagnosticSeverityWarning; 199 break; 200 case DiagnosticsEngine::Level::Remark: 201 case DiagnosticsEngine::Level::Ignored: 202 severity = eDiagnosticSeverityRemark; 203 break; 204 case DiagnosticsEngine::Level::Note: 205 m_manager->AppendMessageToDiagnostic(m_output); 206 make_new_diagnostic = false; 207 } 208 if (make_new_diagnostic) { 209 // ClangDiagnostic messages are expected to have no whitespace/newlines 210 // around them. 211 std::string stripped_output = 212 std::string(llvm::StringRef(m_output).trim()); 213 214 auto new_diagnostic = std::make_unique<ClangDiagnostic>( 215 stripped_output, severity, Info.getID()); 216 217 // FIXME: Should we try to filter out FixIts that apply to our generated 218 // code, and not the user's expression? 219 for (const clang::FixItHint &fixit : Info.getFixItHints()) { 220 if (fixit.isNull()) 221 continue; 222 new_diagnostic->AddFixitHint(fixit); 223 } 224 225 m_manager->AddDiagnostic(std::move(new_diagnostic)); 226 } 227 } 228 229 clang::TextDiagnosticPrinter *GetPassthrough() { return m_passthrough.get(); } 230 231 private: 232 DiagnosticManager *m_manager = nullptr; 233 std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough; 234 /// Output stream of m_passthrough. 235 std::shared_ptr<llvm::raw_string_ostream> m_os; 236 /// Output string filled by m_os. 237 std::string m_output; 238 }; 239 240 static void SetupModuleHeaderPaths(CompilerInstance *compiler, 241 std::vector<std::string> include_directories, 242 lldb::TargetSP target_sp) { 243 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 244 245 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts(); 246 247 for (const std::string &dir : include_directories) { 248 search_opts.AddPath(dir, frontend::System, false, true); 249 LLDB_LOG(log, "Added user include dir: {0}", dir); 250 } 251 252 llvm::SmallString<128> module_cache; 253 const auto &props = ModuleList::GetGlobalModuleListProperties(); 254 props.GetClangModulesCachePath().GetPath(module_cache); 255 search_opts.ModuleCachePath = std::string(module_cache.str()); 256 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str()); 257 258 search_opts.ResourceDir = GetClangResourceDir().GetPath(); 259 260 search_opts.ImplicitModuleMaps = true; 261 } 262 263 //===----------------------------------------------------------------------===// 264 // Implementation of ClangExpressionParser 265 //===----------------------------------------------------------------------===// 266 267 ClangExpressionParser::ClangExpressionParser( 268 ExecutionContextScope *exe_scope, Expression &expr, 269 bool generate_debug_info, std::vector<std::string> include_directories, 270 std::string filename) 271 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(), 272 m_pp_callbacks(nullptr), 273 m_include_directories(std::move(include_directories)), 274 m_filename(std::move(filename)) { 275 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 276 277 // We can't compile expressions without a target. So if the exe_scope is 278 // null or doesn't have a target, then we just need to get out of here. I'll 279 // lldbassert and not make any of the compiler objects since 280 // I can't return errors directly from the constructor. Further calls will 281 // check if the compiler was made and 282 // bag out if it wasn't. 283 284 if (!exe_scope) { 285 lldbassert(exe_scope && 286 "Can't make an expression parser with a null scope."); 287 return; 288 } 289 290 lldb::TargetSP target_sp; 291 target_sp = exe_scope->CalculateTarget(); 292 if (!target_sp) { 293 lldbassert(target_sp.get() && 294 "Can't make an expression parser with a null target."); 295 return; 296 } 297 298 // 1. Create a new compiler instance. 299 m_compiler.reset(new CompilerInstance()); 300 301 // When capturing a reproducer, hook up the file collector with clang to 302 // collector modules and headers. 303 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { 304 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>(); 305 m_compiler->setModuleDepCollector( 306 std::make_shared<ModuleDependencyCollectorAdaptor>( 307 fp.GetFileCollector())); 308 DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts(); 309 opts.IncludeSystemHeaders = true; 310 opts.IncludeModuleFiles = true; 311 } 312 313 // Make sure clang uses the same VFS as LLDB. 314 m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); 315 316 lldb::LanguageType frame_lang = 317 expr.Language(); // defaults to lldb::eLanguageTypeUnknown 318 bool overridden_target_opts = false; 319 lldb_private::LanguageRuntime *lang_rt = nullptr; 320 321 std::string abi; 322 ArchSpec target_arch; 323 target_arch = target_sp->GetArchitecture(); 324 325 const auto target_machine = target_arch.GetMachine(); 326 327 // If the expression is being evaluated in the context of an existing stack 328 // frame, we introspect to see if the language runtime is available. 329 330 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame(); 331 lldb::ProcessSP process_sp = exe_scope->CalculateProcess(); 332 333 // Make sure the user hasn't provided a preferred execution language with 334 // `expression --language X -- ...` 335 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown) 336 frame_lang = frame_sp->GetLanguage(); 337 338 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) { 339 lang_rt = process_sp->GetLanguageRuntime(frame_lang); 340 LLDB_LOGF(log, "Frame has language of type %s", 341 Language::GetNameForLanguageType(frame_lang)); 342 } 343 344 // 2. Configure the compiler with a set of default options that are 345 // appropriate for most situations. 346 if (target_arch.IsValid()) { 347 std::string triple = target_arch.GetTriple().str(); 348 m_compiler->getTargetOpts().Triple = triple; 349 LLDB_LOGF(log, "Using %s as the target triple", 350 m_compiler->getTargetOpts().Triple.c_str()); 351 } else { 352 // If we get here we don't have a valid target and just have to guess. 353 // Sometimes this will be ok to just use the host target triple (when we 354 // evaluate say "2+3", but other expressions like breakpoint conditions and 355 // other things that _are_ target specific really shouldn't just be using 356 // the host triple. In such a case the language runtime should expose an 357 // overridden options set (3), below. 358 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple(); 359 LLDB_LOGF(log, "Using default target triple of %s", 360 m_compiler->getTargetOpts().Triple.c_str()); 361 } 362 // Now add some special fixes for known architectures: Any arm32 iOS 363 // environment, but not on arm64 364 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos && 365 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos && 366 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) { 367 m_compiler->getTargetOpts().ABI = "apcs-gnu"; 368 } 369 // Supported subsets of x86 370 if (target_machine == llvm::Triple::x86 || 371 target_machine == llvm::Triple::x86_64) { 372 m_compiler->getTargetOpts().Features.push_back("+sse"); 373 m_compiler->getTargetOpts().Features.push_back("+sse2"); 374 } 375 376 // Set the target CPU to generate code for. This will be empty for any CPU 377 // that doesn't really need to make a special 378 // CPU string. 379 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU(); 380 381 // Set the target ABI 382 abi = GetClangTargetABI(target_arch); 383 if (!abi.empty()) 384 m_compiler->getTargetOpts().ABI = abi; 385 386 // 3. Now allow the runtime to provide custom configuration options for the 387 // target. In this case, a specialized language runtime is available and we 388 // can query it for extra options. For 99% of use cases, this will not be 389 // needed and should be provided when basic platform detection is not enough. 390 // FIXME: Generalize this. Only RenderScriptRuntime currently supports this 391 // currently. Hardcoding this isn't ideal but it's better than LanguageRuntime 392 // having knowledge of clang::TargetOpts. 393 if (auto *renderscript_rt = 394 llvm::dyn_cast_or_null<RenderScriptRuntime>(lang_rt)) 395 overridden_target_opts = 396 renderscript_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 if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>( 587 target_sp->GetPersistentExpressionStateForLanguage( 588 lldb::eLanguageTypeC))) { 589 std::unique_ptr<PPCallbacks> pp_callbacks( 590 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars, 591 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 598 // 8. Most of this we get from the CompilerInstance, but we also want to give 599 // the context an ExternalASTSource. 600 601 auto &PP = m_compiler->getPreprocessor(); 602 auto &builtin_context = PP.getBuiltinInfo(); 603 builtin_context.initializeBuiltins(PP.getIdentifierTable(), 604 m_compiler->getLangOpts()); 605 606 m_compiler->createASTContext(); 607 clang::ASTContext &ast_context = m_compiler->getASTContext(); 608 609 m_ast_context.reset(new TypeSystemClang( 610 "Expression ASTContext for '" + m_filename + "'", ast_context)); 611 612 std::string module_name("$__lldb_module"); 613 614 m_llvm_context.reset(new LLVMContext()); 615 m_code_generator.reset(CreateLLVMCodeGen( 616 m_compiler->getDiagnostics(), module_name, 617 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(), 618 m_compiler->getCodeGenOpts(), *m_llvm_context)); 619 } 620 621 ClangExpressionParser::~ClangExpressionParser() {} 622 623 namespace { 624 625 /// \class CodeComplete 626 /// 627 /// A code completion consumer for the clang Sema that is responsible for 628 /// creating the completion suggestions when a user requests completion 629 /// of an incomplete `expr` invocation. 630 class CodeComplete : public CodeCompleteConsumer { 631 CodeCompletionTUInfo m_info; 632 633 std::string m_expr; 634 unsigned m_position = 0; 635 CompletionRequest &m_request; 636 /// The printing policy we use when printing declarations for our completion 637 /// descriptions. 638 clang::PrintingPolicy m_desc_policy; 639 640 /// Returns true if the given character can be used in an identifier. 641 /// This also returns true for numbers because for completion we usually 642 /// just iterate backwards over iterators. 643 /// 644 /// Note: lldb uses '$' in its internal identifiers, so we also allow this. 645 static bool IsIdChar(char c) { 646 return c == '_' || std::isalnum(c) || c == '$'; 647 } 648 649 /// Returns true if the given character is used to separate arguments 650 /// in the command line of lldb. 651 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; } 652 653 /// Drops all tokens in front of the expression that are unrelated for 654 /// the completion of the cmd line. 'unrelated' means here that the token 655 /// is not interested for the lldb completion API result. 656 StringRef dropUnrelatedFrontTokens(StringRef cmd) { 657 if (cmd.empty()) 658 return cmd; 659 660 // If we are at the start of a word, then all tokens are unrelated to 661 // the current completion logic. 662 if (IsTokenSeparator(cmd.back())) 663 return StringRef(); 664 665 // Remove all previous tokens from the string as they are unrelated 666 // to completing the current token. 667 StringRef to_remove = cmd; 668 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) { 669 to_remove = to_remove.drop_back(); 670 } 671 cmd = cmd.drop_front(to_remove.size()); 672 673 return cmd; 674 } 675 676 /// Removes the last identifier token from the given cmd line. 677 StringRef removeLastToken(StringRef cmd) { 678 while (!cmd.empty() && IsIdChar(cmd.back())) { 679 cmd = cmd.drop_back(); 680 } 681 return cmd; 682 } 683 684 /// Attemps to merge the given completion from the given position into the 685 /// existing command. Returns the completion string that can be returned to 686 /// the lldb completion API. 687 std::string mergeCompletion(StringRef existing, unsigned pos, 688 StringRef completion) { 689 StringRef existing_command = existing.substr(0, pos); 690 // We rewrite the last token with the completion, so let's drop that 691 // token from the command. 692 existing_command = removeLastToken(existing_command); 693 // We also should remove all previous tokens from the command as they 694 // would otherwise be added to the completion that already has the 695 // completion. 696 existing_command = dropUnrelatedFrontTokens(existing_command); 697 return existing_command.str() + completion.str(); 698 } 699 700 public: 701 /// Constructs a CodeComplete consumer that can be attached to a Sema. 702 /// 703 /// \param[out] expr 704 /// The whole expression string that we are currently parsing. This 705 /// string needs to be equal to the input the user typed, and NOT the 706 /// final code that Clang is parsing. 707 /// \param[out] position 708 /// The character position of the user cursor in the `expr` parameter. 709 /// 710 CodeComplete(CompletionRequest &request, clang::LangOptions ops, 711 std::string expr, unsigned position) 712 : CodeCompleteConsumer(CodeCompleteOptions()), 713 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr), 714 m_position(position), m_request(request), m_desc_policy(ops) { 715 716 // Ensure that the printing policy is producing a description that is as 717 // short as possible. 718 m_desc_policy.SuppressScope = true; 719 m_desc_policy.SuppressTagKeyword = true; 720 m_desc_policy.FullyQualifiedName = false; 721 m_desc_policy.TerseOutput = true; 722 m_desc_policy.IncludeNewlines = false; 723 m_desc_policy.UseVoidForZeroParams = false; 724 m_desc_policy.Bool = true; 725 } 726 727 /// Deregisters and destroys this code-completion consumer. 728 ~CodeComplete() override {} 729 730 /// \name Code-completion filtering 731 /// Check if the result should be filtered out. 732 bool isResultFilteredOut(StringRef Filter, 733 CodeCompletionResult Result) override { 734 // This code is mostly copied from CodeCompleteConsumer. 735 switch (Result.Kind) { 736 case CodeCompletionResult::RK_Declaration: 737 return !( 738 Result.Declaration->getIdentifier() && 739 Result.Declaration->getIdentifier()->getName().startswith(Filter)); 740 case CodeCompletionResult::RK_Keyword: 741 return !StringRef(Result.Keyword).startswith(Filter); 742 case CodeCompletionResult::RK_Macro: 743 return !Result.Macro->getName().startswith(Filter); 744 case CodeCompletionResult::RK_Pattern: 745 return !StringRef(Result.Pattern->getAsString()).startswith(Filter); 746 } 747 // If we trigger this assert or the above switch yields a warning, then 748 // CodeCompletionResult has been enhanced with more kinds of completion 749 // results. Expand the switch above in this case. 750 assert(false && "Unknown completion result type?"); 751 // If we reach this, then we should just ignore whatever kind of unknown 752 // result we got back. We probably can't turn it into any kind of useful 753 // completion suggestion with the existing code. 754 return true; 755 } 756 757 /// \name Code-completion callbacks 758 /// Process the finalized code-completion results. 759 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context, 760 CodeCompletionResult *Results, 761 unsigned NumResults) override { 762 763 // The Sema put the incomplete token we try to complete in here during 764 // lexing, so we need to retrieve it here to know what we are completing. 765 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter(); 766 767 // Iterate over all the results. Filter out results we don't want and 768 // process the rest. 769 for (unsigned I = 0; I != NumResults; ++I) { 770 // Filter the results with the information from the Sema. 771 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I])) 772 continue; 773 774 CodeCompletionResult &R = Results[I]; 775 std::string ToInsert; 776 std::string Description; 777 // Handle the different completion kinds that come from the Sema. 778 switch (R.Kind) { 779 case CodeCompletionResult::RK_Declaration: { 780 const NamedDecl *D = R.Declaration; 781 ToInsert = R.Declaration->getNameAsString(); 782 // If we have a function decl that has no arguments we want to 783 // complete the empty parantheses for the user. If the function has 784 // arguments, we at least complete the opening bracket. 785 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) { 786 if (F->getNumParams() == 0) 787 ToInsert += "()"; 788 else 789 ToInsert += "("; 790 raw_string_ostream OS(Description); 791 F->print(OS, m_desc_policy, false); 792 OS.flush(); 793 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 794 Description = V->getType().getAsString(m_desc_policy); 795 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) { 796 Description = F->getType().getAsString(m_desc_policy); 797 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) { 798 // If we try to complete a namespace, then we can directly append 799 // the '::'. 800 if (!N->isAnonymousNamespace()) 801 ToInsert += "::"; 802 } 803 break; 804 } 805 case CodeCompletionResult::RK_Keyword: 806 ToInsert = R.Keyword; 807 break; 808 case CodeCompletionResult::RK_Macro: 809 ToInsert = R.Macro->getName().str(); 810 break; 811 case CodeCompletionResult::RK_Pattern: 812 ToInsert = R.Pattern->getTypedText(); 813 break; 814 } 815 // At this point all information is in the ToInsert string. 816 817 // We also filter some internal lldb identifiers here. The user 818 // shouldn't see these. 819 if (StringRef(ToInsert).startswith("$__lldb_")) 820 continue; 821 if (!ToInsert.empty()) { 822 // Merge the suggested Token into the existing command line to comply 823 // with the kind of result the lldb API expects. 824 std::string CompletionSuggestion = 825 mergeCompletion(m_expr, m_position, ToInsert); 826 m_request.AddCompletion(CompletionSuggestion, Description); 827 } 828 } 829 } 830 831 /// \param S the semantic-analyzer object for which code-completion is being 832 /// done. 833 /// 834 /// \param CurrentArg the index of the current argument. 835 /// 836 /// \param Candidates an array of overload candidates. 837 /// 838 /// \param NumCandidates the number of overload candidates 839 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 840 OverloadCandidate *Candidates, 841 unsigned NumCandidates, 842 SourceLocation OpenParLoc) override { 843 // At the moment we don't filter out any overloaded candidates. 844 } 845 846 CodeCompletionAllocator &getAllocator() override { 847 return m_info.getAllocator(); 848 } 849 850 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; } 851 }; 852 } // namespace 853 854 bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line, 855 unsigned pos, unsigned typed_pos) { 856 DiagnosticManager mgr; 857 // We need the raw user expression here because that's what the CodeComplete 858 // class uses to provide completion suggestions. 859 // However, the `Text` method only gives us the transformed expression here. 860 // To actually get the raw user input here, we have to cast our expression to 861 // the LLVMUserExpression which exposes the right API. This should never fail 862 // as we always have a ClangUserExpression whenever we call this. 863 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr); 864 CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr->GetUserText(), 865 typed_pos); 866 // We don't need a code generator for parsing. 867 m_code_generator.reset(); 868 // Start parsing the expression with our custom code completion consumer. 869 ParseInternal(mgr, &CC, line, pos); 870 return true; 871 } 872 873 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) { 874 return ParseInternal(diagnostic_manager); 875 } 876 877 unsigned 878 ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager, 879 CodeCompleteConsumer *completion_consumer, 880 unsigned completion_line, 881 unsigned completion_column) { 882 ClangDiagnosticManagerAdapter *adapter = 883 static_cast<ClangDiagnosticManagerAdapter *>( 884 m_compiler->getDiagnostics().getClient()); 885 auto diag_buf = adapter->GetPassthrough(); 886 887 adapter->ResetManager(&diagnostic_manager); 888 889 const char *expr_text = m_expr.Text(); 890 891 clang::SourceManager &source_mgr = m_compiler->getSourceManager(); 892 bool created_main_file = false; 893 894 // Clang wants to do completion on a real file known by Clang's file manager, 895 // so we have to create one to make this work. 896 // TODO: We probably could also simulate to Clang's file manager that there 897 // is a real file that contains our code. 898 bool should_create_file = completion_consumer != nullptr; 899 900 // We also want a real file on disk if we generate full debug info. 901 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() == 902 codegenoptions::FullDebugInfo; 903 904 if (should_create_file) { 905 int temp_fd = -1; 906 llvm::SmallString<128> result_path; 907 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) { 908 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr"); 909 std::string temp_source_path = tmpdir_file_spec.GetPath(); 910 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path); 911 } else { 912 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path); 913 } 914 915 if (temp_fd != -1) { 916 lldb_private::NativeFile file(temp_fd, File::eOpenOptionWrite, true); 917 const size_t expr_text_len = strlen(expr_text); 918 size_t bytes_written = expr_text_len; 919 if (file.Write(expr_text, bytes_written).Success()) { 920 if (bytes_written == expr_text_len) { 921 file.Close(); 922 if (auto fileEntry = 923 m_compiler->getFileManager().getFile(result_path)) { 924 source_mgr.setMainFileID(source_mgr.createFileID( 925 *fileEntry, 926 SourceLocation(), SrcMgr::C_User)); 927 created_main_file = true; 928 } 929 } 930 } 931 } 932 } 933 934 if (!created_main_file) { 935 std::unique_ptr<MemoryBuffer> memory_buffer = 936 MemoryBuffer::getMemBufferCopy(expr_text, m_filename); 937 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer))); 938 } 939 940 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), 941 &m_compiler->getPreprocessor()); 942 943 ClangExpressionHelper *type_system_helper = 944 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 945 946 // If we want to parse for code completion, we need to attach our code 947 // completion consumer to the Sema and specify a completion position. 948 // While parsing the Sema will call this consumer with the provided 949 // completion suggestions. 950 if (completion_consumer) { 951 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID()); 952 auto &PP = m_compiler->getPreprocessor(); 953 // Lines and columns start at 1 in Clang, but code completion positions are 954 // indexed from 0, so we need to add 1 to the line and column here. 955 ++completion_line; 956 ++completion_column; 957 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column); 958 } 959 960 ASTConsumer *ast_transformer = 961 type_system_helper->ASTTransformer(m_code_generator.get()); 962 963 std::unique_ptr<clang::ASTConsumer> Consumer; 964 if (ast_transformer) { 965 Consumer.reset(new ASTConsumerForwarder(ast_transformer)); 966 } else if (m_code_generator) { 967 Consumer.reset(new ASTConsumerForwarder(m_code_generator.get())); 968 } else { 969 Consumer.reset(new ASTConsumer()); 970 } 971 972 clang::ASTContext &ast_context = m_compiler->getASTContext(); 973 974 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context, 975 *Consumer, TU_Complete, completion_consumer)); 976 m_compiler->setASTConsumer(std::move(Consumer)); 977 978 if (ast_context.getLangOpts().Modules) { 979 m_compiler->createASTReader(); 980 m_ast_context->setSema(&m_compiler->getSema()); 981 } 982 983 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); 984 if (decl_map) { 985 decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer()); 986 987 clang::ExternalASTSource *ast_source = decl_map->CreateProxy(); 988 989 if (ast_context.getExternalSource()) { 990 auto module_wrapper = 991 new ExternalASTSourceWrapper(ast_context.getExternalSource()); 992 993 auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source); 994 995 auto multiplexer = 996 new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper); 997 IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer); 998 ast_context.setExternalSource(Source); 999 } else { 1000 ast_context.setExternalSource(ast_source); 1001 } 1002 decl_map->InstallASTContext(*m_ast_context); 1003 } 1004 1005 // Check that the ASTReader is properly attached to ASTContext and Sema. 1006 if (ast_context.getLangOpts().Modules) { 1007 assert(m_compiler->getASTContext().getExternalSource() && 1008 "ASTContext doesn't know about the ASTReader?"); 1009 assert(m_compiler->getSema().getExternalSource() && 1010 "Sema doesn't know about the ASTReader?"); 1011 } 1012 1013 { 1014 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema( 1015 &m_compiler->getSema()); 1016 ParseAST(m_compiler->getSema(), false, false); 1017 } 1018 1019 // Make sure we have no pointer to the Sema we are about to destroy. 1020 if (ast_context.getLangOpts().Modules) 1021 m_ast_context->setSema(nullptr); 1022 // Destroy the Sema. This is necessary because we want to emulate the 1023 // original behavior of ParseAST (which also destroys the Sema after parsing). 1024 m_compiler->setSema(nullptr); 1025 1026 diag_buf->EndSourceFile(); 1027 1028 unsigned num_errors = diag_buf->getNumErrors(); 1029 1030 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) { 1031 num_errors++; 1032 diagnostic_manager.PutString(eDiagnosticSeverityError, 1033 "while importing modules:"); 1034 diagnostic_manager.AppendMessageToDiagnostic( 1035 m_pp_callbacks->getErrorString()); 1036 } 1037 1038 if (!num_errors) { 1039 type_system_helper->CommitPersistentDecls(); 1040 } 1041 1042 adapter->ResetManager(); 1043 1044 return num_errors; 1045 } 1046 1047 std::string 1048 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) { 1049 std::string abi; 1050 1051 if (target_arch.IsMIPS()) { 1052 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) { 1053 case ArchSpec::eMIPSABI_N64: 1054 abi = "n64"; 1055 break; 1056 case ArchSpec::eMIPSABI_N32: 1057 abi = "n32"; 1058 break; 1059 case ArchSpec::eMIPSABI_O32: 1060 abi = "o32"; 1061 break; 1062 default: 1063 break; 1064 } 1065 } 1066 return abi; 1067 } 1068 1069 /// Applies the given Fix-It hint to the given commit. 1070 static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) { 1071 // This is cobbed from clang::Rewrite::FixItRewriter. 1072 if (fixit.CodeToInsert.empty()) { 1073 if (fixit.InsertFromRange.isValid()) { 1074 commit.insertFromRange(fixit.RemoveRange.getBegin(), 1075 fixit.InsertFromRange, /*afterToken=*/false, 1076 fixit.BeforePreviousInsertions); 1077 return; 1078 } 1079 commit.remove(fixit.RemoveRange); 1080 return; 1081 } 1082 if (fixit.RemoveRange.isTokenRange() || 1083 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) { 1084 commit.replace(fixit.RemoveRange, fixit.CodeToInsert); 1085 return; 1086 } 1087 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert, 1088 /*afterToken=*/false, fixit.BeforePreviousInsertions); 1089 } 1090 1091 bool ClangExpressionParser::RewriteExpression( 1092 DiagnosticManager &diagnostic_manager) { 1093 clang::SourceManager &source_manager = m_compiler->getSourceManager(); 1094 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(), 1095 nullptr); 1096 clang::edit::Commit commit(editor); 1097 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts()); 1098 1099 class RewritesReceiver : public edit::EditsReceiver { 1100 Rewriter &rewrite; 1101 1102 public: 1103 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {} 1104 1105 void insert(SourceLocation loc, StringRef text) override { 1106 rewrite.InsertText(loc, text); 1107 } 1108 void replace(CharSourceRange range, StringRef text) override { 1109 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text); 1110 } 1111 }; 1112 1113 RewritesReceiver rewrites_receiver(rewriter); 1114 1115 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics(); 1116 size_t num_diags = diagnostics.size(); 1117 if (num_diags == 0) 1118 return false; 1119 1120 for (const auto &diag : diagnostic_manager.Diagnostics()) { 1121 const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get()); 1122 if (!diagnostic) 1123 continue; 1124 if (!diagnostic->HasFixIts()) 1125 continue; 1126 // Don't apply warning Fix-Its, since the compiler doesn't have enough 1127 // context in an expression for the warning to be useful. 1128 if (diagnostic->GetSeverity() != eDiagnosticSeverityError) 1129 continue; 1130 for (const FixItHint &fixit : diagnostic->FixIts()) 1131 ApplyFixIt(fixit, commit); 1132 } 1133 1134 // FIXME - do we want to try to propagate specific errors here? 1135 if (!commit.isCommitable()) 1136 return false; 1137 else if (!editor.commit(commit)) 1138 return false; 1139 1140 // Now play all the edits, and stash the result in the diagnostic manager. 1141 editor.applyRewrites(rewrites_receiver); 1142 RewriteBuffer &main_file_buffer = 1143 rewriter.getEditBuffer(source_manager.getMainFileID()); 1144 1145 std::string fixed_expression; 1146 llvm::raw_string_ostream out_stream(fixed_expression); 1147 1148 main_file_buffer.write(out_stream); 1149 out_stream.flush(); 1150 diagnostic_manager.SetFixedExpression(fixed_expression); 1151 1152 return true; 1153 } 1154 1155 static bool FindFunctionInModule(ConstString &mangled_name, 1156 llvm::Module *module, const char *orig_name) { 1157 for (const auto &func : module->getFunctionList()) { 1158 const StringRef &name = func.getName(); 1159 if (name.find(orig_name) != StringRef::npos) { 1160 mangled_name.SetString(name); 1161 return true; 1162 } 1163 } 1164 1165 return false; 1166 } 1167 1168 lldb_private::Status ClangExpressionParser::PrepareForExecution( 1169 lldb::addr_t &func_addr, lldb::addr_t &func_end, 1170 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, 1171 bool &can_interpret, ExecutionPolicy execution_policy) { 1172 func_addr = LLDB_INVALID_ADDRESS; 1173 func_end = LLDB_INVALID_ADDRESS; 1174 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1175 1176 lldb_private::Status err; 1177 1178 std::unique_ptr<llvm::Module> llvm_module_up( 1179 m_code_generator->ReleaseModule()); 1180 1181 if (!llvm_module_up) { 1182 err.SetErrorToGenericError(); 1183 err.SetErrorString("IR doesn't contain a module"); 1184 return err; 1185 } 1186 1187 ConstString function_name; 1188 1189 if (execution_policy != eExecutionPolicyTopLevel) { 1190 // Find the actual name of the function (it's often mangled somehow) 1191 1192 if (!FindFunctionInModule(function_name, llvm_module_up.get(), 1193 m_expr.FunctionName())) { 1194 err.SetErrorToGenericError(); 1195 err.SetErrorStringWithFormat("Couldn't find %s() in the module", 1196 m_expr.FunctionName()); 1197 return err; 1198 } else { 1199 LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(), 1200 m_expr.FunctionName()); 1201 } 1202 } 1203 1204 SymbolContext sc; 1205 1206 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) { 1207 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything); 1208 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) { 1209 sc.target_sp = target_sp; 1210 } 1211 1212 LLVMUserExpression::IRPasses custom_passes; 1213 { 1214 auto lang = m_expr.Language(); 1215 LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__, 1216 Language::GetNameForLanguageType(lang)); 1217 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP(); 1218 if (process_sp && lang != lldb::eLanguageTypeUnknown) { 1219 auto runtime = process_sp->GetLanguageRuntime(lang); 1220 if (runtime) 1221 runtime->GetIRPasses(custom_passes); 1222 } 1223 } 1224 1225 if (custom_passes.EarlyPasses) { 1226 LLDB_LOGF(log, 1227 "%s - Running Early IR Passes from LanguageRuntime on " 1228 "expression module '%s'", 1229 __FUNCTION__, m_expr.FunctionName()); 1230 1231 custom_passes.EarlyPasses->run(*llvm_module_up); 1232 } 1233 1234 execution_unit_sp = std::make_shared<IRExecutionUnit>( 1235 m_llvm_context, // handed off here 1236 llvm_module_up, // handed off here 1237 function_name, exe_ctx.GetTargetSP(), sc, 1238 m_compiler->getTargetOpts().Features); 1239 1240 ClangExpressionHelper *type_system_helper = 1241 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 1242 ClangExpressionDeclMap *decl_map = 1243 type_system_helper->DeclMap(); // result can be NULL 1244 1245 if (decl_map) { 1246 Target *target = exe_ctx.GetTargetPtr(); 1247 auto &error_stream = target->GetDebugger().GetErrorStream(); 1248 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(), 1249 *execution_unit_sp, error_stream, 1250 function_name.AsCString()); 1251 1252 bool ir_can_run = 1253 ir_for_target.runOnModule(*execution_unit_sp->GetModule()); 1254 1255 if (!ir_can_run) { 1256 err.SetErrorString( 1257 "The expression could not be prepared to run in the target"); 1258 return err; 1259 } 1260 1261 Process *process = exe_ctx.GetProcessPtr(); 1262 1263 if (execution_policy != eExecutionPolicyAlways && 1264 execution_policy != eExecutionPolicyTopLevel) { 1265 lldb_private::Status interpret_error; 1266 1267 bool interpret_function_calls = 1268 !process ? false : process->CanInterpretFunctionCalls(); 1269 can_interpret = IRInterpreter::CanInterpret( 1270 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), 1271 interpret_error, interpret_function_calls); 1272 1273 if (!can_interpret && execution_policy == eExecutionPolicyNever) { 1274 err.SetErrorStringWithFormat( 1275 "Can't evaluate the expression without a running target due to: %s", 1276 interpret_error.AsCString()); 1277 return err; 1278 } 1279 } 1280 1281 if (!process && execution_policy == eExecutionPolicyAlways) { 1282 err.SetErrorString("Expression needed to run in the target, but the " 1283 "target can't be run"); 1284 return err; 1285 } 1286 1287 if (!process && execution_policy == eExecutionPolicyTopLevel) { 1288 err.SetErrorString("Top-level code needs to be inserted into a runnable " 1289 "target, but the target can't be run"); 1290 return err; 1291 } 1292 1293 if (execution_policy == eExecutionPolicyAlways || 1294 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) { 1295 if (m_expr.NeedsValidation() && process) { 1296 if (!process->GetDynamicCheckers()) { 1297 ClangDynamicCheckerFunctions *dynamic_checkers = 1298 new ClangDynamicCheckerFunctions(); 1299 1300 DiagnosticManager install_diagnostics; 1301 1302 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) { 1303 if (install_diagnostics.Diagnostics().size()) 1304 err.SetErrorString(install_diagnostics.GetString().c_str()); 1305 else 1306 err.SetErrorString("couldn't install checkers, unknown error"); 1307 1308 return err; 1309 } 1310 1311 process->SetDynamicCheckers(dynamic_checkers); 1312 1313 LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] " 1314 "Finished installing dynamic checkers =="); 1315 } 1316 1317 if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>( 1318 process->GetDynamicCheckers())) { 1319 IRDynamicChecks ir_dynamic_checks(*checker_funcs, 1320 function_name.AsCString()); 1321 1322 llvm::Module *module = execution_unit_sp->GetModule(); 1323 if (!module || !ir_dynamic_checks.runOnModule(*module)) { 1324 err.SetErrorToGenericError(); 1325 err.SetErrorString("Couldn't add dynamic checks to the expression"); 1326 return err; 1327 } 1328 1329 if (custom_passes.LatePasses) { 1330 LLDB_LOGF(log, 1331 "%s - Running Late IR Passes from LanguageRuntime on " 1332 "expression module '%s'", 1333 __FUNCTION__, m_expr.FunctionName()); 1334 1335 custom_passes.LatePasses->run(*module); 1336 } 1337 } 1338 } 1339 } 1340 1341 if (execution_policy == eExecutionPolicyAlways || 1342 execution_policy == eExecutionPolicyTopLevel || !can_interpret) { 1343 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 1344 } 1345 } else { 1346 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 1347 } 1348 1349 return err; 1350 } 1351 1352 lldb_private::Status ClangExpressionParser::RunStaticInitializers( 1353 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) { 1354 lldb_private::Status err; 1355 1356 lldbassert(execution_unit_sp.get()); 1357 lldbassert(exe_ctx.HasThreadScope()); 1358 1359 if (!execution_unit_sp.get()) { 1360 err.SetErrorString( 1361 "can't run static initializers for a NULL execution unit"); 1362 return err; 1363 } 1364 1365 if (!exe_ctx.HasThreadScope()) { 1366 err.SetErrorString("can't run static initializers without a thread"); 1367 return err; 1368 } 1369 1370 std::vector<lldb::addr_t> static_initializers; 1371 1372 execution_unit_sp->GetStaticInitializers(static_initializers); 1373 1374 for (lldb::addr_t static_initializer : static_initializers) { 1375 EvaluateExpressionOptions options; 1376 1377 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction( 1378 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(), 1379 llvm::ArrayRef<lldb::addr_t>(), options)); 1380 1381 DiagnosticManager execution_errors; 1382 lldb::ExpressionResults results = 1383 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan( 1384 exe_ctx, call_static_initializer, options, execution_errors); 1385 1386 if (results != lldb::eExpressionCompleted) { 1387 err.SetErrorStringWithFormat("couldn't run static initializer: %s", 1388 execution_errors.GetString().c_str()); 1389 return err; 1390 } 1391 } 1392 1393 return err; 1394 } 1395