1 //===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // ASTUnit Implementation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Frontend/ASTUnit.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/DeclVisitor.h" 18 #include "clang/AST/StmtVisitor.h" 19 #include "clang/AST/TypeOrdering.h" 20 #include "clang/Basic/Diagnostic.h" 21 #include "clang/Basic/MemoryBufferCache.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "clang/Basic/TargetOptions.h" 24 #include "clang/Basic/VirtualFileSystem.h" 25 #include "clang/Frontend/CompilerInstance.h" 26 #include "clang/Frontend/FrontendActions.h" 27 #include "clang/Frontend/FrontendDiagnostic.h" 28 #include "clang/Frontend/FrontendOptions.h" 29 #include "clang/Frontend/MultiplexConsumer.h" 30 #include "clang/Frontend/Utils.h" 31 #include "clang/Lex/HeaderSearch.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Lex/PreprocessorOptions.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Serialization/ASTReader.h" 36 #include "clang/Serialization/ASTWriter.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/ADT/StringSet.h" 40 #include "llvm/Support/CrashRecoveryContext.h" 41 #include "llvm/Support/Host.h" 42 #include "llvm/Support/MemoryBuffer.h" 43 #include "llvm/Support/Mutex.h" 44 #include "llvm/Support/MutexGuard.h" 45 #include "llvm/Support/Timer.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <atomic> 48 #include <cstdio> 49 #include <cstdlib> 50 51 using namespace clang; 52 53 using llvm::TimeRecord; 54 55 namespace { 56 class SimpleTimer { 57 bool WantTiming; 58 TimeRecord Start; 59 std::string Output; 60 61 public: 62 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) { 63 if (WantTiming) 64 Start = TimeRecord::getCurrentTime(); 65 } 66 67 void setOutput(const Twine &Output) { 68 if (WantTiming) 69 this->Output = Output.str(); 70 } 71 72 ~SimpleTimer() { 73 if (WantTiming) { 74 TimeRecord Elapsed = TimeRecord::getCurrentTime(); 75 Elapsed -= Start; 76 llvm::errs() << Output << ':'; 77 Elapsed.print(Elapsed, llvm::errs()); 78 llvm::errs() << '\n'; 79 } 80 } 81 }; 82 83 template <class T> 84 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) { 85 if (!Val) 86 return nullptr; 87 return std::move(*Val); 88 } 89 90 template <class T> 91 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) { 92 if (!Val) 93 return false; 94 Output = std::move(*Val); 95 return true; 96 } 97 98 /// \brief Get a source buffer for \p MainFilePath, handling all file-to-file 99 /// and file-to-buffer remappings inside \p Invocation. 100 static std::unique_ptr<llvm::MemoryBuffer> 101 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, 102 vfs::FileSystem *VFS, 103 StringRef FilePath) { 104 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts(); 105 106 // Try to determine if the main file has been remapped, either from the 107 // command line (to another file) or directly through the compiler 108 // invocation (to a memory buffer). 109 llvm::MemoryBuffer *Buffer = nullptr; 110 std::unique_ptr<llvm::MemoryBuffer> BufferOwner; 111 auto FileStatus = VFS->status(FilePath); 112 if (FileStatus) { 113 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID(); 114 115 // Check whether there is a file-file remapping of the main file 116 for (const auto &RF : PreprocessorOpts.RemappedFiles) { 117 std::string MPath(RF.first); 118 auto MPathStatus = VFS->status(MPath); 119 if (MPathStatus) { 120 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID(); 121 if (MainFileID == MID) { 122 // We found a remapping. Try to load the resulting, remapped source. 123 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second)); 124 if (!BufferOwner) 125 return nullptr; 126 } 127 } 128 } 129 130 // Check whether there is a file-buffer remapping. It supercedes the 131 // file-file remapping. 132 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) { 133 std::string MPath(RB.first); 134 auto MPathStatus = VFS->status(MPath); 135 if (MPathStatus) { 136 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID(); 137 if (MainFileID == MID) { 138 // We found a remapping. 139 BufferOwner.reset(); 140 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second); 141 } 142 } 143 } 144 } 145 146 // If the main source file was not remapped, load it now. 147 if (!Buffer && !BufferOwner) { 148 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath)); 149 if (!BufferOwner) 150 return nullptr; 151 } 152 153 if (BufferOwner) 154 return BufferOwner; 155 if (!Buffer) 156 return nullptr; 157 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath); 158 } 159 } 160 161 struct ASTUnit::ASTWriterData { 162 SmallString<128> Buffer; 163 llvm::BitstreamWriter Stream; 164 ASTWriter Writer; 165 166 ASTWriterData(MemoryBufferCache &PCMCache) 167 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {} 168 }; 169 170 void ASTUnit::clearFileLevelDecls() { 171 llvm::DeleteContainerSeconds(FileDecls); 172 } 173 174 /// \brief After failing to build a precompiled preamble (due to 175 /// errors in the source that occurs in the preamble), the number of 176 /// reparses during which we'll skip even trying to precompile the 177 /// preamble. 178 const unsigned DefaultPreambleRebuildInterval = 5; 179 180 /// \brief Tracks the number of ASTUnit objects that are currently active. 181 /// 182 /// Used for debugging purposes only. 183 static std::atomic<unsigned> ActiveASTUnitObjects; 184 185 ASTUnit::ASTUnit(bool _MainFileIsAST) 186 : Reader(nullptr), HadModuleLoaderFatalFailure(false), 187 OnlyLocalDecls(false), CaptureDiagnostics(false), 188 MainFileIsAST(_MainFileIsAST), 189 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")), 190 OwnsRemappedFileBuffers(true), 191 NumStoredDiagnosticsFromDriver(0), 192 PreambleRebuildCounter(0), 193 NumWarningsInPreamble(0), 194 ShouldCacheCodeCompletionResults(false), 195 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false), 196 CompletionCacheTopLevelHashValue(0), 197 PreambleTopLevelHashValue(0), 198 CurrentTopLevelHashValue(0), 199 UnsafeToFree(false) { 200 if (getenv("LIBCLANG_OBJTRACKING")) 201 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects); 202 } 203 204 ASTUnit::~ASTUnit() { 205 // If we loaded from an AST file, balance out the BeginSourceFile call. 206 if (MainFileIsAST && getDiagnostics().getClient()) { 207 getDiagnostics().getClient()->EndSourceFile(); 208 } 209 210 clearFileLevelDecls(); 211 212 // Free the buffers associated with remapped files. We are required to 213 // perform this operation here because we explicitly request that the 214 // compiler instance *not* free these buffers for each invocation of the 215 // parser. 216 if (Invocation && OwnsRemappedFileBuffers) { 217 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 218 for (const auto &RB : PPOpts.RemappedFileBuffers) 219 delete RB.second; 220 } 221 222 ClearCachedCompletionResults(); 223 224 if (getenv("LIBCLANG_OBJTRACKING")) 225 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects); 226 } 227 228 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) { 229 this->PP = std::move(PP); 230 } 231 232 /// \brief Determine the set of code-completion contexts in which this 233 /// declaration should be shown. 234 static unsigned getDeclShowContexts(const NamedDecl *ND, 235 const LangOptions &LangOpts, 236 bool &IsNestedNameSpecifier) { 237 IsNestedNameSpecifier = false; 238 239 if (isa<UsingShadowDecl>(ND)) 240 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl()); 241 if (!ND) 242 return 0; 243 244 uint64_t Contexts = 0; 245 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) || 246 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) || 247 isa<TypeAliasTemplateDecl>(ND)) { 248 // Types can appear in these contexts. 249 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND)) 250 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel) 251 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 252 | (1LL << CodeCompletionContext::CCC_ClassStructUnion) 253 | (1LL << CodeCompletionContext::CCC_Statement) 254 | (1LL << CodeCompletionContext::CCC_Type) 255 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); 256 257 // In C++, types can appear in expressions contexts (for functional casts). 258 if (LangOpts.CPlusPlus) 259 Contexts |= (1LL << CodeCompletionContext::CCC_Expression); 260 261 // In Objective-C, message sends can send interfaces. In Objective-C++, 262 // all types are available due to functional casts. 263 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND)) 264 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver); 265 266 // In Objective-C, you can only be a subclass of another Objective-C class 267 if (isa<ObjCInterfaceDecl>(ND)) 268 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName); 269 270 // Deal with tag names. 271 if (isa<EnumDecl>(ND)) { 272 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag); 273 274 // Part of the nested-name-specifier in C++0x. 275 if (LangOpts.CPlusPlus11) 276 IsNestedNameSpecifier = true; 277 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) { 278 if (Record->isUnion()) 279 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag); 280 else 281 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag); 282 283 if (LangOpts.CPlusPlus) 284 IsNestedNameSpecifier = true; 285 } else if (isa<ClassTemplateDecl>(ND)) 286 IsNestedNameSpecifier = true; 287 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 288 // Values can appear in these contexts. 289 Contexts = (1LL << CodeCompletionContext::CCC_Statement) 290 | (1LL << CodeCompletionContext::CCC_Expression) 291 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) 292 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver); 293 } else if (isa<ObjCProtocolDecl>(ND)) { 294 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName); 295 } else if (isa<ObjCCategoryDecl>(ND)) { 296 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName); 297 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) { 298 Contexts = (1LL << CodeCompletionContext::CCC_Namespace); 299 300 // Part of the nested-name-specifier. 301 IsNestedNameSpecifier = true; 302 } 303 304 return Contexts; 305 } 306 307 void ASTUnit::CacheCodeCompletionResults() { 308 if (!TheSema) 309 return; 310 311 SimpleTimer Timer(WantTiming); 312 Timer.setOutput("Cache global code completions for " + getMainFileName()); 313 314 // Clear out the previous results. 315 ClearCachedCompletionResults(); 316 317 // Gather the set of global code completions. 318 typedef CodeCompletionResult Result; 319 SmallVector<Result, 8> Results; 320 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>(); 321 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator); 322 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, 323 CCTUInfo, Results); 324 325 // Translate global code completions into cached completions. 326 llvm::DenseMap<CanQualType, unsigned> CompletionTypes; 327 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel); 328 329 for (Result &R : Results) { 330 switch (R.Kind) { 331 case Result::RK_Declaration: { 332 bool IsNestedNameSpecifier = false; 333 CachedCodeCompletionResult CachedResult; 334 CachedResult.Completion = R.CreateCodeCompletionString( 335 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, 336 IncludeBriefCommentsInCodeCompletion); 337 CachedResult.ShowInContexts = getDeclShowContexts( 338 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier); 339 CachedResult.Priority = R.Priority; 340 CachedResult.Kind = R.CursorKind; 341 CachedResult.Availability = R.Availability; 342 343 // Keep track of the type of this completion in an ASTContext-agnostic 344 // way. 345 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration); 346 if (UsageType.isNull()) { 347 CachedResult.TypeClass = STC_Void; 348 CachedResult.Type = 0; 349 } else { 350 CanQualType CanUsageType 351 = Ctx->getCanonicalType(UsageType.getUnqualifiedType()); 352 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType); 353 354 // Determine whether we have already seen this type. If so, we save 355 // ourselves the work of formatting the type string by using the 356 // temporary, CanQualType-based hash table to find the associated value. 357 unsigned &TypeValue = CompletionTypes[CanUsageType]; 358 if (TypeValue == 0) { 359 TypeValue = CompletionTypes.size(); 360 CachedCompletionTypes[QualType(CanUsageType).getAsString()] 361 = TypeValue; 362 } 363 364 CachedResult.Type = TypeValue; 365 } 366 367 CachedCompletionResults.push_back(CachedResult); 368 369 /// Handle nested-name-specifiers in C++. 370 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier && 371 !R.StartsNestedNameSpecifier) { 372 // The contexts in which a nested-name-specifier can appear in C++. 373 uint64_t NNSContexts 374 = (1LL << CodeCompletionContext::CCC_TopLevel) 375 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 376 | (1LL << CodeCompletionContext::CCC_ClassStructUnion) 377 | (1LL << CodeCompletionContext::CCC_Statement) 378 | (1LL << CodeCompletionContext::CCC_Expression) 379 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) 380 | (1LL << CodeCompletionContext::CCC_EnumTag) 381 | (1LL << CodeCompletionContext::CCC_UnionTag) 382 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag) 383 | (1LL << CodeCompletionContext::CCC_Type) 384 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName) 385 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); 386 387 if (isa<NamespaceDecl>(R.Declaration) || 388 isa<NamespaceAliasDecl>(R.Declaration)) 389 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace); 390 391 if (unsigned RemainingContexts 392 = NNSContexts & ~CachedResult.ShowInContexts) { 393 // If there any contexts where this completion can be a 394 // nested-name-specifier but isn't already an option, create a 395 // nested-name-specifier completion. 396 R.StartsNestedNameSpecifier = true; 397 CachedResult.Completion = R.CreateCodeCompletionString( 398 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, 399 IncludeBriefCommentsInCodeCompletion); 400 CachedResult.ShowInContexts = RemainingContexts; 401 CachedResult.Priority = CCP_NestedNameSpecifier; 402 CachedResult.TypeClass = STC_Void; 403 CachedResult.Type = 0; 404 CachedCompletionResults.push_back(CachedResult); 405 } 406 } 407 break; 408 } 409 410 case Result::RK_Keyword: 411 case Result::RK_Pattern: 412 // Ignore keywords and patterns; we don't care, since they are so 413 // easily regenerated. 414 break; 415 416 case Result::RK_Macro: { 417 CachedCodeCompletionResult CachedResult; 418 CachedResult.Completion = R.CreateCodeCompletionString( 419 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, 420 IncludeBriefCommentsInCodeCompletion); 421 CachedResult.ShowInContexts 422 = (1LL << CodeCompletionContext::CCC_TopLevel) 423 | (1LL << CodeCompletionContext::CCC_ObjCInterface) 424 | (1LL << CodeCompletionContext::CCC_ObjCImplementation) 425 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 426 | (1LL << CodeCompletionContext::CCC_ClassStructUnion) 427 | (1LL << CodeCompletionContext::CCC_Statement) 428 | (1LL << CodeCompletionContext::CCC_Expression) 429 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) 430 | (1LL << CodeCompletionContext::CCC_MacroNameUse) 431 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression) 432 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) 433 | (1LL << CodeCompletionContext::CCC_OtherWithMacros); 434 435 CachedResult.Priority = R.Priority; 436 CachedResult.Kind = R.CursorKind; 437 CachedResult.Availability = R.Availability; 438 CachedResult.TypeClass = STC_Void; 439 CachedResult.Type = 0; 440 CachedCompletionResults.push_back(CachedResult); 441 break; 442 } 443 } 444 } 445 446 // Save the current top-level hash value. 447 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue; 448 } 449 450 void ASTUnit::ClearCachedCompletionResults() { 451 CachedCompletionResults.clear(); 452 CachedCompletionTypes.clear(); 453 CachedCompletionAllocator = nullptr; 454 } 455 456 namespace { 457 458 /// \brief Gathers information from ASTReader that will be used to initialize 459 /// a Preprocessor. 460 class ASTInfoCollector : public ASTReaderListener { 461 Preprocessor &PP; 462 ASTContext *Context; 463 HeaderSearchOptions &HSOpts; 464 PreprocessorOptions &PPOpts; 465 LangOptions &LangOpt; 466 std::shared_ptr<TargetOptions> &TargetOpts; 467 IntrusiveRefCntPtr<TargetInfo> &Target; 468 unsigned &Counter; 469 470 bool InitializedLanguage; 471 public: 472 ASTInfoCollector(Preprocessor &PP, ASTContext *Context, 473 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts, 474 LangOptions &LangOpt, 475 std::shared_ptr<TargetOptions> &TargetOpts, 476 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter) 477 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts), 478 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target), 479 Counter(Counter), InitializedLanguage(false) {} 480 481 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 482 bool AllowCompatibleDifferences) override { 483 if (InitializedLanguage) 484 return false; 485 486 LangOpt = LangOpts; 487 InitializedLanguage = true; 488 489 updated(); 490 return false; 491 } 492 493 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 494 StringRef SpecificModuleCachePath, 495 bool Complain) override { 496 this->HSOpts = HSOpts; 497 return false; 498 } 499 500 virtual bool 501 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, 502 std::string &SuggestedPredefines) override { 503 this->PPOpts = PPOpts; 504 return false; 505 } 506 507 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 508 bool AllowCompatibleDifferences) override { 509 // If we've already initialized the target, don't do it again. 510 if (Target) 511 return false; 512 513 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts); 514 Target = 515 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts); 516 517 updated(); 518 return false; 519 } 520 521 void ReadCounter(const serialization::ModuleFile &M, 522 unsigned Value) override { 523 Counter = Value; 524 } 525 526 private: 527 void updated() { 528 if (!Target || !InitializedLanguage) 529 return; 530 531 // Inform the target of the language options. 532 // 533 // FIXME: We shouldn't need to do this, the target should be immutable once 534 // created. This complexity should be lifted elsewhere. 535 Target->adjust(LangOpt); 536 537 // Initialize the preprocessor. 538 PP.Initialize(*Target); 539 540 if (!Context) 541 return; 542 543 // Initialize the ASTContext 544 Context->InitBuiltinTypes(*Target); 545 546 // Adjust printing policy based on language options. 547 Context->setPrintingPolicy(PrintingPolicy(LangOpt)); 548 549 // We didn't have access to the comment options when the ASTContext was 550 // constructed, so register them now. 551 Context->getCommentCommandTraits().registerCommentOptions( 552 LangOpt.CommentOpts); 553 } 554 }; 555 556 /// \brief Diagnostic consumer that saves each diagnostic it is given. 557 class StoredDiagnosticConsumer : public DiagnosticConsumer { 558 SmallVectorImpl<StoredDiagnostic> *StoredDiags; 559 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags; 560 const LangOptions *LangOpts; 561 SourceManager *SourceMgr; 562 563 public: 564 StoredDiagnosticConsumer( 565 SmallVectorImpl<StoredDiagnostic> *StoredDiags, 566 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags) 567 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags), 568 LangOpts(nullptr), SourceMgr(nullptr) { 569 assert((StoredDiags || StandaloneDiags) && 570 "No output collections were passed to StoredDiagnosticConsumer."); 571 } 572 573 void BeginSourceFile(const LangOptions &LangOpts, 574 const Preprocessor *PP = nullptr) override { 575 this->LangOpts = &LangOpts; 576 if (PP) 577 SourceMgr = &PP->getSourceManager(); 578 } 579 580 void HandleDiagnostic(DiagnosticsEngine::Level Level, 581 const Diagnostic &Info) override; 582 }; 583 584 /// \brief RAII object that optionally captures diagnostics, if 585 /// there is no diagnostic client to capture them already. 586 class CaptureDroppedDiagnostics { 587 DiagnosticsEngine &Diags; 588 StoredDiagnosticConsumer Client; 589 DiagnosticConsumer *PreviousClient; 590 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient; 591 592 public: 593 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags, 594 SmallVectorImpl<StoredDiagnostic> *StoredDiags, 595 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags) 596 : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(nullptr) 597 { 598 if (RequestCapture || Diags.getClient() == nullptr) { 599 OwningPreviousClient = Diags.takeClient(); 600 PreviousClient = Diags.getClient(); 601 Diags.setClient(&Client, false); 602 } 603 } 604 605 ~CaptureDroppedDiagnostics() { 606 if (Diags.getClient() == &Client) 607 Diags.setClient(PreviousClient, !!OwningPreviousClient.release()); 608 } 609 }; 610 611 } // anonymous namespace 612 613 static ASTUnit::StandaloneDiagnostic 614 makeStandaloneDiagnostic(const LangOptions &LangOpts, 615 const StoredDiagnostic &InDiag); 616 617 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level, 618 const Diagnostic &Info) { 619 // Default implementation (Warnings/errors count). 620 DiagnosticConsumer::HandleDiagnostic(Level, Info); 621 622 // Only record the diagnostic if it's part of the source manager we know 623 // about. This effectively drops diagnostics from modules we're building. 624 // FIXME: In the long run, ee don't want to drop source managers from modules. 625 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) { 626 StoredDiagnostic *ResultDiag = nullptr; 627 if (StoredDiags) { 628 StoredDiags->emplace_back(Level, Info); 629 ResultDiag = &StoredDiags->back(); 630 } 631 632 if (StandaloneDiags) { 633 llvm::Optional<StoredDiagnostic> StoredDiag = llvm::None; 634 if (!ResultDiag) { 635 StoredDiag.emplace(Level, Info); 636 ResultDiag = StoredDiag.getPointer(); 637 } 638 StandaloneDiags->push_back( 639 makeStandaloneDiagnostic(*LangOpts, *ResultDiag)); 640 } 641 } 642 } 643 644 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const { 645 return Reader; 646 } 647 648 ASTMutationListener *ASTUnit::getASTMutationListener() { 649 if (WriterData) 650 return &WriterData->Writer; 651 return nullptr; 652 } 653 654 ASTDeserializationListener *ASTUnit::getDeserializationListener() { 655 if (WriterData) 656 return &WriterData->Writer; 657 return nullptr; 658 } 659 660 std::unique_ptr<llvm::MemoryBuffer> 661 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) { 662 assert(FileMgr); 663 auto Buffer = FileMgr->getBufferForFile(Filename); 664 if (Buffer) 665 return std::move(*Buffer); 666 if (ErrorStr) 667 *ErrorStr = Buffer.getError().message(); 668 return nullptr; 669 } 670 671 /// \brief Configure the diagnostics object for use with ASTUnit. 672 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 673 ASTUnit &AST, bool CaptureDiagnostics) { 674 assert(Diags.get() && "no DiagnosticsEngine was provided"); 675 if (CaptureDiagnostics) 676 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr)); 677 } 678 679 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( 680 const std::string &Filename, const PCHContainerReader &PCHContainerRdr, 681 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 682 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo, 683 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles, 684 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors, 685 bool UserFilesAreVolatile) { 686 std::unique_ptr<ASTUnit> AST(new ASTUnit(true)); 687 688 // Recover resources if we crash before exiting this method. 689 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 690 ASTUnitCleanup(AST.get()); 691 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 692 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 693 DiagCleanup(Diags.get()); 694 695 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 696 697 AST->LangOpts = std::make_shared<LangOptions>(); 698 AST->OnlyLocalDecls = OnlyLocalDecls; 699 AST->CaptureDiagnostics = CaptureDiagnostics; 700 AST->Diagnostics = Diags; 701 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem(); 702 AST->FileMgr = new FileManager(FileSystemOpts, VFS); 703 AST->UserFilesAreVolatile = UserFilesAreVolatile; 704 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), 705 AST->getFileManager(), 706 UserFilesAreVolatile); 707 AST->PCMCache = new MemoryBufferCache; 708 AST->HSOpts = std::make_shared<HeaderSearchOptions>(); 709 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat(); 710 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts, 711 AST->getSourceManager(), 712 AST->getDiagnostics(), 713 AST->getLangOpts(), 714 /*Target=*/nullptr)); 715 AST->PPOpts = std::make_shared<PreprocessorOptions>(); 716 717 for (const auto &RemappedFile : RemappedFiles) 718 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second); 719 720 // Gather Info for preprocessor construction later on. 721 722 HeaderSearch &HeaderInfo = *AST->HeaderInfo; 723 unsigned Counter; 724 725 AST->PP = std::make_shared<Preprocessor>( 726 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts, 727 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader, 728 /*IILookup=*/nullptr, 729 /*OwnsHeaderSearch=*/false); 730 Preprocessor &PP = *AST->PP; 731 732 if (ToLoad >= LoadASTOnly) 733 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), 734 PP.getIdentifierTable(), PP.getSelectorTable(), 735 PP.getBuiltinInfo()); 736 737 bool disableValid = false; 738 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) 739 disableValid = true; 740 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { }, 741 /*isysroot=*/"", 742 /*DisableValidation=*/disableValid, 743 AllowPCHWithCompilerErrors); 744 745 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>( 746 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts, 747 AST->TargetOpts, AST->Target, Counter)); 748 749 // Attach the AST reader to the AST context as an external AST 750 // source, so that declarations will be deserialized from the 751 // AST file as needed. 752 // We need the external source to be set up before we read the AST, because 753 // eagerly-deserialized declarations may use it. 754 if (AST->Ctx) 755 AST->Ctx->setExternalSource(AST->Reader); 756 757 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile, 758 SourceLocation(), ASTReader::ARR_None)) { 759 case ASTReader::Success: 760 break; 761 762 case ASTReader::Failure: 763 case ASTReader::Missing: 764 case ASTReader::OutOfDate: 765 case ASTReader::VersionMismatch: 766 case ASTReader::ConfigurationMismatch: 767 case ASTReader::HadErrors: 768 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); 769 return nullptr; 770 } 771 772 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile(); 773 774 PP.setCounterValue(Counter); 775 776 // Create an AST consumer, even though it isn't used. 777 if (ToLoad >= LoadASTOnly) 778 AST->Consumer.reset(new ASTConsumer); 779 780 // Create a semantic analysis object and tell the AST reader about it. 781 if (ToLoad >= LoadEverything) { 782 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer)); 783 AST->TheSema->Initialize(); 784 AST->Reader->InitializeSema(*AST->TheSema); 785 } 786 787 // Tell the diagnostic client that we have started a source file. 788 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP); 789 790 return AST; 791 } 792 793 namespace { 794 795 /// \brief Add the given macro to the hash of all top-level entities. 796 void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) { 797 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash); 798 } 799 800 /// \brief Preprocessor callback class that updates a hash value with the names 801 /// of all macros that have been defined by the translation unit. 802 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks { 803 unsigned &Hash; 804 805 public: 806 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { } 807 808 void MacroDefined(const Token &MacroNameTok, 809 const MacroDirective *MD) override { 810 AddDefinedMacroToHash(MacroNameTok, Hash); 811 } 812 }; 813 814 /// \brief Add the given declaration to the hash of all top-level entities. 815 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) { 816 if (!D) 817 return; 818 819 DeclContext *DC = D->getDeclContext(); 820 if (!DC) 821 return; 822 823 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit())) 824 return; 825 826 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) { 827 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) { 828 // For an unscoped enum include the enumerators in the hash since they 829 // enter the top-level namespace. 830 if (!EnumD->isScoped()) { 831 for (const auto *EI : EnumD->enumerators()) { 832 if (EI->getIdentifier()) 833 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash); 834 } 835 } 836 } 837 838 if (ND->getIdentifier()) 839 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash); 840 else if (DeclarationName Name = ND->getDeclName()) { 841 std::string NameStr = Name.getAsString(); 842 Hash = llvm::HashString(NameStr, Hash); 843 } 844 return; 845 } 846 847 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) { 848 if (Module *Mod = ImportD->getImportedModule()) { 849 std::string ModName = Mod->getFullModuleName(); 850 Hash = llvm::HashString(ModName, Hash); 851 } 852 return; 853 } 854 } 855 856 class TopLevelDeclTrackerConsumer : public ASTConsumer { 857 ASTUnit &Unit; 858 unsigned &Hash; 859 860 public: 861 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash) 862 : Unit(_Unit), Hash(Hash) { 863 Hash = 0; 864 } 865 866 void handleTopLevelDecl(Decl *D) { 867 if (!D) 868 return; 869 870 // FIXME: Currently ObjC method declarations are incorrectly being 871 // reported as top-level declarations, even though their DeclContext 872 // is the containing ObjC @interface/@implementation. This is a 873 // fundamental problem in the parser right now. 874 if (isa<ObjCMethodDecl>(D)) 875 return; 876 877 AddTopLevelDeclarationToHash(D, Hash); 878 Unit.addTopLevelDecl(D); 879 880 handleFileLevelDecl(D); 881 } 882 883 void handleFileLevelDecl(Decl *D) { 884 Unit.addFileLevelDecl(D); 885 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) { 886 for (auto *I : NSD->decls()) 887 handleFileLevelDecl(I); 888 } 889 } 890 891 bool HandleTopLevelDecl(DeclGroupRef D) override { 892 for (Decl *TopLevelDecl : D) 893 handleTopLevelDecl(TopLevelDecl); 894 return true; 895 } 896 897 // We're not interested in "interesting" decls. 898 void HandleInterestingDecl(DeclGroupRef) override {} 899 900 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { 901 for (Decl *TopLevelDecl : D) 902 handleTopLevelDecl(TopLevelDecl); 903 } 904 905 ASTMutationListener *GetASTMutationListener() override { 906 return Unit.getASTMutationListener(); 907 } 908 909 ASTDeserializationListener *GetASTDeserializationListener() override { 910 return Unit.getDeserializationListener(); 911 } 912 }; 913 914 class TopLevelDeclTrackerAction : public ASTFrontendAction { 915 public: 916 ASTUnit &Unit; 917 918 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, 919 StringRef InFile) override { 920 CI.getPreprocessor().addPPCallbacks( 921 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>( 922 Unit.getCurrentTopLevelHashValue())); 923 return llvm::make_unique<TopLevelDeclTrackerConsumer>( 924 Unit, Unit.getCurrentTopLevelHashValue()); 925 } 926 927 public: 928 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} 929 930 bool hasCodeCompletionSupport() const override { return false; } 931 TranslationUnitKind getTranslationUnitKind() override { 932 return Unit.getTranslationUnitKind(); 933 } 934 }; 935 936 class ASTUnitPreambleCallbacks : public PreambleCallbacks { 937 public: 938 unsigned getHash() const { return Hash; } 939 940 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); } 941 942 std::vector<serialization::DeclID> takeTopLevelDeclIDs() { 943 return std::move(TopLevelDeclIDs); 944 } 945 946 void AfterPCHEmitted(ASTWriter &Writer) override { 947 TopLevelDeclIDs.reserve(TopLevelDecls.size()); 948 for (Decl *D : TopLevelDecls) { 949 // Invalid top-level decls may not have been serialized. 950 if (D->isInvalidDecl()) 951 continue; 952 TopLevelDeclIDs.push_back(Writer.getDeclID(D)); 953 } 954 } 955 956 void HandleTopLevelDecl(DeclGroupRef DG) override { 957 for (Decl *D : DG) { 958 // FIXME: Currently ObjC method declarations are incorrectly being 959 // reported as top-level declarations, even though their DeclContext 960 // is the containing ObjC @interface/@implementation. This is a 961 // fundamental problem in the parser right now. 962 if (isa<ObjCMethodDecl>(D)) 963 continue; 964 AddTopLevelDeclarationToHash(D, Hash); 965 TopLevelDecls.push_back(D); 966 } 967 } 968 969 void HandleMacroDefined(const Token &MacroNameTok, 970 const MacroDirective *MD) override { 971 AddDefinedMacroToHash(MacroNameTok, Hash); 972 } 973 974 private: 975 unsigned Hash = 0; 976 std::vector<Decl *> TopLevelDecls; 977 std::vector<serialization::DeclID> TopLevelDeclIDs; 978 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags; 979 }; 980 981 } // anonymous namespace 982 983 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) { 984 return StoredDiag.getLocation().isValid(); 985 } 986 987 static void 988 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) { 989 // Get rid of stored diagnostics except the ones from the driver which do not 990 // have a source location. 991 StoredDiags.erase( 992 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag), 993 StoredDiags.end()); 994 } 995 996 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> & 997 StoredDiagnostics, 998 SourceManager &SM) { 999 // The stored diagnostic has the old source manager in it; update 1000 // the locations to refer into the new source manager. Since we've 1001 // been careful to make sure that the source manager's state 1002 // before and after are identical, so that we can reuse the source 1003 // location itself. 1004 for (StoredDiagnostic &SD : StoredDiagnostics) { 1005 if (SD.getLocation().isValid()) { 1006 FullSourceLoc Loc(SD.getLocation(), SM); 1007 SD.setLocation(Loc); 1008 } 1009 } 1010 } 1011 1012 static IntrusiveRefCntPtr<vfs::FileSystem> createVFSOverlayForPreamblePCH( 1013 StringRef PCHFilename, 1014 IntrusiveRefCntPtr<vfs::FileSystem> RealFS, 1015 IntrusiveRefCntPtr<vfs::FileSystem> VFS) { 1016 // We want only the PCH file from the real filesystem to be available, 1017 // so we create an in-memory VFS with just that and overlay it on top. 1018 auto Buf = RealFS->getBufferForFile(PCHFilename); 1019 if (!Buf) 1020 return VFS; 1021 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> 1022 PCHFS(new vfs::InMemoryFileSystem()); 1023 PCHFS->addFile(PCHFilename, 0, std::move(*Buf)); 1024 IntrusiveRefCntPtr<vfs::OverlayFileSystem> 1025 Overlay(new vfs::OverlayFileSystem(VFS)); 1026 Overlay->pushOverlay(PCHFS); 1027 return Overlay; 1028 } 1029 1030 /// Parse the source file into a translation unit using the given compiler 1031 /// invocation, replacing the current translation unit. 1032 /// 1033 /// \returns True if a failure occurred that causes the ASTUnit not to 1034 /// contain any translation-unit information, false otherwise. 1035 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1036 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer, 1037 IntrusiveRefCntPtr<vfs::FileSystem> VFS) { 1038 if (!Invocation) 1039 return true; 1040 1041 // Create the compiler instance to use for building the AST. 1042 std::unique_ptr<CompilerInstance> Clang( 1043 new CompilerInstance(std::move(PCHContainerOps))); 1044 if (FileMgr && VFS) { 1045 assert(VFS == FileMgr->getVirtualFileSystem() && 1046 "VFS passed to Parse and VFS in FileMgr are different"); 1047 } else if (VFS) { 1048 Clang->setVirtualFileSystem(VFS); 1049 } 1050 1051 // Make sure we can access the PCH file even if we're using a VFS 1052 if (!VFS && FileMgr) 1053 VFS = FileMgr->getVirtualFileSystem(); 1054 IntrusiveRefCntPtr<vfs::FileSystem> RealFS = vfs::getRealFileSystem(); 1055 if (OverrideMainBuffer && VFS && RealFS && VFS != RealFS && 1056 !VFS->exists(Preamble->GetPCHPath())) { 1057 // We have a slight inconsistency here -- we're using the VFS to 1058 // read files, but the PCH was generated in the real file system. 1059 VFS = createVFSOverlayForPreamblePCH(Preamble->GetPCHPath(), RealFS, VFS); 1060 if (FileMgr) { 1061 FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS); 1062 Clang->setFileManager(FileMgr.get()); 1063 } 1064 else { 1065 Clang->setVirtualFileSystem(VFS); 1066 } 1067 } 1068 1069 // Recover resources if we crash before exiting this method. 1070 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 1071 CICleanup(Clang.get()); 1072 1073 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation)); 1074 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile(); 1075 1076 // Set up diagnostics, capturing any diagnostics that would 1077 // otherwise be dropped. 1078 Clang->setDiagnostics(&getDiagnostics()); 1079 1080 // Create the target instance. 1081 Clang->setTarget(TargetInfo::CreateTargetInfo( 1082 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 1083 if (!Clang->hasTarget()) 1084 return true; 1085 1086 // Inform the target of the language options. 1087 // 1088 // FIXME: We shouldn't need to do this, the target should be immutable once 1089 // created. This complexity should be lifted elsewhere. 1090 Clang->getTarget().adjust(Clang->getLangOpts()); 1091 1092 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1093 "Invocation must have exactly one source file!"); 1094 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 1095 InputKind::Source && 1096 "FIXME: AST inputs not yet supported here!"); 1097 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 1098 InputKind::LLVM_IR && 1099 "IR inputs not support here!"); 1100 1101 // Configure the various subsystems. 1102 LangOpts = Clang->getInvocation().LangOpts; 1103 FileSystemOpts = Clang->getFileSystemOpts(); 1104 if (!FileMgr) { 1105 Clang->createFileManager(); 1106 FileMgr = &Clang->getFileManager(); 1107 } 1108 1109 ResetForParse(); 1110 1111 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr, 1112 UserFilesAreVolatile); 1113 if (!OverrideMainBuffer) { 1114 checkAndRemoveNonDriverDiags(StoredDiagnostics); 1115 TopLevelDeclsInPreamble.clear(); 1116 } 1117 1118 // Create a file manager object to provide access to and cache the filesystem. 1119 Clang->setFileManager(&getFileManager()); 1120 1121 // Create the source manager. 1122 Clang->setSourceManager(&getSourceManager()); 1123 1124 // If the main file has been overridden due to the use of a preamble, 1125 // make that override happen and introduce the preamble. 1126 if (OverrideMainBuffer) { 1127 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null"); 1128 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get()); 1129 1130 // The stored diagnostic has the old source manager in it; update 1131 // the locations to refer into the new source manager. Since we've 1132 // been careful to make sure that the source manager's state 1133 // before and after are identical, so that we can reuse the source 1134 // location itself. 1135 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager()); 1136 1137 // Keep track of the override buffer; 1138 SavedMainFileBuffer = std::move(OverrideMainBuffer); 1139 } 1140 1141 std::unique_ptr<TopLevelDeclTrackerAction> Act( 1142 new TopLevelDeclTrackerAction(*this)); 1143 1144 // Recover resources if we crash before exiting this method. 1145 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> 1146 ActCleanup(Act.get()); 1147 1148 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) 1149 goto error; 1150 1151 if (SavedMainFileBuffer) 1152 TranslateStoredDiagnostics(getFileManager(), getSourceManager(), 1153 PreambleDiagnostics, StoredDiagnostics); 1154 else 1155 PreambleSrcLocCache.clear(); 1156 1157 if (!Act->Execute()) 1158 goto error; 1159 1160 transferASTDataFromCompilerInstance(*Clang); 1161 1162 Act->EndSourceFile(); 1163 1164 FailedParseDiagnostics.clear(); 1165 1166 return false; 1167 1168 error: 1169 // Remove the overridden buffer we used for the preamble. 1170 SavedMainFileBuffer = nullptr; 1171 1172 // Keep the ownership of the data in the ASTUnit because the client may 1173 // want to see the diagnostics. 1174 transferASTDataFromCompilerInstance(*Clang); 1175 FailedParseDiagnostics.swap(StoredDiagnostics); 1176 StoredDiagnostics.clear(); 1177 NumStoredDiagnosticsFromDriver = 0; 1178 return true; 1179 } 1180 1181 static std::pair<unsigned, unsigned> 1182 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, 1183 const LangOptions &LangOpts) { 1184 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts); 1185 unsigned Offset = SM.getFileOffset(FileRange.getBegin()); 1186 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd()); 1187 return std::make_pair(Offset, EndOffset); 1188 } 1189 1190 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, 1191 const LangOptions &LangOpts, 1192 const FixItHint &InFix) { 1193 ASTUnit::StandaloneFixIt OutFix; 1194 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts); 1195 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM, 1196 LangOpts); 1197 OutFix.CodeToInsert = InFix.CodeToInsert; 1198 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions; 1199 return OutFix; 1200 } 1201 1202 static ASTUnit::StandaloneDiagnostic 1203 makeStandaloneDiagnostic(const LangOptions &LangOpts, 1204 const StoredDiagnostic &InDiag) { 1205 ASTUnit::StandaloneDiagnostic OutDiag; 1206 OutDiag.ID = InDiag.getID(); 1207 OutDiag.Level = InDiag.getLevel(); 1208 OutDiag.Message = InDiag.getMessage(); 1209 OutDiag.LocOffset = 0; 1210 if (InDiag.getLocation().isInvalid()) 1211 return OutDiag; 1212 const SourceManager &SM = InDiag.getLocation().getManager(); 1213 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation()); 1214 OutDiag.Filename = SM.getFilename(FileLoc); 1215 if (OutDiag.Filename.empty()) 1216 return OutDiag; 1217 OutDiag.LocOffset = SM.getFileOffset(FileLoc); 1218 for (const CharSourceRange &Range : InDiag.getRanges()) 1219 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts)); 1220 for (const FixItHint &FixIt : InDiag.getFixIts()) 1221 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt)); 1222 1223 return OutDiag; 1224 } 1225 1226 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing 1227 /// the source file. 1228 /// 1229 /// This routine will compute the preamble of the main source file. If a 1230 /// non-trivial preamble is found, it will precompile that preamble into a 1231 /// precompiled header so that the precompiled preamble can be used to reduce 1232 /// reparsing time. If a precompiled preamble has already been constructed, 1233 /// this routine will determine if it is still valid and, if so, avoid 1234 /// rebuilding the precompiled preamble. 1235 /// 1236 /// \param AllowRebuild When true (the default), this routine is 1237 /// allowed to rebuild the precompiled preamble if it is found to be 1238 /// out-of-date. 1239 /// 1240 /// \param MaxLines When non-zero, the maximum number of lines that 1241 /// can occur within the preamble. 1242 /// 1243 /// \returns If the precompiled preamble can be used, returns a newly-allocated 1244 /// buffer that should be used in place of the main file when doing so. 1245 /// Otherwise, returns a NULL pointer. 1246 std::unique_ptr<llvm::MemoryBuffer> 1247 ASTUnit::getMainBufferWithPrecompiledPreamble( 1248 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1249 const CompilerInvocation &PreambleInvocationIn, 1250 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild, 1251 unsigned MaxLines) { 1252 1253 auto MainFilePath = 1254 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile(); 1255 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer = 1256 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(), 1257 MainFilePath); 1258 if (!MainFileBuffer) 1259 return nullptr; 1260 1261 PreambleBounds Bounds = 1262 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(), 1263 MainFileBuffer.get(), MaxLines); 1264 if (!Bounds.Size) 1265 return nullptr; 1266 1267 if (Preamble) { 1268 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds, 1269 VFS.get())) { 1270 // Okay! We can re-use the precompiled preamble. 1271 1272 // Set the state of the diagnostic object to mimic its state 1273 // after parsing the preamble. 1274 getDiagnostics().Reset(); 1275 ProcessWarningOptions(getDiagnostics(), 1276 PreambleInvocationIn.getDiagnosticOpts()); 1277 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 1278 1279 PreambleRebuildCounter = 1; 1280 return MainFileBuffer; 1281 } else { 1282 Preamble.reset(); 1283 PreambleDiagnostics.clear(); 1284 TopLevelDeclsInPreamble.clear(); 1285 PreambleRebuildCounter = 1; 1286 } 1287 } 1288 1289 // If the preamble rebuild counter > 1, it's because we previously 1290 // failed to build a preamble and we're not yet ready to try 1291 // again. Decrement the counter and return a failure. 1292 if (PreambleRebuildCounter > 1) { 1293 --PreambleRebuildCounter; 1294 return nullptr; 1295 } 1296 1297 assert(!Preamble && "No Preamble should be stored at that point"); 1298 // If we aren't allowed to rebuild the precompiled preamble, just 1299 // return now. 1300 if (!AllowRebuild) 1301 return nullptr; 1302 1303 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone; 1304 SmallVector<StoredDiagnostic, 4> NewPreambleDiags; 1305 ASTUnitPreambleCallbacks Callbacks; 1306 { 1307 llvm::Optional<CaptureDroppedDiagnostics> Capture; 1308 if (CaptureDiagnostics) 1309 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags, 1310 &NewPreambleDiagsStandalone); 1311 1312 // We did not previously compute a preamble, or it can't be reused anyway. 1313 SimpleTimer PreambleTimer(WantTiming); 1314 PreambleTimer.setOutput("Precompiling preamble"); 1315 1316 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build( 1317 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS, 1318 PCHContainerOps, Callbacks); 1319 if (NewPreamble) { 1320 Preamble = std::move(*NewPreamble); 1321 PreambleRebuildCounter = 1; 1322 } else { 1323 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) { 1324 case BuildPreambleError::CouldntCreateTempFile: 1325 case BuildPreambleError::PreambleIsEmpty: 1326 // Try again next time. 1327 PreambleRebuildCounter = 1; 1328 return nullptr; 1329 case BuildPreambleError::CouldntCreateTargetInfo: 1330 case BuildPreambleError::BeginSourceFileFailed: 1331 case BuildPreambleError::CouldntEmitPCH: 1332 case BuildPreambleError::CouldntCreateVFSOverlay: 1333 // These erros are more likely to repeat, retry after some period. 1334 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1335 return nullptr; 1336 } 1337 llvm_unreachable("unexpected BuildPreambleError"); 1338 } 1339 } 1340 1341 assert(Preamble && "Preamble wasn't built"); 1342 1343 TopLevelDecls.clear(); 1344 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs(); 1345 PreambleTopLevelHashValue = Callbacks.getHash(); 1346 1347 NumWarningsInPreamble = getDiagnostics().getNumWarnings(); 1348 1349 checkAndRemoveNonDriverDiags(NewPreambleDiags); 1350 StoredDiagnostics = std::move(NewPreambleDiags); 1351 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone); 1352 1353 // If the hash of top-level entities differs from the hash of the top-level 1354 // entities the last time we rebuilt the preamble, clear out the completion 1355 // cache. 1356 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) { 1357 CompletionCacheTopLevelHashValue = 0; 1358 PreambleTopLevelHashValue = CurrentTopLevelHashValue; 1359 } 1360 1361 return MainFileBuffer; 1362 } 1363 1364 void ASTUnit::RealizeTopLevelDeclsFromPreamble() { 1365 assert(Preamble && "Should only be called when preamble was built"); 1366 1367 std::vector<Decl *> Resolved; 1368 Resolved.reserve(TopLevelDeclsInPreamble.size()); 1369 ExternalASTSource &Source = *getASTContext().getExternalSource(); 1370 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) { 1371 // Resolve the declaration ID to an actual declaration, possibly 1372 // deserializing the declaration in the process. 1373 if (Decl *D = Source.GetExternalDecl(TopLevelDecl)) 1374 Resolved.push_back(D); 1375 } 1376 TopLevelDeclsInPreamble.clear(); 1377 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); 1378 } 1379 1380 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) { 1381 // Steal the created target, context, and preprocessor if they have been 1382 // created. 1383 assert(CI.hasInvocation() && "missing invocation"); 1384 LangOpts = CI.getInvocation().LangOpts; 1385 TheSema = CI.takeSema(); 1386 Consumer = CI.takeASTConsumer(); 1387 if (CI.hasASTContext()) 1388 Ctx = &CI.getASTContext(); 1389 if (CI.hasPreprocessor()) 1390 PP = CI.getPreprocessorPtr(); 1391 CI.setSourceManager(nullptr); 1392 CI.setFileManager(nullptr); 1393 if (CI.hasTarget()) 1394 Target = &CI.getTarget(); 1395 Reader = CI.getModuleManager(); 1396 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure(); 1397 } 1398 1399 StringRef ASTUnit::getMainFileName() const { 1400 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) { 1401 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0]; 1402 if (Input.isFile()) 1403 return Input.getFile(); 1404 else 1405 return Input.getBuffer()->getBufferIdentifier(); 1406 } 1407 1408 if (SourceMgr) { 1409 if (const FileEntry * 1410 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID())) 1411 return FE->getName(); 1412 } 1413 1414 return StringRef(); 1415 } 1416 1417 StringRef ASTUnit::getASTFileName() const { 1418 if (!isMainFileAST()) 1419 return StringRef(); 1420 1421 serialization::ModuleFile & 1422 Mod = Reader->getModuleManager().getPrimaryModule(); 1423 return Mod.FileName; 1424 } 1425 1426 std::unique_ptr<ASTUnit> 1427 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI, 1428 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 1429 bool CaptureDiagnostics, bool UserFilesAreVolatile) { 1430 std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); 1431 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 1432 IntrusiveRefCntPtr<vfs::FileSystem> VFS = 1433 createVFSFromCompilerInvocation(*CI, *Diags); 1434 if (!VFS) 1435 return nullptr; 1436 AST->Diagnostics = Diags; 1437 AST->FileSystemOpts = CI->getFileSystemOpts(); 1438 AST->Invocation = std::move(CI); 1439 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); 1440 AST->UserFilesAreVolatile = UserFilesAreVolatile; 1441 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr, 1442 UserFilesAreVolatile); 1443 AST->PCMCache = new MemoryBufferCache; 1444 1445 return AST; 1446 } 1447 1448 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( 1449 std::shared_ptr<CompilerInvocation> CI, 1450 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1451 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action, 1452 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath, 1453 bool OnlyLocalDecls, bool CaptureDiagnostics, 1454 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults, 1455 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile, 1456 std::unique_ptr<ASTUnit> *ErrAST) { 1457 assert(CI && "A CompilerInvocation is required"); 1458 1459 std::unique_ptr<ASTUnit> OwnAST; 1460 ASTUnit *AST = Unit; 1461 if (!AST) { 1462 // Create the AST unit. 1463 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile); 1464 AST = OwnAST.get(); 1465 if (!AST) 1466 return nullptr; 1467 } 1468 1469 if (!ResourceFilesPath.empty()) { 1470 // Override the resources path. 1471 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath; 1472 } 1473 AST->OnlyLocalDecls = OnlyLocalDecls; 1474 AST->CaptureDiagnostics = CaptureDiagnostics; 1475 if (PrecompilePreambleAfterNParses > 0) 1476 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses; 1477 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete; 1478 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1479 AST->IncludeBriefCommentsInCodeCompletion 1480 = IncludeBriefCommentsInCodeCompletion; 1481 1482 // Recover resources if we crash before exiting this method. 1483 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1484 ASTUnitCleanup(OwnAST.get()); 1485 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 1486 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 1487 DiagCleanup(Diags.get()); 1488 1489 // We'll manage file buffers ourselves. 1490 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1491 CI->getFrontendOpts().DisableFree = false; 1492 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts()); 1493 1494 // Create the compiler instance to use for building the AST. 1495 std::unique_ptr<CompilerInstance> Clang( 1496 new CompilerInstance(std::move(PCHContainerOps))); 1497 1498 // Recover resources if we crash before exiting this method. 1499 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 1500 CICleanup(Clang.get()); 1501 1502 Clang->setInvocation(std::move(CI)); 1503 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile(); 1504 1505 // Set up diagnostics, capturing any diagnostics that would 1506 // otherwise be dropped. 1507 Clang->setDiagnostics(&AST->getDiagnostics()); 1508 1509 // Create the target instance. 1510 Clang->setTarget(TargetInfo::CreateTargetInfo( 1511 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 1512 if (!Clang->hasTarget()) 1513 return nullptr; 1514 1515 // Inform the target of the language options. 1516 // 1517 // FIXME: We shouldn't need to do this, the target should be immutable once 1518 // created. This complexity should be lifted elsewhere. 1519 Clang->getTarget().adjust(Clang->getLangOpts()); 1520 1521 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1522 "Invocation must have exactly one source file!"); 1523 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 1524 InputKind::Source && 1525 "FIXME: AST inputs not yet supported here!"); 1526 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 1527 InputKind::LLVM_IR && 1528 "IR inputs not support here!"); 1529 1530 // Configure the various subsystems. 1531 AST->TheSema.reset(); 1532 AST->Ctx = nullptr; 1533 AST->PP = nullptr; 1534 AST->Reader = nullptr; 1535 1536 // Create a file manager object to provide access to and cache the filesystem. 1537 Clang->setFileManager(&AST->getFileManager()); 1538 1539 // Create the source manager. 1540 Clang->setSourceManager(&AST->getSourceManager()); 1541 1542 FrontendAction *Act = Action; 1543 1544 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct; 1545 if (!Act) { 1546 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST)); 1547 Act = TrackerAct.get(); 1548 } 1549 1550 // Recover resources if we crash before exiting this method. 1551 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> 1552 ActCleanup(TrackerAct.get()); 1553 1554 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) { 1555 AST->transferASTDataFromCompilerInstance(*Clang); 1556 if (OwnAST && ErrAST) 1557 ErrAST->swap(OwnAST); 1558 1559 return nullptr; 1560 } 1561 1562 if (Persistent && !TrackerAct) { 1563 Clang->getPreprocessor().addPPCallbacks( 1564 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>( 1565 AST->getCurrentTopLevelHashValue())); 1566 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 1567 if (Clang->hasASTConsumer()) 1568 Consumers.push_back(Clang->takeASTConsumer()); 1569 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>( 1570 *AST, AST->getCurrentTopLevelHashValue())); 1571 Clang->setASTConsumer( 1572 llvm::make_unique<MultiplexConsumer>(std::move(Consumers))); 1573 } 1574 if (!Act->Execute()) { 1575 AST->transferASTDataFromCompilerInstance(*Clang); 1576 if (OwnAST && ErrAST) 1577 ErrAST->swap(OwnAST); 1578 1579 return nullptr; 1580 } 1581 1582 // Steal the created target, context, and preprocessor. 1583 AST->transferASTDataFromCompilerInstance(*Clang); 1584 1585 Act->EndSourceFile(); 1586 1587 if (OwnAST) 1588 return OwnAST.release(); 1589 else 1590 return AST; 1591 } 1592 1593 bool ASTUnit::LoadFromCompilerInvocation( 1594 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1595 unsigned PrecompilePreambleAfterNParses, 1596 IntrusiveRefCntPtr<vfs::FileSystem> VFS) { 1597 if (!Invocation) 1598 return true; 1599 1600 assert(VFS && "VFS is null"); 1601 1602 // We'll manage file buffers ourselves. 1603 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1604 Invocation->getFrontendOpts().DisableFree = false; 1605 getDiagnostics().Reset(); 1606 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1607 1608 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; 1609 if (PrecompilePreambleAfterNParses > 0) { 1610 PreambleRebuildCounter = PrecompilePreambleAfterNParses; 1611 OverrideMainBuffer = 1612 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS); 1613 getDiagnostics().Reset(); 1614 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1615 } 1616 1617 SimpleTimer ParsingTimer(WantTiming); 1618 ParsingTimer.setOutput("Parsing " + getMainFileName()); 1619 1620 // Recover resources if we crash before exiting this method. 1621 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer> 1622 MemBufferCleanup(OverrideMainBuffer.get()); 1623 1624 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS); 1625 } 1626 1627 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation( 1628 std::shared_ptr<CompilerInvocation> CI, 1629 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1630 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr, 1631 bool OnlyLocalDecls, bool CaptureDiagnostics, 1632 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind, 1633 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, 1634 bool UserFilesAreVolatile) { 1635 // Create the AST unit. 1636 std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); 1637 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 1638 AST->Diagnostics = Diags; 1639 AST->OnlyLocalDecls = OnlyLocalDecls; 1640 AST->CaptureDiagnostics = CaptureDiagnostics; 1641 AST->TUKind = TUKind; 1642 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1643 AST->IncludeBriefCommentsInCodeCompletion 1644 = IncludeBriefCommentsInCodeCompletion; 1645 AST->Invocation = std::move(CI); 1646 AST->FileSystemOpts = FileMgr->getFileSystemOpts(); 1647 AST->FileMgr = FileMgr; 1648 AST->UserFilesAreVolatile = UserFilesAreVolatile; 1649 1650 // Recover resources if we crash before exiting this method. 1651 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1652 ASTUnitCleanup(AST.get()); 1653 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 1654 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 1655 DiagCleanup(Diags.get()); 1656 1657 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), 1658 PrecompilePreambleAfterNParses, 1659 AST->FileMgr->getVirtualFileSystem())) 1660 return nullptr; 1661 return AST; 1662 } 1663 1664 ASTUnit *ASTUnit::LoadFromCommandLine( 1665 const char **ArgBegin, const char **ArgEnd, 1666 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1667 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath, 1668 bool OnlyLocalDecls, bool CaptureDiagnostics, 1669 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName, 1670 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind, 1671 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, 1672 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies, 1673 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization, 1674 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST, 1675 IntrusiveRefCntPtr<vfs::FileSystem> VFS) { 1676 assert(Diags.get() && "no DiagnosticsEngine was provided"); 1677 1678 SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 1679 1680 std::shared_ptr<CompilerInvocation> CI; 1681 1682 { 1683 1684 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, 1685 &StoredDiagnostics, nullptr); 1686 1687 CI = clang::createInvocationFromCommandLine( 1688 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS); 1689 if (!CI) 1690 return nullptr; 1691 } 1692 1693 // Override any files that need remapping 1694 for (const auto &RemappedFile : RemappedFiles) { 1695 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first, 1696 RemappedFile.second); 1697 } 1698 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts(); 1699 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName; 1700 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors; 1701 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0; 1702 PPOpts.SingleFileParseMode = SingleFileParse; 1703 1704 // Override the resources path. 1705 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath; 1706 1707 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies; 1708 1709 if (ModuleFormat) 1710 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue(); 1711 1712 // Create the AST unit. 1713 std::unique_ptr<ASTUnit> AST; 1714 AST.reset(new ASTUnit(false)); 1715 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 1716 AST->Diagnostics = Diags; 1717 AST->FileSystemOpts = CI->getFileSystemOpts(); 1718 if (!VFS) 1719 VFS = vfs::getRealFileSystem(); 1720 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); 1721 if (!VFS) 1722 return nullptr; 1723 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); 1724 AST->PCMCache = new MemoryBufferCache; 1725 AST->OnlyLocalDecls = OnlyLocalDecls; 1726 AST->CaptureDiagnostics = CaptureDiagnostics; 1727 AST->TUKind = TUKind; 1728 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1729 AST->IncludeBriefCommentsInCodeCompletion 1730 = IncludeBriefCommentsInCodeCompletion; 1731 AST->UserFilesAreVolatile = UserFilesAreVolatile; 1732 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size(); 1733 AST->StoredDiagnostics.swap(StoredDiagnostics); 1734 AST->Invocation = CI; 1735 if (ForSerialization) 1736 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache)); 1737 // Zero out now to ease cleanup during crash recovery. 1738 CI = nullptr; 1739 Diags = nullptr; 1740 1741 // Recover resources if we crash before exiting this method. 1742 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1743 ASTUnitCleanup(AST.get()); 1744 1745 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), 1746 PrecompilePreambleAfterNParses, 1747 VFS)) { 1748 // Some error occurred, if caller wants to examine diagnostics, pass it the 1749 // ASTUnit. 1750 if (ErrAST) { 1751 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics); 1752 ErrAST->swap(AST); 1753 } 1754 return nullptr; 1755 } 1756 1757 return AST.release(); 1758 } 1759 1760 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1761 ArrayRef<RemappedFile> RemappedFiles, 1762 IntrusiveRefCntPtr<vfs::FileSystem> VFS) { 1763 if (!Invocation) 1764 return true; 1765 1766 if (!VFS) { 1767 assert(FileMgr && "FileMgr is null on Reparse call"); 1768 VFS = FileMgr->getVirtualFileSystem(); 1769 } 1770 1771 clearFileLevelDecls(); 1772 1773 SimpleTimer ParsingTimer(WantTiming); 1774 ParsingTimer.setOutput("Reparsing " + getMainFileName()); 1775 1776 // Remap files. 1777 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1778 for (const auto &RB : PPOpts.RemappedFileBuffers) 1779 delete RB.second; 1780 1781 Invocation->getPreprocessorOpts().clearRemappedFiles(); 1782 for (const auto &RemappedFile : RemappedFiles) { 1783 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first, 1784 RemappedFile.second); 1785 } 1786 1787 // If we have a preamble file lying around, or if we might try to 1788 // build a precompiled preamble, do so now. 1789 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; 1790 if (Preamble || PreambleRebuildCounter > 0) 1791 OverrideMainBuffer = 1792 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS); 1793 1794 1795 // Clear out the diagnostics state. 1796 FileMgr.reset(); 1797 getDiagnostics().Reset(); 1798 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1799 if (OverrideMainBuffer) 1800 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 1801 1802 // Parse the sources 1803 bool Result = 1804 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS); 1805 1806 // If we're caching global code-completion results, and the top-level 1807 // declarations have changed, clear out the code-completion cache. 1808 if (!Result && ShouldCacheCodeCompletionResults && 1809 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue) 1810 CacheCodeCompletionResults(); 1811 1812 // We now need to clear out the completion info related to this translation 1813 // unit; it'll be recreated if necessary. 1814 CCTUInfo.reset(); 1815 1816 return Result; 1817 } 1818 1819 void ASTUnit::ResetForParse() { 1820 SavedMainFileBuffer.reset(); 1821 1822 SourceMgr.reset(); 1823 TheSema.reset(); 1824 Ctx.reset(); 1825 PP.reset(); 1826 Reader.reset(); 1827 1828 TopLevelDecls.clear(); 1829 clearFileLevelDecls(); 1830 } 1831 1832 //----------------------------------------------------------------------------// 1833 // Code completion 1834 //----------------------------------------------------------------------------// 1835 1836 namespace { 1837 /// \brief Code completion consumer that combines the cached code-completion 1838 /// results from an ASTUnit with the code-completion results provided to it, 1839 /// then passes the result on to 1840 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer { 1841 uint64_t NormalContexts; 1842 ASTUnit &AST; 1843 CodeCompleteConsumer &Next; 1844 1845 public: 1846 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next, 1847 const CodeCompleteOptions &CodeCompleteOpts) 1848 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()), 1849 AST(AST), Next(Next) 1850 { 1851 // Compute the set of contexts in which we will look when we don't have 1852 // any information about the specific context. 1853 NormalContexts 1854 = (1LL << CodeCompletionContext::CCC_TopLevel) 1855 | (1LL << CodeCompletionContext::CCC_ObjCInterface) 1856 | (1LL << CodeCompletionContext::CCC_ObjCImplementation) 1857 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 1858 | (1LL << CodeCompletionContext::CCC_Statement) 1859 | (1LL << CodeCompletionContext::CCC_Expression) 1860 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) 1861 | (1LL << CodeCompletionContext::CCC_DotMemberAccess) 1862 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess) 1863 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess) 1864 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName) 1865 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) 1866 | (1LL << CodeCompletionContext::CCC_Recovery); 1867 1868 if (AST.getASTContext().getLangOpts().CPlusPlus) 1869 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag) 1870 | (1LL << CodeCompletionContext::CCC_UnionTag) 1871 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag); 1872 } 1873 1874 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, 1875 CodeCompletionResult *Results, 1876 unsigned NumResults) override; 1877 1878 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 1879 OverloadCandidate *Candidates, 1880 unsigned NumCandidates) override { 1881 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates); 1882 } 1883 1884 CodeCompletionAllocator &getAllocator() override { 1885 return Next.getAllocator(); 1886 } 1887 1888 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { 1889 return Next.getCodeCompletionTUInfo(); 1890 } 1891 }; 1892 } // anonymous namespace 1893 1894 /// \brief Helper function that computes which global names are hidden by the 1895 /// local code-completion results. 1896 static void CalculateHiddenNames(const CodeCompletionContext &Context, 1897 CodeCompletionResult *Results, 1898 unsigned NumResults, 1899 ASTContext &Ctx, 1900 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){ 1901 bool OnlyTagNames = false; 1902 switch (Context.getKind()) { 1903 case CodeCompletionContext::CCC_Recovery: 1904 case CodeCompletionContext::CCC_TopLevel: 1905 case CodeCompletionContext::CCC_ObjCInterface: 1906 case CodeCompletionContext::CCC_ObjCImplementation: 1907 case CodeCompletionContext::CCC_ObjCIvarList: 1908 case CodeCompletionContext::CCC_ClassStructUnion: 1909 case CodeCompletionContext::CCC_Statement: 1910 case CodeCompletionContext::CCC_Expression: 1911 case CodeCompletionContext::CCC_ObjCMessageReceiver: 1912 case CodeCompletionContext::CCC_DotMemberAccess: 1913 case CodeCompletionContext::CCC_ArrowMemberAccess: 1914 case CodeCompletionContext::CCC_ObjCPropertyAccess: 1915 case CodeCompletionContext::CCC_Namespace: 1916 case CodeCompletionContext::CCC_Type: 1917 case CodeCompletionContext::CCC_Name: 1918 case CodeCompletionContext::CCC_PotentiallyQualifiedName: 1919 case CodeCompletionContext::CCC_ParenthesizedExpression: 1920 case CodeCompletionContext::CCC_ObjCInterfaceName: 1921 break; 1922 1923 case CodeCompletionContext::CCC_EnumTag: 1924 case CodeCompletionContext::CCC_UnionTag: 1925 case CodeCompletionContext::CCC_ClassOrStructTag: 1926 OnlyTagNames = true; 1927 break; 1928 1929 case CodeCompletionContext::CCC_ObjCProtocolName: 1930 case CodeCompletionContext::CCC_MacroName: 1931 case CodeCompletionContext::CCC_MacroNameUse: 1932 case CodeCompletionContext::CCC_PreprocessorExpression: 1933 case CodeCompletionContext::CCC_PreprocessorDirective: 1934 case CodeCompletionContext::CCC_NaturalLanguage: 1935 case CodeCompletionContext::CCC_SelectorName: 1936 case CodeCompletionContext::CCC_TypeQualifiers: 1937 case CodeCompletionContext::CCC_Other: 1938 case CodeCompletionContext::CCC_OtherWithMacros: 1939 case CodeCompletionContext::CCC_ObjCInstanceMessage: 1940 case CodeCompletionContext::CCC_ObjCClassMessage: 1941 case CodeCompletionContext::CCC_ObjCCategoryName: 1942 // We're looking for nothing, or we're looking for names that cannot 1943 // be hidden. 1944 return; 1945 } 1946 1947 typedef CodeCompletionResult Result; 1948 for (unsigned I = 0; I != NumResults; ++I) { 1949 if (Results[I].Kind != Result::RK_Declaration) 1950 continue; 1951 1952 unsigned IDNS 1953 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace(); 1954 1955 bool Hiding = false; 1956 if (OnlyTagNames) 1957 Hiding = (IDNS & Decl::IDNS_Tag); 1958 else { 1959 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 1960 Decl::IDNS_Namespace | Decl::IDNS_Ordinary | 1961 Decl::IDNS_NonMemberOperator); 1962 if (Ctx.getLangOpts().CPlusPlus) 1963 HiddenIDNS |= Decl::IDNS_Tag; 1964 Hiding = (IDNS & HiddenIDNS); 1965 } 1966 1967 if (!Hiding) 1968 continue; 1969 1970 DeclarationName Name = Results[I].Declaration->getDeclName(); 1971 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo()) 1972 HiddenNames.insert(Identifier->getName()); 1973 else 1974 HiddenNames.insert(Name.getAsString()); 1975 } 1976 } 1977 1978 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, 1979 CodeCompletionContext Context, 1980 CodeCompletionResult *Results, 1981 unsigned NumResults) { 1982 // Merge the results we were given with the results we cached. 1983 bool AddedResult = false; 1984 uint64_t InContexts = 1985 Context.getKind() == CodeCompletionContext::CCC_Recovery 1986 ? NormalContexts : (1LL << Context.getKind()); 1987 // Contains the set of names that are hidden by "local" completion results. 1988 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames; 1989 typedef CodeCompletionResult Result; 1990 SmallVector<Result, 8> AllResults; 1991 for (ASTUnit::cached_completion_iterator 1992 C = AST.cached_completion_begin(), 1993 CEnd = AST.cached_completion_end(); 1994 C != CEnd; ++C) { 1995 // If the context we are in matches any of the contexts we are 1996 // interested in, we'll add this result. 1997 if ((C->ShowInContexts & InContexts) == 0) 1998 continue; 1999 2000 // If we haven't added any results previously, do so now. 2001 if (!AddedResult) { 2002 CalculateHiddenNames(Context, Results, NumResults, S.Context, 2003 HiddenNames); 2004 AllResults.insert(AllResults.end(), Results, Results + NumResults); 2005 AddedResult = true; 2006 } 2007 2008 // Determine whether this global completion result is hidden by a local 2009 // completion result. If so, skip it. 2010 if (C->Kind != CXCursor_MacroDefinition && 2011 HiddenNames.count(C->Completion->getTypedText())) 2012 continue; 2013 2014 // Adjust priority based on similar type classes. 2015 unsigned Priority = C->Priority; 2016 CodeCompletionString *Completion = C->Completion; 2017 if (!Context.getPreferredType().isNull()) { 2018 if (C->Kind == CXCursor_MacroDefinition) { 2019 Priority = getMacroUsagePriority(C->Completion->getTypedText(), 2020 S.getLangOpts(), 2021 Context.getPreferredType()->isAnyPointerType()); 2022 } else if (C->Type) { 2023 CanQualType Expected 2024 = S.Context.getCanonicalType( 2025 Context.getPreferredType().getUnqualifiedType()); 2026 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected); 2027 if (ExpectedSTC == C->TypeClass) { 2028 // We know this type is similar; check for an exact match. 2029 llvm::StringMap<unsigned> &CachedCompletionTypes 2030 = AST.getCachedCompletionTypes(); 2031 llvm::StringMap<unsigned>::iterator Pos 2032 = CachedCompletionTypes.find(QualType(Expected).getAsString()); 2033 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type) 2034 Priority /= CCF_ExactTypeMatch; 2035 else 2036 Priority /= CCF_SimilarTypeMatch; 2037 } 2038 } 2039 } 2040 2041 // Adjust the completion string, if required. 2042 if (C->Kind == CXCursor_MacroDefinition && 2043 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) { 2044 // Create a new code-completion string that just contains the 2045 // macro name, without its arguments. 2046 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(), 2047 CCP_CodePattern, C->Availability); 2048 Builder.AddTypedTextChunk(C->Completion->getTypedText()); 2049 Priority = CCP_CodePattern; 2050 Completion = Builder.TakeString(); 2051 } 2052 2053 AllResults.push_back(Result(Completion, Priority, C->Kind, 2054 C->Availability)); 2055 } 2056 2057 // If we did not add any cached completion results, just forward the 2058 // results we were given to the next consumer. 2059 if (!AddedResult) { 2060 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults); 2061 return; 2062 } 2063 2064 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(), 2065 AllResults.size()); 2066 } 2067 2068 void ASTUnit::CodeComplete( 2069 StringRef File, unsigned Line, unsigned Column, 2070 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros, 2071 bool IncludeCodePatterns, bool IncludeBriefComments, 2072 CodeCompleteConsumer &Consumer, 2073 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 2074 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, 2075 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 2076 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { 2077 if (!Invocation) 2078 return; 2079 2080 SimpleTimer CompletionTimer(WantTiming); 2081 CompletionTimer.setOutput("Code completion @ " + File + ":" + 2082 Twine(Line) + ":" + Twine(Column)); 2083 2084 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation); 2085 2086 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts(); 2087 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts; 2088 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts(); 2089 2090 CodeCompleteOpts.IncludeMacros = IncludeMacros && 2091 CachedCompletionResults.empty(); 2092 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns; 2093 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty(); 2094 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments; 2095 2096 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion); 2097 2098 FrontendOpts.CodeCompletionAt.FileName = File; 2099 FrontendOpts.CodeCompletionAt.Line = Line; 2100 FrontendOpts.CodeCompletionAt.Column = Column; 2101 2102 // Set the language options appropriately. 2103 LangOpts = *CCInvocation->getLangOpts(); 2104 2105 // Spell-checking and warnings are wasteful during code-completion. 2106 LangOpts.SpellChecking = false; 2107 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true; 2108 2109 std::unique_ptr<CompilerInstance> Clang( 2110 new CompilerInstance(PCHContainerOps)); 2111 2112 // Recover resources if we crash before exiting this method. 2113 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 2114 CICleanup(Clang.get()); 2115 2116 auto &Inv = *CCInvocation; 2117 Clang->setInvocation(std::move(CCInvocation)); 2118 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile(); 2119 2120 // Set up diagnostics, capturing any diagnostics produced. 2121 Clang->setDiagnostics(&Diag); 2122 CaptureDroppedDiagnostics Capture(true, 2123 Clang->getDiagnostics(), 2124 &StoredDiagnostics, nullptr); 2125 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts()); 2126 2127 // Create the target instance. 2128 Clang->setTarget(TargetInfo::CreateTargetInfo( 2129 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 2130 if (!Clang->hasTarget()) { 2131 Clang->setInvocation(nullptr); 2132 return; 2133 } 2134 2135 // Inform the target of the language options. 2136 // 2137 // FIXME: We shouldn't need to do this, the target should be immutable once 2138 // created. This complexity should be lifted elsewhere. 2139 Clang->getTarget().adjust(Clang->getLangOpts()); 2140 2141 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 2142 "Invocation must have exactly one source file!"); 2143 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 2144 InputKind::Source && 2145 "FIXME: AST inputs not yet supported here!"); 2146 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 2147 InputKind::LLVM_IR && 2148 "IR inputs not support here!"); 2149 2150 // Use the source and file managers that we were given. 2151 Clang->setFileManager(&FileMgr); 2152 Clang->setSourceManager(&SourceMgr); 2153 2154 // Remap files. 2155 PreprocessorOpts.clearRemappedFiles(); 2156 PreprocessorOpts.RetainRemappedFileBuffers = true; 2157 for (const auto &RemappedFile : RemappedFiles) { 2158 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second); 2159 OwnedBuffers.push_back(RemappedFile.second); 2160 } 2161 2162 // Use the code completion consumer we were given, but adding any cached 2163 // code-completion results. 2164 AugmentedCodeCompleteConsumer *AugmentedConsumer 2165 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts); 2166 Clang->setCodeCompletionConsumer(AugmentedConsumer); 2167 2168 // If we have a precompiled preamble, try to use it. We only allow 2169 // the use of the precompiled preamble if we're if the completion 2170 // point is within the main file, after the end of the precompiled 2171 // preamble. 2172 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; 2173 if (Preamble) { 2174 std::string CompleteFilePath(File); 2175 2176 auto VFS = FileMgr.getVirtualFileSystem(); 2177 auto CompleteFileStatus = VFS->status(CompleteFilePath); 2178 if (CompleteFileStatus) { 2179 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID(); 2180 2181 std::string MainPath(OriginalSourceFile); 2182 auto MainStatus = VFS->status(MainPath); 2183 if (MainStatus) { 2184 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID(); 2185 if (CompleteFileID == MainID && Line > 1) 2186 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( 2187 PCHContainerOps, Inv, VFS, false, Line - 1); 2188 } 2189 } 2190 } 2191 2192 // If the main file has been overridden due to the use of a preamble, 2193 // make that override happen and introduce the preamble. 2194 if (OverrideMainBuffer) { 2195 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null"); 2196 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get()); 2197 OwnedBuffers.push_back(OverrideMainBuffer.release()); 2198 } else { 2199 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 2200 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 2201 } 2202 2203 // Disable the preprocessing record if modules are not enabled. 2204 if (!Clang->getLangOpts().Modules) 2205 PreprocessorOpts.DetailedRecord = false; 2206 2207 std::unique_ptr<SyntaxOnlyAction> Act; 2208 Act.reset(new SyntaxOnlyAction); 2209 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) { 2210 Act->Execute(); 2211 Act->EndSourceFile(); 2212 } 2213 } 2214 2215 bool ASTUnit::Save(StringRef File) { 2216 if (HadModuleLoaderFatalFailure) 2217 return true; 2218 2219 // Write to a temporary file and later rename it to the actual file, to avoid 2220 // possible race conditions. 2221 SmallString<128> TempPath; 2222 TempPath = File; 2223 TempPath += "-%%%%%%%%"; 2224 int fd; 2225 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath)) 2226 return true; 2227 2228 // FIXME: Can we somehow regenerate the stat cache here, or do we need to 2229 // unconditionally create a stat cache when we parse the file? 2230 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true); 2231 2232 serialize(Out); 2233 Out.close(); 2234 if (Out.has_error()) { 2235 Out.clear_error(); 2236 return true; 2237 } 2238 2239 if (llvm::sys::fs::rename(TempPath, File)) { 2240 llvm::sys::fs::remove(TempPath); 2241 return true; 2242 } 2243 2244 return false; 2245 } 2246 2247 static bool serializeUnit(ASTWriter &Writer, 2248 SmallVectorImpl<char> &Buffer, 2249 Sema &S, 2250 bool hasErrors, 2251 raw_ostream &OS) { 2252 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors); 2253 2254 // Write the generated bitstream to "Out". 2255 if (!Buffer.empty()) 2256 OS.write(Buffer.data(), Buffer.size()); 2257 2258 return false; 2259 } 2260 2261 bool ASTUnit::serialize(raw_ostream &OS) { 2262 // For serialization we are lenient if the errors were only warn-as-error kind. 2263 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred(); 2264 2265 if (WriterData) 2266 return serializeUnit(WriterData->Writer, WriterData->Buffer, 2267 getSema(), hasErrors, OS); 2268 2269 SmallString<128> Buffer; 2270 llvm::BitstreamWriter Stream(Buffer); 2271 MemoryBufferCache PCMCache; 2272 ASTWriter Writer(Stream, Buffer, PCMCache, {}); 2273 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS); 2274 } 2275 2276 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap; 2277 2278 void ASTUnit::TranslateStoredDiagnostics( 2279 FileManager &FileMgr, 2280 SourceManager &SrcMgr, 2281 const SmallVectorImpl<StandaloneDiagnostic> &Diags, 2282 SmallVectorImpl<StoredDiagnostic> &Out) { 2283 // Map the standalone diagnostic into the new source manager. We also need to 2284 // remap all the locations to the new view. This includes the diag location, 2285 // any associated source ranges, and the source ranges of associated fix-its. 2286 // FIXME: There should be a cleaner way to do this. 2287 SmallVector<StoredDiagnostic, 4> Result; 2288 Result.reserve(Diags.size()); 2289 2290 for (const StandaloneDiagnostic &SD : Diags) { 2291 // Rebuild the StoredDiagnostic. 2292 if (SD.Filename.empty()) 2293 continue; 2294 const FileEntry *FE = FileMgr.getFile(SD.Filename); 2295 if (!FE) 2296 continue; 2297 SourceLocation FileLoc; 2298 auto ItFileID = PreambleSrcLocCache.find(SD.Filename); 2299 if (ItFileID == PreambleSrcLocCache.end()) { 2300 FileID FID = SrcMgr.translateFile(FE); 2301 FileLoc = SrcMgr.getLocForStartOfFile(FID); 2302 PreambleSrcLocCache[SD.Filename] = FileLoc; 2303 } else { 2304 FileLoc = ItFileID->getValue(); 2305 } 2306 2307 if (FileLoc.isInvalid()) 2308 continue; 2309 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset); 2310 FullSourceLoc Loc(L, SrcMgr); 2311 2312 SmallVector<CharSourceRange, 4> Ranges; 2313 Ranges.reserve(SD.Ranges.size()); 2314 for (const auto &Range : SD.Ranges) { 2315 SourceLocation BL = FileLoc.getLocWithOffset(Range.first); 2316 SourceLocation EL = FileLoc.getLocWithOffset(Range.second); 2317 Ranges.push_back(CharSourceRange::getCharRange(BL, EL)); 2318 } 2319 2320 SmallVector<FixItHint, 2> FixIts; 2321 FixIts.reserve(SD.FixIts.size()); 2322 for (const StandaloneFixIt &FixIt : SD.FixIts) { 2323 FixIts.push_back(FixItHint()); 2324 FixItHint &FH = FixIts.back(); 2325 FH.CodeToInsert = FixIt.CodeToInsert; 2326 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first); 2327 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second); 2328 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL); 2329 } 2330 2331 Result.push_back(StoredDiagnostic(SD.Level, SD.ID, 2332 SD.Message, Loc, Ranges, FixIts)); 2333 } 2334 Result.swap(Out); 2335 } 2336 2337 void ASTUnit::addFileLevelDecl(Decl *D) { 2338 assert(D); 2339 2340 // We only care about local declarations. 2341 if (D->isFromASTFile()) 2342 return; 2343 2344 SourceManager &SM = *SourceMgr; 2345 SourceLocation Loc = D->getLocation(); 2346 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc)) 2347 return; 2348 2349 // We only keep track of the file-level declarations of each file. 2350 if (!D->getLexicalDeclContext()->isFileContext()) 2351 return; 2352 2353 SourceLocation FileLoc = SM.getFileLoc(Loc); 2354 assert(SM.isLocalSourceLocation(FileLoc)); 2355 FileID FID; 2356 unsigned Offset; 2357 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 2358 if (FID.isInvalid()) 2359 return; 2360 2361 LocDeclsTy *&Decls = FileDecls[FID]; 2362 if (!Decls) 2363 Decls = new LocDeclsTy(); 2364 2365 std::pair<unsigned, Decl *> LocDecl(Offset, D); 2366 2367 if (Decls->empty() || Decls->back().first <= Offset) { 2368 Decls->push_back(LocDecl); 2369 return; 2370 } 2371 2372 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(), 2373 LocDecl, llvm::less_first()); 2374 2375 Decls->insert(I, LocDecl); 2376 } 2377 2378 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, 2379 SmallVectorImpl<Decl *> &Decls) { 2380 if (File.isInvalid()) 2381 return; 2382 2383 if (SourceMgr->isLoadedFileID(File)) { 2384 assert(Ctx->getExternalSource() && "No external source!"); 2385 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length, 2386 Decls); 2387 } 2388 2389 FileDeclsTy::iterator I = FileDecls.find(File); 2390 if (I == FileDecls.end()) 2391 return; 2392 2393 LocDeclsTy &LocDecls = *I->second; 2394 if (LocDecls.empty()) 2395 return; 2396 2397 LocDeclsTy::iterator BeginIt = 2398 std::lower_bound(LocDecls.begin(), LocDecls.end(), 2399 std::make_pair(Offset, (Decl *)nullptr), 2400 llvm::less_first()); 2401 if (BeginIt != LocDecls.begin()) 2402 --BeginIt; 2403 2404 // If we are pointing at a top-level decl inside an objc container, we need 2405 // to backtrack until we find it otherwise we will fail to report that the 2406 // region overlaps with an objc container. 2407 while (BeginIt != LocDecls.begin() && 2408 BeginIt->second->isTopLevelDeclInObjCContainer()) 2409 --BeginIt; 2410 2411 LocDeclsTy::iterator EndIt = std::upper_bound( 2412 LocDecls.begin(), LocDecls.end(), 2413 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first()); 2414 if (EndIt != LocDecls.end()) 2415 ++EndIt; 2416 2417 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt) 2418 Decls.push_back(DIt->second); 2419 } 2420 2421 SourceLocation ASTUnit::getLocation(const FileEntry *File, 2422 unsigned Line, unsigned Col) const { 2423 const SourceManager &SM = getSourceManager(); 2424 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col); 2425 return SM.getMacroArgExpandedLocation(Loc); 2426 } 2427 2428 SourceLocation ASTUnit::getLocation(const FileEntry *File, 2429 unsigned Offset) const { 2430 const SourceManager &SM = getSourceManager(); 2431 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1); 2432 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset)); 2433 } 2434 2435 /// \brief If \arg Loc is a loaded location from the preamble, returns 2436 /// the corresponding local location of the main file, otherwise it returns 2437 /// \arg Loc. 2438 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const { 2439 FileID PreambleID; 2440 if (SourceMgr) 2441 PreambleID = SourceMgr->getPreambleFileID(); 2442 2443 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid()) 2444 return Loc; 2445 2446 unsigned Offs; 2447 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) { 2448 SourceLocation FileLoc 2449 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID()); 2450 return FileLoc.getLocWithOffset(Offs); 2451 } 2452 2453 return Loc; 2454 } 2455 2456 /// \brief If \arg Loc is a local location of the main file but inside the 2457 /// preamble chunk, returns the corresponding loaded location from the 2458 /// preamble, otherwise it returns \arg Loc. 2459 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const { 2460 FileID PreambleID; 2461 if (SourceMgr) 2462 PreambleID = SourceMgr->getPreambleFileID(); 2463 2464 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid()) 2465 return Loc; 2466 2467 unsigned Offs; 2468 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) && 2469 Offs < Preamble->getBounds().Size) { 2470 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID); 2471 return FileLoc.getLocWithOffset(Offs); 2472 } 2473 2474 return Loc; 2475 } 2476 2477 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const { 2478 FileID FID; 2479 if (SourceMgr) 2480 FID = SourceMgr->getPreambleFileID(); 2481 2482 if (Loc.isInvalid() || FID.isInvalid()) 2483 return false; 2484 2485 return SourceMgr->isInFileID(Loc, FID); 2486 } 2487 2488 bool ASTUnit::isInMainFileID(SourceLocation Loc) const { 2489 FileID FID; 2490 if (SourceMgr) 2491 FID = SourceMgr->getMainFileID(); 2492 2493 if (Loc.isInvalid() || FID.isInvalid()) 2494 return false; 2495 2496 return SourceMgr->isInFileID(Loc, FID); 2497 } 2498 2499 SourceLocation ASTUnit::getEndOfPreambleFileID() const { 2500 FileID FID; 2501 if (SourceMgr) 2502 FID = SourceMgr->getPreambleFileID(); 2503 2504 if (FID.isInvalid()) 2505 return SourceLocation(); 2506 2507 return SourceMgr->getLocForEndOfFile(FID); 2508 } 2509 2510 SourceLocation ASTUnit::getStartOfMainFileID() const { 2511 FileID FID; 2512 if (SourceMgr) 2513 FID = SourceMgr->getMainFileID(); 2514 2515 if (FID.isInvalid()) 2516 return SourceLocation(); 2517 2518 return SourceMgr->getLocForStartOfFile(FID); 2519 } 2520 2521 llvm::iterator_range<PreprocessingRecord::iterator> 2522 ASTUnit::getLocalPreprocessingEntities() const { 2523 if (isMainFileAST()) { 2524 serialization::ModuleFile & 2525 Mod = Reader->getModuleManager().getPrimaryModule(); 2526 return Reader->getModulePreprocessedEntities(Mod); 2527 } 2528 2529 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) 2530 return llvm::make_range(PPRec->local_begin(), PPRec->local_end()); 2531 2532 return llvm::make_range(PreprocessingRecord::iterator(), 2533 PreprocessingRecord::iterator()); 2534 } 2535 2536 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) { 2537 if (isMainFileAST()) { 2538 serialization::ModuleFile & 2539 Mod = Reader->getModuleManager().getPrimaryModule(); 2540 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) { 2541 if (!Fn(context, D)) 2542 return false; 2543 } 2544 2545 return true; 2546 } 2547 2548 for (ASTUnit::top_level_iterator TL = top_level_begin(), 2549 TLEnd = top_level_end(); 2550 TL != TLEnd; ++TL) { 2551 if (!Fn(context, *TL)) 2552 return false; 2553 } 2554 2555 return true; 2556 } 2557 2558 const FileEntry *ASTUnit::getPCHFile() { 2559 if (!Reader) 2560 return nullptr; 2561 2562 serialization::ModuleFile *Mod = nullptr; 2563 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) { 2564 switch (M.Kind) { 2565 case serialization::MK_ImplicitModule: 2566 case serialization::MK_ExplicitModule: 2567 case serialization::MK_PrebuiltModule: 2568 return true; // skip dependencies. 2569 case serialization::MK_PCH: 2570 Mod = &M; 2571 return true; // found it. 2572 case serialization::MK_Preamble: 2573 return false; // look in dependencies. 2574 case serialization::MK_MainFile: 2575 return false; // look in dependencies. 2576 } 2577 2578 return true; 2579 }); 2580 if (Mod) 2581 return Mod->File; 2582 2583 return nullptr; 2584 } 2585 2586 bool ASTUnit::isModuleFile() const { 2587 return isMainFileAST() && getLangOpts().isCompilingModule(); 2588 } 2589 2590 InputKind ASTUnit::getInputKind() const { 2591 auto &LangOpts = getLangOpts(); 2592 2593 InputKind::Language Lang; 2594 if (LangOpts.OpenCL) 2595 Lang = InputKind::OpenCL; 2596 else if (LangOpts.CUDA) 2597 Lang = InputKind::CUDA; 2598 else if (LangOpts.RenderScript) 2599 Lang = InputKind::RenderScript; 2600 else if (LangOpts.CPlusPlus) 2601 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX; 2602 else 2603 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C; 2604 2605 InputKind::Format Fmt = InputKind::Source; 2606 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap) 2607 Fmt = InputKind::ModuleMap; 2608 2609 // We don't know if input was preprocessed. Assume not. 2610 bool PP = false; 2611 2612 return InputKind(Lang, Fmt, PP); 2613 } 2614 2615 #ifndef NDEBUG 2616 ASTUnit::ConcurrencyState::ConcurrencyState() { 2617 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true); 2618 } 2619 2620 ASTUnit::ConcurrencyState::~ConcurrencyState() { 2621 delete static_cast<llvm::sys::MutexImpl *>(Mutex); 2622 } 2623 2624 void ASTUnit::ConcurrencyState::start() { 2625 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire(); 2626 assert(acquired && "Concurrent access to ASTUnit!"); 2627 } 2628 2629 void ASTUnit::ConcurrencyState::finish() { 2630 static_cast<llvm::sys::MutexImpl *>(Mutex)->release(); 2631 } 2632 2633 #else // NDEBUG 2634 2635 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; } 2636 ASTUnit::ConcurrencyState::~ConcurrencyState() {} 2637 void ASTUnit::ConcurrencyState::start() {} 2638 void ASTUnit::ConcurrencyState::finish() {} 2639 2640 #endif // NDEBUG 2641