1 //===-- ClangModulesDeclVendor.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 <mutex> 10 11 #include "clang/Basic/TargetInfo.h" 12 #include "clang/Frontend/CompilerInstance.h" 13 #include "clang/Frontend/FrontendActions.h" 14 #include "clang/Lex/Preprocessor.h" 15 #include "clang/Lex/PreprocessorOptions.h" 16 #include "clang/Parse/Parser.h" 17 #include "clang/Sema/Lookup.h" 18 #include "clang/Serialization/ASTReader.h" 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/Path.h" 21 #include "llvm/Support/Threading.h" 22 23 #include "ClangHost.h" 24 #include "ClangModulesDeclVendor.h" 25 #include "ModuleDependencyCollector.h" 26 27 #include "lldb/Core/ModuleList.h" 28 #include "lldb/Host/Host.h" 29 #include "lldb/Host/HostInfo.h" 30 #include "lldb/Symbol/ClangASTContext.h" 31 #include "lldb/Symbol/CompileUnit.h" 32 #include "lldb/Symbol/SourceModule.h" 33 #include "lldb/Target/Target.h" 34 #include "lldb/Utility/FileSpec.h" 35 #include "lldb/Utility/LLDBAssert.h" 36 #include "lldb/Utility/Log.h" 37 #include "lldb/Utility/Reproducer.h" 38 #include "lldb/Utility/StreamString.h" 39 40 using namespace lldb_private; 41 42 namespace { 43 // Any Clang compiler requires a consumer for diagnostics. This one stores 44 // them as strings so we can provide them to the user in case a module failed 45 // to load. 46 class StoringDiagnosticConsumer : public clang::DiagnosticConsumer { 47 public: 48 StoringDiagnosticConsumer(); 49 50 void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel, 51 const clang::Diagnostic &info) override; 52 53 void ClearDiagnostics(); 54 55 void DumpDiagnostics(Stream &error_stream); 56 57 private: 58 typedef std::pair<clang::DiagnosticsEngine::Level, std::string> 59 IDAndDiagnostic; 60 std::vector<IDAndDiagnostic> m_diagnostics; 61 Log *m_log; 62 }; 63 64 // The private implementation of our ClangModulesDeclVendor. Contains all the 65 // Clang state required to load modules. 66 class ClangModulesDeclVendorImpl : public ClangModulesDeclVendor { 67 public: 68 ClangModulesDeclVendorImpl( 69 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine, 70 std::shared_ptr<clang::CompilerInvocation> compiler_invocation, 71 std::unique_ptr<clang::CompilerInstance> compiler_instance, 72 std::unique_ptr<clang::Parser> parser); 73 74 ~ClangModulesDeclVendorImpl() override = default; 75 76 bool AddModule(const SourceModule &module, ModuleVector *exported_modules, 77 Stream &error_stream) override; 78 79 bool AddModulesForCompileUnit(CompileUnit &cu, ModuleVector &exported_modules, 80 Stream &error_stream) override; 81 82 uint32_t FindDecls(ConstString name, bool append, uint32_t max_matches, 83 std::vector<clang::NamedDecl *> &decls) override; 84 85 void ForEachMacro(const ModuleVector &modules, 86 std::function<bool(const std::string &)> handler) override; 87 88 clang::ExternalASTMerger::ImporterSource GetImporterSource() override; 89 private: 90 void 91 ReportModuleExportsHelper(std::set<ClangModulesDeclVendor::ModuleID> &exports, 92 clang::Module *module); 93 94 void ReportModuleExports(ModuleVector &exports, clang::Module *module); 95 96 clang::ModuleLoadResult DoGetModule(clang::ModuleIdPath path, 97 bool make_visible); 98 99 bool m_enabled = false; 100 101 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine; 102 std::shared_ptr<clang::CompilerInvocation> m_compiler_invocation; 103 std::unique_ptr<clang::CompilerInstance> m_compiler_instance; 104 std::unique_ptr<clang::Parser> m_parser; 105 size_t m_source_location_index = 106 0; // used to give name components fake SourceLocations 107 108 typedef std::vector<ConstString> ImportedModule; 109 typedef std::map<ImportedModule, clang::Module *> ImportedModuleMap; 110 typedef std::set<ModuleID> ImportedModuleSet; 111 ImportedModuleMap m_imported_modules; 112 ImportedModuleSet m_user_imported_modules; 113 const clang::ExternalASTMerger::OriginMap m_origin_map; 114 // We assume that every ASTContext has an ClangASTContext, so we also store 115 // a custom ClangASTContext for our internal ASTContext. 116 std::unique_ptr<ClangASTContext> m_ast_context; 117 }; 118 } // anonymous namespace 119 120 StoringDiagnosticConsumer::StoringDiagnosticConsumer() { 121 m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 122 } 123 124 void StoringDiagnosticConsumer::HandleDiagnostic( 125 clang::DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &info) { 126 llvm::SmallVector<char, 256> diagnostic_string; 127 128 info.FormatDiagnostic(diagnostic_string); 129 130 m_diagnostics.push_back( 131 IDAndDiagnostic(DiagLevel, std::string(diagnostic_string.data(), 132 diagnostic_string.size()))); 133 } 134 135 void StoringDiagnosticConsumer::ClearDiagnostics() { m_diagnostics.clear(); } 136 137 void StoringDiagnosticConsumer::DumpDiagnostics(Stream &error_stream) { 138 for (IDAndDiagnostic &diag : m_diagnostics) { 139 switch (diag.first) { 140 default: 141 error_stream.PutCString(diag.second); 142 error_stream.PutChar('\n'); 143 break; 144 case clang::DiagnosticsEngine::Level::Ignored: 145 break; 146 } 147 } 148 } 149 150 ClangModulesDeclVendor::ClangModulesDeclVendor() 151 : ClangDeclVendor(eClangModuleDeclVendor) {} 152 153 ClangModulesDeclVendor::~ClangModulesDeclVendor() {} 154 155 ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl( 156 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine, 157 std::shared_ptr<clang::CompilerInvocation> compiler_invocation, 158 std::unique_ptr<clang::CompilerInstance> compiler_instance, 159 std::unique_ptr<clang::Parser> parser) 160 : m_diagnostics_engine(std::move(diagnostics_engine)), 161 m_compiler_invocation(std::move(compiler_invocation)), 162 m_compiler_instance(std::move(compiler_instance)), 163 m_parser(std::move(parser)), m_origin_map() { 164 165 // Initialize our ClangASTContext. 166 m_ast_context.reset(new ClangASTContext(m_compiler_instance->getASTContext())); 167 } 168 169 void ClangModulesDeclVendorImpl::ReportModuleExportsHelper( 170 std::set<ClangModulesDeclVendor::ModuleID> &exports, 171 clang::Module *module) { 172 if (exports.count(reinterpret_cast<ClangModulesDeclVendor::ModuleID>(module))) 173 return; 174 175 exports.insert(reinterpret_cast<ClangModulesDeclVendor::ModuleID>(module)); 176 177 llvm::SmallVector<clang::Module *, 2> sub_exports; 178 179 module->getExportedModules(sub_exports); 180 181 for (clang::Module *module : sub_exports) { 182 ReportModuleExportsHelper(exports, module); 183 } 184 } 185 186 void ClangModulesDeclVendorImpl::ReportModuleExports( 187 ClangModulesDeclVendor::ModuleVector &exports, clang::Module *module) { 188 std::set<ClangModulesDeclVendor::ModuleID> exports_set; 189 190 ReportModuleExportsHelper(exports_set, module); 191 192 for (ModuleID module : exports_set) { 193 exports.push_back(module); 194 } 195 } 196 197 bool ClangModulesDeclVendorImpl::AddModule(const SourceModule &module, 198 ModuleVector *exported_modules, 199 Stream &error_stream) { 200 // Fail early. 201 202 if (m_compiler_instance->hadModuleLoaderFatalFailure()) { 203 error_stream.PutCString("error: Couldn't load a module because the module " 204 "loader is in a fatal state.\n"); 205 return false; 206 } 207 208 // Check if we've already imported this module. 209 210 std::vector<ConstString> imported_module; 211 212 for (ConstString path_component : module.path) { 213 imported_module.push_back(path_component); 214 } 215 216 { 217 ImportedModuleMap::iterator mi = m_imported_modules.find(imported_module); 218 219 if (mi != m_imported_modules.end()) { 220 if (exported_modules) { 221 ReportModuleExports(*exported_modules, mi->second); 222 } 223 return true; 224 } 225 } 226 227 clang::HeaderSearch &HS = 228 m_compiler_instance->getPreprocessor().getHeaderSearchInfo(); 229 230 if (module.search_path) { 231 auto path_begin = llvm::sys::path::begin(module.search_path.GetStringRef()); 232 auto path_end = llvm::sys::path::end(module.search_path.GetStringRef()); 233 auto sysroot_begin = llvm::sys::path::begin(module.sysroot.GetStringRef()); 234 auto sysroot_end = llvm::sys::path::end(module.sysroot.GetStringRef()); 235 // FIXME: Use C++14 std::equal(it, it, it, it) variant once it's available. 236 bool is_system_module = (std::distance(path_begin, path_end) >= 237 std::distance(sysroot_begin, sysroot_end)) && 238 std::equal(sysroot_begin, sysroot_end, path_begin); 239 // No need to inject search paths to modules in the sysroot. 240 if (!is_system_module) { 241 auto error = [&]() { 242 error_stream.Printf("error: No module map file in %s\n", 243 module.search_path.AsCString()); 244 return false; 245 }; 246 247 bool is_system = true; 248 bool is_framework = false; 249 auto dir = 250 HS.getFileMgr().getDirectory(module.search_path.GetStringRef()); 251 if (!dir) 252 return error(); 253 auto *file = HS.lookupModuleMapFile(*dir, is_framework); 254 if (!file) 255 return error(); 256 if (!HS.loadModuleMapFile(file, is_system)) 257 return error(); 258 } 259 } 260 if (!HS.lookupModule(module.path.front().GetStringRef())) { 261 error_stream.Printf("error: Header search couldn't locate module %s\n", 262 module.path.front().AsCString()); 263 return false; 264 } 265 266 llvm::SmallVector<std::pair<clang::IdentifierInfo *, clang::SourceLocation>, 267 4> 268 clang_path; 269 270 { 271 clang::SourceManager &source_manager = 272 m_compiler_instance->getASTContext().getSourceManager(); 273 274 for (ConstString path_component : module.path) { 275 clang_path.push_back(std::make_pair( 276 &m_compiler_instance->getASTContext().Idents.get( 277 path_component.GetStringRef()), 278 source_manager.getLocForStartOfFile(source_manager.getMainFileID()) 279 .getLocWithOffset(m_source_location_index++))); 280 } 281 } 282 283 StoringDiagnosticConsumer *diagnostic_consumer = 284 static_cast<StoringDiagnosticConsumer *>( 285 m_compiler_instance->getDiagnostics().getClient()); 286 287 diagnostic_consumer->ClearDiagnostics(); 288 289 clang::Module *top_level_module = DoGetModule(clang_path.front(), false); 290 291 if (!top_level_module) { 292 diagnostic_consumer->DumpDiagnostics(error_stream); 293 error_stream.Printf("error: Couldn't load top-level module %s\n", 294 module.path.front().AsCString()); 295 return false; 296 } 297 298 clang::Module *submodule = top_level_module; 299 300 for (auto &component : llvm::ArrayRef<ConstString>(module.path).drop_front()) { 301 submodule = submodule->findSubmodule(component.GetStringRef()); 302 if (!submodule) { 303 diagnostic_consumer->DumpDiagnostics(error_stream); 304 error_stream.Printf("error: Couldn't load submodule %s\n", 305 component.GetCString()); 306 return false; 307 } 308 } 309 310 clang::Module *requested_module = DoGetModule(clang_path, true); 311 312 if (requested_module != nullptr) { 313 if (exported_modules) { 314 ReportModuleExports(*exported_modules, requested_module); 315 } 316 317 m_imported_modules[imported_module] = requested_module; 318 319 m_enabled = true; 320 321 return true; 322 } 323 324 return false; 325 } 326 327 bool ClangModulesDeclVendor::LanguageSupportsClangModules( 328 lldb::LanguageType language) { 329 switch (language) { 330 default: 331 return false; 332 case lldb::LanguageType::eLanguageTypeC: 333 case lldb::LanguageType::eLanguageTypeC11: 334 case lldb::LanguageType::eLanguageTypeC89: 335 case lldb::LanguageType::eLanguageTypeC99: 336 case lldb::LanguageType::eLanguageTypeC_plus_plus: 337 case lldb::LanguageType::eLanguageTypeC_plus_plus_03: 338 case lldb::LanguageType::eLanguageTypeC_plus_plus_11: 339 case lldb::LanguageType::eLanguageTypeC_plus_plus_14: 340 case lldb::LanguageType::eLanguageTypeObjC: 341 case lldb::LanguageType::eLanguageTypeObjC_plus_plus: 342 return true; 343 } 344 } 345 346 bool ClangModulesDeclVendorImpl::AddModulesForCompileUnit( 347 CompileUnit &cu, ClangModulesDeclVendor::ModuleVector &exported_modules, 348 Stream &error_stream) { 349 if (LanguageSupportsClangModules(cu.GetLanguage())) { 350 for (auto &imported_module : cu.GetImportedModules()) 351 if (!AddModule(imported_module, &exported_modules, error_stream)) 352 return false; 353 } 354 return true; 355 } 356 357 // ClangImporter::lookupValue 358 359 uint32_t 360 ClangModulesDeclVendorImpl::FindDecls(ConstString name, bool append, 361 uint32_t max_matches, 362 std::vector<clang::NamedDecl *> &decls) { 363 if (!m_enabled) { 364 return 0; 365 } 366 367 if (!append) 368 decls.clear(); 369 370 clang::IdentifierInfo &ident = 371 m_compiler_instance->getASTContext().Idents.get(name.GetStringRef()); 372 373 clang::LookupResult lookup_result( 374 m_compiler_instance->getSema(), clang::DeclarationName(&ident), 375 clang::SourceLocation(), clang::Sema::LookupOrdinaryName); 376 377 m_compiler_instance->getSema().LookupName( 378 lookup_result, 379 m_compiler_instance->getSema().getScopeForContext( 380 m_compiler_instance->getASTContext().getTranslationUnitDecl())); 381 382 uint32_t num_matches = 0; 383 384 for (clang::NamedDecl *named_decl : lookup_result) { 385 if (num_matches >= max_matches) 386 return num_matches; 387 388 decls.push_back(named_decl); 389 ++num_matches; 390 } 391 392 return num_matches; 393 } 394 395 void ClangModulesDeclVendorImpl::ForEachMacro( 396 const ClangModulesDeclVendor::ModuleVector &modules, 397 std::function<bool(const std::string &)> handler) { 398 if (!m_enabled) { 399 return; 400 } 401 402 typedef std::map<ModuleID, ssize_t> ModulePriorityMap; 403 ModulePriorityMap module_priorities; 404 405 ssize_t priority = 0; 406 407 for (ModuleID module : modules) { 408 module_priorities[module] = priority++; 409 } 410 411 if (m_compiler_instance->getPreprocessor().getExternalSource()) { 412 m_compiler_instance->getPreprocessor() 413 .getExternalSource() 414 ->ReadDefinedMacros(); 415 } 416 417 for (clang::Preprocessor::macro_iterator 418 mi = m_compiler_instance->getPreprocessor().macro_begin(), 419 me = m_compiler_instance->getPreprocessor().macro_end(); 420 mi != me; ++mi) { 421 const clang::IdentifierInfo *ii = nullptr; 422 423 { 424 if (clang::IdentifierInfoLookup *lookup = 425 m_compiler_instance->getPreprocessor() 426 .getIdentifierTable() 427 .getExternalIdentifierLookup()) { 428 lookup->get(mi->first->getName()); 429 } 430 if (!ii) { 431 ii = mi->first; 432 } 433 } 434 435 ssize_t found_priority = -1; 436 clang::MacroInfo *macro_info = nullptr; 437 438 for (clang::ModuleMacro *module_macro : 439 m_compiler_instance->getPreprocessor().getLeafModuleMacros(ii)) { 440 clang::Module *module = module_macro->getOwningModule(); 441 442 { 443 ModulePriorityMap::iterator pi = 444 module_priorities.find(reinterpret_cast<ModuleID>(module)); 445 446 if (pi != module_priorities.end() && pi->second > found_priority) { 447 macro_info = module_macro->getMacroInfo(); 448 found_priority = pi->second; 449 } 450 } 451 452 clang::Module *top_level_module = module->getTopLevelModule(); 453 454 if (top_level_module != module) { 455 ModulePriorityMap::iterator pi = module_priorities.find( 456 reinterpret_cast<ModuleID>(top_level_module)); 457 458 if ((pi != module_priorities.end()) && pi->second > found_priority) { 459 macro_info = module_macro->getMacroInfo(); 460 found_priority = pi->second; 461 } 462 } 463 } 464 465 if (macro_info) { 466 std::string macro_expansion = "#define "; 467 macro_expansion.append(mi->first->getName().str()); 468 469 { 470 if (macro_info->isFunctionLike()) { 471 macro_expansion.append("("); 472 473 bool first_arg = true; 474 475 for (auto pi = macro_info->param_begin(), 476 pe = macro_info->param_end(); 477 pi != pe; ++pi) { 478 if (!first_arg) { 479 macro_expansion.append(", "); 480 } else { 481 first_arg = false; 482 } 483 484 macro_expansion.append((*pi)->getName().str()); 485 } 486 487 if (macro_info->isC99Varargs()) { 488 if (first_arg) { 489 macro_expansion.append("..."); 490 } else { 491 macro_expansion.append(", ..."); 492 } 493 } else if (macro_info->isGNUVarargs()) { 494 macro_expansion.append("..."); 495 } 496 497 macro_expansion.append(")"); 498 } 499 500 macro_expansion.append(" "); 501 502 bool first_token = true; 503 504 for (clang::MacroInfo::tokens_iterator ti = macro_info->tokens_begin(), 505 te = macro_info->tokens_end(); 506 ti != te; ++ti) { 507 if (!first_token) { 508 macro_expansion.append(" "); 509 } else { 510 first_token = false; 511 } 512 513 if (ti->isLiteral()) { 514 if (const char *literal_data = ti->getLiteralData()) { 515 std::string token_str(literal_data, ti->getLength()); 516 macro_expansion.append(token_str); 517 } else { 518 bool invalid = false; 519 const char *literal_source = 520 m_compiler_instance->getSourceManager().getCharacterData( 521 ti->getLocation(), &invalid); 522 523 if (invalid) { 524 lldbassert(0 && "Unhandled token kind"); 525 macro_expansion.append("<unknown literal value>"); 526 } else { 527 macro_expansion.append( 528 std::string(literal_source, ti->getLength())); 529 } 530 } 531 } else if (const char *punctuator_spelling = 532 clang::tok::getPunctuatorSpelling(ti->getKind())) { 533 macro_expansion.append(punctuator_spelling); 534 } else if (const char *keyword_spelling = 535 clang::tok::getKeywordSpelling(ti->getKind())) { 536 macro_expansion.append(keyword_spelling); 537 } else { 538 switch (ti->getKind()) { 539 case clang::tok::TokenKind::identifier: 540 macro_expansion.append(ti->getIdentifierInfo()->getName().str()); 541 break; 542 case clang::tok::TokenKind::raw_identifier: 543 macro_expansion.append(ti->getRawIdentifier().str()); 544 break; 545 default: 546 macro_expansion.append(ti->getName()); 547 break; 548 } 549 } 550 } 551 552 if (handler(macro_expansion)) { 553 return; 554 } 555 } 556 } 557 } 558 } 559 560 clang::ModuleLoadResult 561 ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path, 562 bool make_visible) { 563 clang::Module::NameVisibilityKind visibility = 564 make_visible ? clang::Module::AllVisible : clang::Module::Hidden; 565 566 const bool is_inclusion_directive = false; 567 568 return m_compiler_instance->loadModule(path.front().second, path, visibility, 569 is_inclusion_directive); 570 } 571 572 clang::ExternalASTMerger::ImporterSource 573 ClangModulesDeclVendorImpl::GetImporterSource() { 574 return clang::ExternalASTMerger::ImporterSource( 575 m_compiler_instance->getASTContext(), 576 m_compiler_instance->getFileManager(), m_origin_map); 577 } 578 579 static const char *ModuleImportBufferName = "LLDBModulesMemoryBuffer"; 580 581 lldb_private::ClangModulesDeclVendor * 582 ClangModulesDeclVendor::Create(Target &target) { 583 // FIXME we should insure programmatically that the expression parser's 584 // compiler and the modules runtime's 585 // compiler are both initialized in the same way – preferably by the same 586 // code. 587 588 if (!target.GetPlatform()->SupportsModules()) 589 return nullptr; 590 591 const ArchSpec &arch = target.GetArchitecture(); 592 593 std::vector<std::string> compiler_invocation_arguments = { 594 "clang", 595 "-fmodules", 596 "-fimplicit-module-maps", 597 "-fcxx-modules", 598 "-fsyntax-only", 599 "-femit-all-decls", 600 "-target", 601 arch.GetTriple().str(), 602 "-fmodules-validate-system-headers", 603 "-Werror=non-modular-include-in-framework-module"}; 604 605 target.GetPlatform()->AddClangModuleCompilationOptions( 606 &target, compiler_invocation_arguments); 607 608 compiler_invocation_arguments.push_back(ModuleImportBufferName); 609 610 // Add additional search paths with { "-I", path } or { "-F", path } here. 611 612 { 613 llvm::SmallString<128> path; 614 auto props = ModuleList::GetGlobalModuleListProperties(); 615 props.GetClangModulesCachePath().GetPath(path); 616 std::string module_cache_argument("-fmodules-cache-path="); 617 module_cache_argument.append(path.str()); 618 compiler_invocation_arguments.push_back(module_cache_argument); 619 } 620 621 FileSpecList module_search_paths = target.GetClangModuleSearchPaths(); 622 623 for (size_t spi = 0, spe = module_search_paths.GetSize(); spi < spe; ++spi) { 624 const FileSpec &search_path = module_search_paths.GetFileSpecAtIndex(spi); 625 626 std::string search_path_argument = "-I"; 627 search_path_argument.append(search_path.GetPath()); 628 629 compiler_invocation_arguments.push_back(search_path_argument); 630 } 631 632 { 633 FileSpec clang_resource_dir = GetClangResourceDir(); 634 635 if (FileSystem::Instance().IsDirectory(clang_resource_dir.GetPath())) { 636 compiler_invocation_arguments.push_back("-resource-dir"); 637 compiler_invocation_arguments.push_back(clang_resource_dir.GetPath()); 638 } 639 } 640 641 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine = 642 clang::CompilerInstance::createDiagnostics(new clang::DiagnosticOptions, 643 new StoringDiagnosticConsumer); 644 645 std::vector<const char *> compiler_invocation_argument_cstrs; 646 compiler_invocation_argument_cstrs.reserve( 647 compiler_invocation_arguments.size()); 648 for (const std::string &arg : compiler_invocation_arguments) 649 compiler_invocation_argument_cstrs.push_back(arg.c_str()); 650 651 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 652 LLDB_LOG(log, "ClangModulesDeclVendor's compiler flags {0:$[ ]}", 653 llvm::make_range(compiler_invocation_arguments.begin(), 654 compiler_invocation_arguments.end())); 655 656 std::shared_ptr<clang::CompilerInvocation> invocation = 657 clang::createInvocationFromCommandLine(compiler_invocation_argument_cstrs, 658 diagnostics_engine); 659 660 if (!invocation) 661 return nullptr; 662 663 std::unique_ptr<llvm::MemoryBuffer> source_buffer = 664 llvm::MemoryBuffer::getMemBuffer( 665 "extern int __lldb __attribute__((unavailable));", 666 ModuleImportBufferName); 667 668 invocation->getPreprocessorOpts().addRemappedFile(ModuleImportBufferName, 669 source_buffer.release()); 670 671 std::unique_ptr<clang::CompilerInstance> instance( 672 new clang::CompilerInstance); 673 674 // When capturing a reproducer, hook up the file collector with clang to 675 // collector modules and headers. 676 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { 677 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>(); 678 instance->setModuleDepCollector( 679 std::make_shared<ModuleDependencyCollectorAdaptor>( 680 fp.GetFileCollector())); 681 clang::DependencyOutputOptions &opts = instance->getDependencyOutputOpts(); 682 opts.IncludeSystemHeaders = true; 683 opts.IncludeModuleFiles = true; 684 } 685 686 // Make sure clang uses the same VFS as LLDB. 687 instance->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); 688 instance->setDiagnostics(diagnostics_engine.get()); 689 instance->setInvocation(invocation); 690 691 std::unique_ptr<clang::FrontendAction> action(new clang::SyntaxOnlyAction); 692 693 instance->setTarget(clang::TargetInfo::CreateTargetInfo( 694 *diagnostics_engine, instance->getInvocation().TargetOpts)); 695 696 if (!instance->hasTarget()) 697 return nullptr; 698 699 instance->getTarget().adjust(instance->getLangOpts()); 700 701 if (!action->BeginSourceFile(*instance, 702 instance->getFrontendOpts().Inputs[0])) 703 return nullptr; 704 705 instance->getPreprocessor().enableIncrementalProcessing(); 706 707 instance->createModuleManager(); 708 709 instance->createSema(action->getTranslationUnitKind(), nullptr); 710 711 const bool skipFunctionBodies = false; 712 std::unique_ptr<clang::Parser> parser(new clang::Parser( 713 instance->getPreprocessor(), instance->getSema(), skipFunctionBodies)); 714 715 instance->getPreprocessor().EnterMainSourceFile(); 716 parser->Initialize(); 717 718 clang::Parser::DeclGroupPtrTy parsed; 719 720 while (!parser->ParseTopLevelDecl(parsed)) 721 ; 722 723 return new ClangModulesDeclVendorImpl(std::move(diagnostics_engine), 724 std::move(invocation), 725 std::move(instance), std::move(parser)); 726 } 727