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