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