1 //===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // ASTUnit Implementation.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Frontend/ASTUnit.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CommentCommandTraits.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclGroup.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/Diagnostic.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/IdentifierTable.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/LangOptions.h"
33 #include "clang/Basic/LangStandard.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TargetOptions.h"
39 #include "clang/Frontend/CompilerInstance.h"
40 #include "clang/Frontend/CompilerInvocation.h"
41 #include "clang/Frontend/FrontendAction.h"
42 #include "clang/Frontend/FrontendActions.h"
43 #include "clang/Frontend/FrontendDiagnostic.h"
44 #include "clang/Frontend/FrontendOptions.h"
45 #include "clang/Frontend/MultiplexConsumer.h"
46 #include "clang/Frontend/PrecompiledPreamble.h"
47 #include "clang/Frontend/Utils.h"
48 #include "clang/Lex/HeaderSearch.h"
49 #include "clang/Lex/HeaderSearchOptions.h"
50 #include "clang/Lex/Lexer.h"
51 #include "clang/Lex/PPCallbacks.h"
52 #include "clang/Lex/PreprocessingRecord.h"
53 #include "clang/Lex/Preprocessor.h"
54 #include "clang/Lex/PreprocessorOptions.h"
55 #include "clang/Lex/Token.h"
56 #include "clang/Sema/CodeCompleteConsumer.h"
57 #include "clang/Sema/CodeCompleteOptions.h"
58 #include "clang/Sema/Sema.h"
59 #include "clang/Serialization/ASTBitCodes.h"
60 #include "clang/Serialization/ASTReader.h"
61 #include "clang/Serialization/ASTWriter.h"
62 #include "clang/Serialization/ContinuousRangeMap.h"
63 #include "clang/Serialization/InMemoryModuleCache.h"
64 #include "clang/Serialization/ModuleFile.h"
65 #include "clang/Serialization/PCHContainerOperations.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/IntrusiveRefCntPtr.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallString.h"
73 #include "llvm/ADT/SmallVector.h"
74 #include "llvm/ADT/StringMap.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/ADT/StringSet.h"
77 #include "llvm/ADT/Twine.h"
78 #include "llvm/ADT/iterator_range.h"
79 #include "llvm/Bitstream/BitstreamWriter.h"
80 #include "llvm/Support/Allocator.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CrashRecoveryContext.h"
83 #include "llvm/Support/DJB.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/ErrorOr.h"
86 #include "llvm/Support/FileSystem.h"
87 #include "llvm/Support/FileUtilities.h"
88 #include "llvm/Support/MemoryBuffer.h"
89 #include "llvm/Support/Timer.h"
90 #include "llvm/Support/VirtualFileSystem.h"
91 #include "llvm/Support/raw_ostream.h"
105 using namespace clang;
107 using llvm::TimeRecord;
117 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
119 Start = TimeRecord::getCurrentTime();
124 TimeRecord Elapsed = TimeRecord::getCurrentTime();
126 llvm::errs() << Output << ':';
127 Elapsed.print(Elapsed, llvm::errs());
128 llvm::errs() << '\n';
132 void setOutput(const Twine &Output) {
134 this->Output = Output.str();
141 static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
144 return std::move(*Val);
148 static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
151 Output = std::move(*Val);
155 /// Get a source buffer for \p MainFilePath, handling all file-to-file
156 /// and file-to-buffer remappings inside \p Invocation.
157 static std::unique_ptr<llvm::MemoryBuffer>
158 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
159 llvm::vfs::FileSystem *VFS,
160 StringRef FilePath, bool isVolatile) {
161 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
163 // Try to determine if the main file has been remapped, either from the
164 // command line (to another file) or directly through the compiler
165 // invocation (to a memory buffer).
166 llvm::MemoryBuffer *Buffer = nullptr;
167 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
168 auto FileStatus = VFS->status(FilePath);
170 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
172 // Check whether there is a file-file remapping of the main file
173 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
174 std::string MPath(RF.first);
175 auto MPathStatus = VFS->status(MPath);
177 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
178 if (MainFileID == MID) {
179 // We found a remapping. Try to load the resulting, remapped source.
180 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
187 // Check whether there is a file-buffer remapping. It supercedes the
188 // file-file remapping.
189 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
190 std::string MPath(RB.first);
191 auto MPathStatus = VFS->status(MPath);
193 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
194 if (MainFileID == MID) {
195 // We found a remapping.
197 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
203 // If the main source file was not remapped, load it now.
204 if (!Buffer && !BufferOwner) {
205 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
214 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
217 struct ASTUnit::ASTWriterData {
218 SmallString<128> Buffer;
219 llvm::BitstreamWriter Stream;
222 ASTWriterData(InMemoryModuleCache &ModuleCache)
223 : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
226 void ASTUnit::clearFileLevelDecls() {
227 llvm::DeleteContainerSeconds(FileDecls);
230 /// After failing to build a precompiled preamble (due to
231 /// errors in the source that occurs in the preamble), the number of
232 /// reparses during which we'll skip even trying to precompile the
234 const unsigned DefaultPreambleRebuildInterval = 5;
236 /// Tracks the number of ASTUnit objects that are currently active.
238 /// Used for debugging purposes only.
239 static std::atomic<unsigned> ActiveASTUnitObjects;
241 ASTUnit::ASTUnit(bool _MainFileIsAST)
242 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
243 ShouldCacheCodeCompletionResults(false),
244 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
245 UnsafeToFree(false) {
246 if (getenv("LIBCLANG_OBJTRACKING"))
247 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
250 ASTUnit::~ASTUnit() {
251 // If we loaded from an AST file, balance out the BeginSourceFile call.
252 if (MainFileIsAST && getDiagnostics().getClient()) {
253 getDiagnostics().getClient()->EndSourceFile();
256 clearFileLevelDecls();
258 // Free the buffers associated with remapped files. We are required to
259 // perform this operation here because we explicitly request that the
260 // compiler instance *not* free these buffers for each invocation of the
262 if (Invocation && OwnsRemappedFileBuffers) {
263 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
264 for (const auto &RB : PPOpts.RemappedFileBuffers)
268 ClearCachedCompletionResults();
270 if (getenv("LIBCLANG_OBJTRACKING"))
271 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
274 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
275 this->PP = std::move(PP);
278 void ASTUnit::enableSourceFileDiagnostics() {
279 assert(getDiagnostics().getClient() && Ctx &&
280 "Bad context for source file");
281 getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
284 /// Determine the set of code-completion contexts in which this
285 /// declaration should be shown.
286 static uint64_t getDeclShowContexts(const NamedDecl *ND,
287 const LangOptions &LangOpts,
288 bool &IsNestedNameSpecifier) {
289 IsNestedNameSpecifier = false;
291 if (isa<UsingShadowDecl>(ND))
292 ND = ND->getUnderlyingDecl();
296 uint64_t Contexts = 0;
297 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
298 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
299 isa<TypeAliasTemplateDecl>(ND)) {
300 // Types can appear in these contexts.
301 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
302 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
303 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
304 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
305 | (1LL << CodeCompletionContext::CCC_Statement)
306 | (1LL << CodeCompletionContext::CCC_Type)
307 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
309 // In C++, types can appear in expressions contexts (for functional casts).
310 if (LangOpts.CPlusPlus)
311 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
313 // In Objective-C, message sends can send interfaces. In Objective-C++,
314 // all types are available due to functional casts.
315 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
316 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
318 // In Objective-C, you can only be a subclass of another Objective-C class
319 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
320 // Objective-C interfaces can be used in a class property expression.
321 if (ID->getDefinition())
322 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
323 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
326 // Deal with tag names.
327 if (isa<EnumDecl>(ND)) {
328 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
330 // Part of the nested-name-specifier in C++0x.
331 if (LangOpts.CPlusPlus11)
332 IsNestedNameSpecifier = true;
333 } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
334 if (Record->isUnion())
335 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
337 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
339 if (LangOpts.CPlusPlus)
340 IsNestedNameSpecifier = true;
341 } else if (isa<ClassTemplateDecl>(ND))
342 IsNestedNameSpecifier = true;
343 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
344 // Values can appear in these contexts.
345 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
346 | (1LL << CodeCompletionContext::CCC_Expression)
347 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
348 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
349 } else if (isa<ObjCProtocolDecl>(ND)) {
350 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
351 } else if (isa<ObjCCategoryDecl>(ND)) {
352 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
353 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
354 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
356 // Part of the nested-name-specifier.
357 IsNestedNameSpecifier = true;
363 void ASTUnit::CacheCodeCompletionResults() {
367 SimpleTimer Timer(WantTiming);
368 Timer.setOutput("Cache global code completions for " + getMainFileName());
370 // Clear out the previous results.
371 ClearCachedCompletionResults();
373 // Gather the set of global code completions.
374 using Result = CodeCompletionResult;
375 SmallVector<Result, 8> Results;
376 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
377 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
378 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
381 // Translate global code completions into cached completions.
382 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
383 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
385 for (auto &R : Results) {
387 case Result::RK_Declaration: {
388 bool IsNestedNameSpecifier = false;
389 CachedCodeCompletionResult CachedResult;
390 CachedResult.Completion = R.CreateCodeCompletionString(
391 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
392 IncludeBriefCommentsInCodeCompletion);
393 CachedResult.ShowInContexts = getDeclShowContexts(
394 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
395 CachedResult.Priority = R.Priority;
396 CachedResult.Kind = R.CursorKind;
397 CachedResult.Availability = R.Availability;
399 // Keep track of the type of this completion in an ASTContext-agnostic
401 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
402 if (UsageType.isNull()) {
403 CachedResult.TypeClass = STC_Void;
404 CachedResult.Type = 0;
406 CanQualType CanUsageType
407 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
408 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
410 // Determine whether we have already seen this type. If so, we save
411 // ourselves the work of formatting the type string by using the
412 // temporary, CanQualType-based hash table to find the associated value.
413 unsigned &TypeValue = CompletionTypes[CanUsageType];
414 if (TypeValue == 0) {
415 TypeValue = CompletionTypes.size();
416 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
420 CachedResult.Type = TypeValue;
423 CachedCompletionResults.push_back(CachedResult);
425 /// Handle nested-name-specifiers in C++.
426 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
427 !R.StartsNestedNameSpecifier) {
428 // The contexts in which a nested-name-specifier can appear in C++.
430 = (1LL << CodeCompletionContext::CCC_TopLevel)
431 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
432 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
433 | (1LL << CodeCompletionContext::CCC_Statement)
434 | (1LL << CodeCompletionContext::CCC_Expression)
435 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
436 | (1LL << CodeCompletionContext::CCC_EnumTag)
437 | (1LL << CodeCompletionContext::CCC_UnionTag)
438 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
439 | (1LL << CodeCompletionContext::CCC_Type)
440 | (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
441 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
443 if (isa<NamespaceDecl>(R.Declaration) ||
444 isa<NamespaceAliasDecl>(R.Declaration))
445 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
447 if (uint64_t RemainingContexts
448 = NNSContexts & ~CachedResult.ShowInContexts) {
449 // If there any contexts where this completion can be a
450 // nested-name-specifier but isn't already an option, create a
451 // nested-name-specifier completion.
452 R.StartsNestedNameSpecifier = true;
453 CachedResult.Completion = R.CreateCodeCompletionString(
454 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
455 IncludeBriefCommentsInCodeCompletion);
456 CachedResult.ShowInContexts = RemainingContexts;
457 CachedResult.Priority = CCP_NestedNameSpecifier;
458 CachedResult.TypeClass = STC_Void;
459 CachedResult.Type = 0;
460 CachedCompletionResults.push_back(CachedResult);
466 case Result::RK_Keyword:
467 case Result::RK_Pattern:
468 // Ignore keywords and patterns; we don't care, since they are so
469 // easily regenerated.
472 case Result::RK_Macro: {
473 CachedCodeCompletionResult CachedResult;
474 CachedResult.Completion = R.CreateCodeCompletionString(
475 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
476 IncludeBriefCommentsInCodeCompletion);
477 CachedResult.ShowInContexts
478 = (1LL << CodeCompletionContext::CCC_TopLevel)
479 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
480 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
481 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
482 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
483 | (1LL << CodeCompletionContext::CCC_Statement)
484 | (1LL << CodeCompletionContext::CCC_Expression)
485 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
486 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
487 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
488 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
489 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
491 CachedResult.Priority = R.Priority;
492 CachedResult.Kind = R.CursorKind;
493 CachedResult.Availability = R.Availability;
494 CachedResult.TypeClass = STC_Void;
495 CachedResult.Type = 0;
496 CachedCompletionResults.push_back(CachedResult);
502 // Save the current top-level hash value.
503 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
506 void ASTUnit::ClearCachedCompletionResults() {
507 CachedCompletionResults.clear();
508 CachedCompletionTypes.clear();
509 CachedCompletionAllocator = nullptr;
514 /// Gathers information from ASTReader that will be used to initialize
516 class ASTInfoCollector : public ASTReaderListener {
519 HeaderSearchOptions &HSOpts;
520 PreprocessorOptions &PPOpts;
521 LangOptions &LangOpt;
522 std::shared_ptr<TargetOptions> &TargetOpts;
523 IntrusiveRefCntPtr<TargetInfo> &Target;
525 bool InitializedLanguage = false;
528 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
529 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
530 LangOptions &LangOpt,
531 std::shared_ptr<TargetOptions> &TargetOpts,
532 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
533 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
534 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
537 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
538 bool AllowCompatibleDifferences) override {
539 if (InitializedLanguage)
543 InitializedLanguage = true;
549 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
550 StringRef SpecificModuleCachePath,
551 bool Complain) override {
552 this->HSOpts = HSOpts;
556 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
557 std::string &SuggestedPredefines) override {
558 this->PPOpts = PPOpts;
562 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
563 bool AllowCompatibleDifferences) override {
564 // If we've already initialized the target, don't do it again.
568 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
570 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
576 void ReadCounter(const serialization::ModuleFile &M,
577 unsigned Value) override {
583 if (!Target || !InitializedLanguage)
586 // Inform the target of the language options.
588 // FIXME: We shouldn't need to do this, the target should be immutable once
589 // created. This complexity should be lifted elsewhere.
590 Target->adjust(LangOpt);
592 // Initialize the preprocessor.
593 PP.Initialize(*Target);
598 // Initialize the ASTContext
599 Context->InitBuiltinTypes(*Target);
601 // Adjust printing policy based on language options.
602 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
604 // We didn't have access to the comment options when the ASTContext was
605 // constructed, so register them now.
606 Context->getCommentCommandTraits().registerCommentOptions(
607 LangOpt.CommentOpts);
611 /// Diagnostic consumer that saves each diagnostic it is given.
612 class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
613 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
614 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
615 bool CaptureNonErrorsFromIncludes = true;
616 const LangOptions *LangOpts = nullptr;
617 SourceManager *SourceMgr = nullptr;
620 FilterAndStoreDiagnosticConsumer(
621 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
622 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags,
623 bool CaptureNonErrorsFromIncludes)
624 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
625 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
626 assert((StoredDiags || StandaloneDiags) &&
627 "No output collections were passed to StoredDiagnosticConsumer.");
630 void BeginSourceFile(const LangOptions &LangOpts,
631 const Preprocessor *PP = nullptr) override {
632 this->LangOpts = &LangOpts;
634 SourceMgr = &PP->getSourceManager();
637 void HandleDiagnostic(DiagnosticsEngine::Level Level,
638 const Diagnostic &Info) override;
641 /// RAII object that optionally captures and filters diagnostics, if
642 /// there is no diagnostic client to capture them already.
643 class CaptureDroppedDiagnostics {
644 DiagnosticsEngine &Diags;
645 FilterAndStoreDiagnosticConsumer Client;
646 DiagnosticConsumer *PreviousClient = nullptr;
647 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
650 CaptureDroppedDiagnostics(
651 CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
652 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
653 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
655 Client(StoredDiags, StandaloneDiags,
656 CaptureDiagnostics !=
657 CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) {
658 if (CaptureDiagnostics != CaptureDiagsKind::None ||
659 Diags.getClient() == nullptr) {
660 OwningPreviousClient = Diags.takeClient();
661 PreviousClient = Diags.getClient();
662 Diags.setClient(&Client, false);
666 ~CaptureDroppedDiagnostics() {
667 if (Diags.getClient() == &Client)
668 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
674 static ASTUnit::StandaloneDiagnostic
675 makeStandaloneDiagnostic(const LangOptions &LangOpts,
676 const StoredDiagnostic &InDiag);
678 static bool isInMainFile(const clang::Diagnostic &D) {
679 if (!D.hasSourceManager() || !D.getLocation().isValid())
682 auto &M = D.getSourceManager();
683 return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
686 void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
687 DiagnosticsEngine::Level Level, const Diagnostic &Info) {
688 // Default implementation (Warnings/errors count).
689 DiagnosticConsumer::HandleDiagnostic(Level, Info);
691 // Only record the diagnostic if it's part of the source manager we know
692 // about. This effectively drops diagnostics from modules we're building.
693 // FIXME: In the long run, ee don't want to drop source managers from modules.
694 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
695 if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning &&
696 !isInMainFile(Info)) {
700 StoredDiagnostic *ResultDiag = nullptr;
702 StoredDiags->emplace_back(Level, Info);
703 ResultDiag = &StoredDiags->back();
706 if (StandaloneDiags) {
707 llvm::Optional<StoredDiagnostic> StoredDiag = None;
709 StoredDiag.emplace(Level, Info);
710 ResultDiag = StoredDiag.getPointer();
712 StandaloneDiags->push_back(
713 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
718 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
722 ASTMutationListener *ASTUnit::getASTMutationListener() {
724 return &WriterData->Writer;
728 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
730 return &WriterData->Writer;
734 std::unique_ptr<llvm::MemoryBuffer>
735 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
737 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
739 return std::move(*Buffer);
741 *ErrorStr = Buffer.getError().message();
745 /// Configure the diagnostics object for use with ASTUnit.
746 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
748 CaptureDiagsKind CaptureDiagnostics) {
749 assert(Diags.get() && "no DiagnosticsEngine was provided");
750 if (CaptureDiagnostics != CaptureDiagsKind::None)
751 Diags->setClient(new FilterAndStoreDiagnosticConsumer(
752 &AST.StoredDiagnostics, nullptr,
753 CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes));
756 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
757 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
758 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
759 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
760 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
761 CaptureDiagsKind CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
762 bool UserFilesAreVolatile) {
763 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
765 // Recover resources if we crash before exiting this method.
766 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
767 ASTUnitCleanup(AST.get());
768 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
769 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
770 DiagCleanup(Diags.get());
772 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
774 AST->LangOpts = std::make_shared<LangOptions>();
775 AST->OnlyLocalDecls = OnlyLocalDecls;
776 AST->CaptureDiagnostics = CaptureDiagnostics;
777 AST->Diagnostics = Diags;
778 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
779 llvm::vfs::getRealFileSystem();
780 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
781 AST->UserFilesAreVolatile = UserFilesAreVolatile;
782 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
783 AST->getFileManager(),
784 UserFilesAreVolatile);
785 AST->ModuleCache = new InMemoryModuleCache;
786 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
787 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
788 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
789 AST->getSourceManager(),
790 AST->getDiagnostics(),
792 /*Target=*/nullptr));
793 AST->PPOpts = std::make_shared<PreprocessorOptions>();
795 for (const auto &RemappedFile : RemappedFiles)
796 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
798 // Gather Info for preprocessor construction later on.
800 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
803 AST->PP = std::make_shared<Preprocessor>(
804 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
805 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
806 /*IILookup=*/nullptr,
807 /*OwnsHeaderSearch=*/false);
808 Preprocessor &PP = *AST->PP;
810 if (ToLoad >= LoadASTOnly)
811 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
812 PP.getIdentifierTable(), PP.getSelectorTable(),
813 PP.getBuiltinInfo());
815 bool disableValid = false;
816 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
818 AST->Reader = new ASTReader(
819 PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
821 /*DisableValidation=*/disableValid, AllowPCHWithCompilerErrors);
823 AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
824 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
825 AST->TargetOpts, AST->Target, Counter));
827 // Attach the AST reader to the AST context as an external AST
828 // source, so that declarations will be deserialized from the
829 // AST file as needed.
830 // We need the external source to be set up before we read the AST, because
831 // eagerly-deserialized declarations may use it.
833 AST->Ctx->setExternalSource(AST->Reader);
835 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
836 SourceLocation(), ASTReader::ARR_None)) {
837 case ASTReader::Success:
840 case ASTReader::Failure:
841 case ASTReader::Missing:
842 case ASTReader::OutOfDate:
843 case ASTReader::VersionMismatch:
844 case ASTReader::ConfigurationMismatch:
845 case ASTReader::HadErrors:
846 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
850 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
852 PP.setCounterValue(Counter);
854 // Create an AST consumer, even though it isn't used.
855 if (ToLoad >= LoadASTOnly)
856 AST->Consumer.reset(new ASTConsumer);
858 // Create a semantic analysis object and tell the AST reader about it.
859 if (ToLoad >= LoadEverything) {
860 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
861 AST->TheSema->Initialize();
862 AST->Reader->InitializeSema(*AST->TheSema);
865 // Tell the diagnostic client that we have started a source file.
866 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
871 /// Add the given macro to the hash of all top-level entities.
872 static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
873 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
878 /// Preprocessor callback class that updates a hash value with the names
879 /// of all macros that have been defined by the translation unit.
880 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
884 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
886 void MacroDefined(const Token &MacroNameTok,
887 const MacroDirective *MD) override {
888 AddDefinedMacroToHash(MacroNameTok, Hash);
894 /// Add the given declaration to the hash of all top-level entities.
895 static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
899 DeclContext *DC = D->getDeclContext();
903 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
906 if (const auto *ND = dyn_cast<NamedDecl>(D)) {
907 if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
908 // For an unscoped enum include the enumerators in the hash since they
909 // enter the top-level namespace.
910 if (!EnumD->isScoped()) {
911 for (const auto *EI : EnumD->enumerators()) {
912 if (EI->getIdentifier())
913 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
918 if (ND->getIdentifier())
919 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
920 else if (DeclarationName Name = ND->getDeclName()) {
921 std::string NameStr = Name.getAsString();
922 Hash = llvm::djbHash(NameStr, Hash);
927 if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
928 if (const Module *Mod = ImportD->getImportedModule()) {
929 std::string ModName = Mod->getFullModuleName();
930 Hash = llvm::djbHash(ModName, Hash);
938 class TopLevelDeclTrackerConsumer : public ASTConsumer {
943 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
944 : Unit(_Unit), Hash(Hash) {
948 void handleTopLevelDecl(Decl *D) {
952 // FIXME: Currently ObjC method declarations are incorrectly being
953 // reported as top-level declarations, even though their DeclContext
954 // is the containing ObjC @interface/@implementation. This is a
955 // fundamental problem in the parser right now.
956 if (isa<ObjCMethodDecl>(D))
959 AddTopLevelDeclarationToHash(D, Hash);
960 Unit.addTopLevelDecl(D);
962 handleFileLevelDecl(D);
965 void handleFileLevelDecl(Decl *D) {
966 Unit.addFileLevelDecl(D);
967 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
968 for (auto *I : NSD->decls())
969 handleFileLevelDecl(I);
973 bool HandleTopLevelDecl(DeclGroupRef D) override {
974 for (auto *TopLevelDecl : D)
975 handleTopLevelDecl(TopLevelDecl);
979 // We're not interested in "interesting" decls.
980 void HandleInterestingDecl(DeclGroupRef) override {}
982 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
983 for (auto *TopLevelDecl : D)
984 handleTopLevelDecl(TopLevelDecl);
987 ASTMutationListener *GetASTMutationListener() override {
988 return Unit.getASTMutationListener();
991 ASTDeserializationListener *GetASTDeserializationListener() override {
992 return Unit.getDeserializationListener();
996 class TopLevelDeclTrackerAction : public ASTFrontendAction {
1000 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
1001 StringRef InFile) override {
1002 CI.getPreprocessor().addPPCallbacks(
1003 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1004 Unit.getCurrentTopLevelHashValue()));
1005 return std::make_unique<TopLevelDeclTrackerConsumer>(
1006 Unit, Unit.getCurrentTopLevelHashValue());
1010 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1012 bool hasCodeCompletionSupport() const override { return false; }
1014 TranslationUnitKind getTranslationUnitKind() override {
1015 return Unit.getTranslationUnitKind();
1019 class ASTUnitPreambleCallbacks : public PreambleCallbacks {
1021 unsigned getHash() const { return Hash; }
1023 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
1025 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1026 return std::move(TopLevelDeclIDs);
1029 void AfterPCHEmitted(ASTWriter &Writer) override {
1030 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1031 for (const auto *D : TopLevelDecls) {
1032 // Invalid top-level decls may not have been serialized.
1033 if (D->isInvalidDecl())
1035 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1039 void HandleTopLevelDecl(DeclGroupRef DG) override {
1040 for (auto *D : DG) {
1041 // FIXME: Currently ObjC method declarations are incorrectly being
1042 // reported as top-level declarations, even though their DeclContext
1043 // is the containing ObjC @interface/@implementation. This is a
1044 // fundamental problem in the parser right now.
1045 if (isa<ObjCMethodDecl>(D))
1047 AddTopLevelDeclarationToHash(D, Hash);
1048 TopLevelDecls.push_back(D);
1052 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1053 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1058 std::vector<Decl *> TopLevelDecls;
1059 std::vector<serialization::DeclID> TopLevelDeclIDs;
1060 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
1065 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1066 return StoredDiag.getLocation().isValid();
1070 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1071 // Get rid of stored diagnostics except the ones from the driver which do not
1072 // have a source location.
1074 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1078 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1080 SourceManager &SM) {
1081 // The stored diagnostic has the old source manager in it; update
1082 // the locations to refer into the new source manager. Since we've
1083 // been careful to make sure that the source manager's state
1084 // before and after are identical, so that we can reuse the source
1086 for (auto &SD : StoredDiagnostics) {
1087 if (SD.getLocation().isValid()) {
1088 FullSourceLoc Loc(SD.getLocation(), SM);
1089 SD.setLocation(Loc);
1094 /// Parse the source file into a translation unit using the given compiler
1095 /// invocation, replacing the current translation unit.
1097 /// \returns True if a failure occurred that causes the ASTUnit not to
1098 /// contain any translation-unit information, false otherwise.
1099 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1100 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1101 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1106 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1107 "VFS passed to Parse and VFS in FileMgr are different");
1109 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1110 if (OverrideMainBuffer) {
1112 "No preamble was built, but OverrideMainBuffer is not null");
1113 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1114 // VFS may have changed...
1117 // Create the compiler instance to use for building the AST.
1118 std::unique_ptr<CompilerInstance> Clang(
1119 new CompilerInstance(std::move(PCHContainerOps)));
1121 // Ensure that Clang has a FileManager with the right VFS, which may have
1122 // changed above in AddImplicitPreamble. If VFS is nullptr, rely on
1123 // createFileManager to create one.
1124 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
1125 Clang->setFileManager(&*FileMgr);
1127 FileMgr = Clang->createFileManager(std::move(VFS));
1129 // Recover resources if we crash before exiting this method.
1130 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1131 CICleanup(Clang.get());
1133 Clang->setInvocation(CCInvocation);
1134 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1136 // Set up diagnostics, capturing any diagnostics that would
1137 // otherwise be dropped.
1138 Clang->setDiagnostics(&getDiagnostics());
1140 // Create the target instance.
1141 Clang->setTarget(TargetInfo::CreateTargetInfo(
1142 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1143 if (!Clang->hasTarget())
1146 // Inform the target of the language options.
1148 // FIXME: We shouldn't need to do this, the target should be immutable once
1149 // created. This complexity should be lifted elsewhere.
1150 Clang->getTarget().adjust(Clang->getLangOpts());
1152 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1153 "Invocation must have exactly one source file!");
1154 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1155 InputKind::Source &&
1156 "FIXME: AST inputs not yet supported here!");
1157 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1158 Language::LLVM_IR &&
1159 "IR inputs not support here!");
1161 // Configure the various subsystems.
1162 LangOpts = Clang->getInvocation().LangOpts;
1163 FileSystemOpts = Clang->getFileSystemOpts();
1167 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1168 UserFilesAreVolatile);
1169 if (!OverrideMainBuffer) {
1170 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1171 TopLevelDeclsInPreamble.clear();
1174 // Create a file manager object to provide access to and cache the filesystem.
1175 Clang->setFileManager(&getFileManager());
1177 // Create the source manager.
1178 Clang->setSourceManager(&getSourceManager());
1180 // If the main file has been overridden due to the use of a preamble,
1181 // make that override happen and introduce the preamble.
1182 if (OverrideMainBuffer) {
1183 // The stored diagnostic has the old source manager in it; update
1184 // the locations to refer into the new source manager. Since we've
1185 // been careful to make sure that the source manager's state
1186 // before and after are identical, so that we can reuse the source
1188 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1190 // Keep track of the override buffer;
1191 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1194 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1195 new TopLevelDeclTrackerAction(*this));
1197 // Recover resources if we crash before exiting this method.
1198 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1199 ActCleanup(Act.get());
1201 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1204 if (SavedMainFileBuffer)
1205 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1206 PreambleDiagnostics, StoredDiagnostics);
1208 PreambleSrcLocCache.clear();
1210 if (llvm::Error Err = Act->Execute()) {
1211 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1215 transferASTDataFromCompilerInstance(*Clang);
1217 Act->EndSourceFile();
1219 FailedParseDiagnostics.clear();
1224 // Remove the overridden buffer we used for the preamble.
1225 SavedMainFileBuffer = nullptr;
1227 // Keep the ownership of the data in the ASTUnit because the client may
1228 // want to see the diagnostics.
1229 transferASTDataFromCompilerInstance(*Clang);
1230 FailedParseDiagnostics.swap(StoredDiagnostics);
1231 StoredDiagnostics.clear();
1232 NumStoredDiagnosticsFromDriver = 0;
1236 static std::pair<unsigned, unsigned>
1237 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1238 const LangOptions &LangOpts) {
1239 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1240 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1241 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1242 return std::make_pair(Offset, EndOffset);
1245 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1246 const LangOptions &LangOpts,
1247 const FixItHint &InFix) {
1248 ASTUnit::StandaloneFixIt OutFix;
1249 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1250 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1252 OutFix.CodeToInsert = InFix.CodeToInsert;
1253 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1257 static ASTUnit::StandaloneDiagnostic
1258 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1259 const StoredDiagnostic &InDiag) {
1260 ASTUnit::StandaloneDiagnostic OutDiag;
1261 OutDiag.ID = InDiag.getID();
1262 OutDiag.Level = InDiag.getLevel();
1263 OutDiag.Message = InDiag.getMessage();
1264 OutDiag.LocOffset = 0;
1265 if (InDiag.getLocation().isInvalid())
1267 const SourceManager &SM = InDiag.getLocation().getManager();
1268 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1269 OutDiag.Filename = SM.getFilename(FileLoc);
1270 if (OutDiag.Filename.empty())
1272 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1273 for (const auto &Range : InDiag.getRanges())
1274 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1275 for (const auto &FixIt : InDiag.getFixIts())
1276 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1281 /// Attempt to build or re-use a precompiled preamble when (re-)parsing
1282 /// the source file.
1284 /// This routine will compute the preamble of the main source file. If a
1285 /// non-trivial preamble is found, it will precompile that preamble into a
1286 /// precompiled header so that the precompiled preamble can be used to reduce
1287 /// reparsing time. If a precompiled preamble has already been constructed,
1288 /// this routine will determine if it is still valid and, if so, avoid
1289 /// rebuilding the precompiled preamble.
1291 /// \param AllowRebuild When true (the default), this routine is
1292 /// allowed to rebuild the precompiled preamble if it is found to be
1295 /// \param MaxLines When non-zero, the maximum number of lines that
1296 /// can occur within the preamble.
1298 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1299 /// buffer that should be used in place of the main file when doing so.
1300 /// Otherwise, returns a NULL pointer.
1301 std::unique_ptr<llvm::MemoryBuffer>
1302 ASTUnit::getMainBufferWithPrecompiledPreamble(
1303 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1304 CompilerInvocation &PreambleInvocationIn,
1305 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
1306 unsigned MaxLines) {
1308 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1309 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1310 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1311 MainFilePath, UserFilesAreVolatile);
1312 if (!MainFileBuffer)
1315 PreambleBounds Bounds =
1316 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1317 MainFileBuffer.get(), MaxLines);
1322 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1324 // Okay! We can re-use the precompiled preamble.
1326 // Set the state of the diagnostic object to mimic its state
1327 // after parsing the preamble.
1328 getDiagnostics().Reset();
1329 ProcessWarningOptions(getDiagnostics(),
1330 PreambleInvocationIn.getDiagnosticOpts());
1331 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1333 PreambleRebuildCountdown = 1;
1334 return MainFileBuffer;
1337 PreambleDiagnostics.clear();
1338 TopLevelDeclsInPreamble.clear();
1339 PreambleSrcLocCache.clear();
1340 PreambleRebuildCountdown = 1;
1344 // If the preamble rebuild counter > 1, it's because we previously
1345 // failed to build a preamble and we're not yet ready to try
1346 // again. Decrement the counter and return a failure.
1347 if (PreambleRebuildCountdown > 1) {
1348 --PreambleRebuildCountdown;
1352 assert(!Preamble && "No Preamble should be stored at that point");
1353 // If we aren't allowed to rebuild the precompiled preamble, just
1360 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1361 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1362 ASTUnitPreambleCallbacks Callbacks;
1364 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1365 if (CaptureDiagnostics != CaptureDiagsKind::None)
1366 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1367 &NewPreambleDiagsStandalone);
1369 // We did not previously compute a preamble, or it can't be reused anyway.
1370 SimpleTimer PreambleTimer(WantTiming);
1371 PreambleTimer.setOutput("Precompiling preamble");
1373 const bool PreviousSkipFunctionBodies =
1374 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1375 if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1376 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1378 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1379 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1380 PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
1382 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1383 PreviousSkipFunctionBodies;
1386 Preamble = std::move(*NewPreamble);
1387 PreambleRebuildCountdown = 1;
1389 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1390 case BuildPreambleError::CouldntCreateTempFile:
1391 // Try again next time.
1392 PreambleRebuildCountdown = 1;
1394 case BuildPreambleError::CouldntCreateTargetInfo:
1395 case BuildPreambleError::BeginSourceFileFailed:
1396 case BuildPreambleError::CouldntEmitPCH:
1397 case BuildPreambleError::BadInputs:
1398 // These erros are more likely to repeat, retry after some period.
1399 PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
1402 llvm_unreachable("unexpected BuildPreambleError");
1406 assert(Preamble && "Preamble wasn't built");
1408 TopLevelDecls.clear();
1409 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1410 PreambleTopLevelHashValue = Callbacks.getHash();
1412 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1414 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1415 StoredDiagnostics = std::move(NewPreambleDiags);
1416 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1418 // If the hash of top-level entities differs from the hash of the top-level
1419 // entities the last time we rebuilt the preamble, clear out the completion
1421 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1422 CompletionCacheTopLevelHashValue = 0;
1423 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1426 return MainFileBuffer;
1429 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1430 assert(Preamble && "Should only be called when preamble was built");
1432 std::vector<Decl *> Resolved;
1433 Resolved.reserve(TopLevelDeclsInPreamble.size());
1434 ExternalASTSource &Source = *getASTContext().getExternalSource();
1435 for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1436 // Resolve the declaration ID to an actual declaration, possibly
1437 // deserializing the declaration in the process.
1438 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1439 Resolved.push_back(D);
1441 TopLevelDeclsInPreamble.clear();
1442 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1445 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1446 // Steal the created target, context, and preprocessor if they have been
1448 assert(CI.hasInvocation() && "missing invocation");
1449 LangOpts = CI.getInvocation().LangOpts;
1450 TheSema = CI.takeSema();
1451 Consumer = CI.takeASTConsumer();
1452 if (CI.hasASTContext())
1453 Ctx = &CI.getASTContext();
1454 if (CI.hasPreprocessor())
1455 PP = CI.getPreprocessorPtr();
1456 CI.setSourceManager(nullptr);
1457 CI.setFileManager(nullptr);
1459 Target = &CI.getTarget();
1460 Reader = CI.getASTReader();
1461 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1464 StringRef ASTUnit::getMainFileName() const {
1465 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1466 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1468 return Input.getFile();
1470 return Input.getBuffer()->getBufferIdentifier();
1474 if (const FileEntry *
1475 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1476 return FE->getName();
1482 StringRef ASTUnit::getASTFileName() const {
1483 if (!isMainFileAST())
1486 serialization::ModuleFile &
1487 Mod = Reader->getModuleManager().getPrimaryModule();
1488 return Mod.FileName;
1491 std::unique_ptr<ASTUnit>
1492 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1493 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1494 CaptureDiagsKind CaptureDiagnostics,
1495 bool UserFilesAreVolatile) {
1496 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1497 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1498 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1499 createVFSFromCompilerInvocation(*CI, *Diags);
1500 AST->Diagnostics = Diags;
1501 AST->FileSystemOpts = CI->getFileSystemOpts();
1502 AST->Invocation = std::move(CI);
1503 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1504 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1505 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1506 UserFilesAreVolatile);
1507 AST->ModuleCache = new InMemoryModuleCache;
1512 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1513 std::shared_ptr<CompilerInvocation> CI,
1514 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1515 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1516 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1517 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1518 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1519 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1520 std::unique_ptr<ASTUnit> *ErrAST) {
1521 assert(CI && "A CompilerInvocation is required");
1523 std::unique_ptr<ASTUnit> OwnAST;
1524 ASTUnit *AST = Unit;
1526 // Create the AST unit.
1527 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1533 if (!ResourceFilesPath.empty()) {
1534 // Override the resources path.
1535 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1537 AST->OnlyLocalDecls = OnlyLocalDecls;
1538 AST->CaptureDiagnostics = CaptureDiagnostics;
1539 if (PrecompilePreambleAfterNParses > 0)
1540 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1541 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1542 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1543 AST->IncludeBriefCommentsInCodeCompletion
1544 = IncludeBriefCommentsInCodeCompletion;
1546 // Recover resources if we crash before exiting this method.
1547 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1548 ASTUnitCleanup(OwnAST.get());
1549 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1550 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1551 DiagCleanup(Diags.get());
1553 // We'll manage file buffers ourselves.
1554 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1555 CI->getFrontendOpts().DisableFree = false;
1556 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1558 // Create the compiler instance to use for building the AST.
1559 std::unique_ptr<CompilerInstance> Clang(
1560 new CompilerInstance(std::move(PCHContainerOps)));
1562 // Recover resources if we crash before exiting this method.
1563 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1564 CICleanup(Clang.get());
1566 Clang->setInvocation(std::move(CI));
1567 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1569 // Set up diagnostics, capturing any diagnostics that would
1570 // otherwise be dropped.
1571 Clang->setDiagnostics(&AST->getDiagnostics());
1573 // Create the target instance.
1574 Clang->setTarget(TargetInfo::CreateTargetInfo(
1575 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1576 if (!Clang->hasTarget())
1579 // Inform the target of the language options.
1581 // FIXME: We shouldn't need to do this, the target should be immutable once
1582 // created. This complexity should be lifted elsewhere.
1583 Clang->getTarget().adjust(Clang->getLangOpts());
1585 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1586 "Invocation must have exactly one source file!");
1587 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1588 InputKind::Source &&
1589 "FIXME: AST inputs not yet supported here!");
1590 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1591 Language::LLVM_IR &&
1592 "IR inputs not support here!");
1594 // Configure the various subsystems.
1595 AST->TheSema.reset();
1598 AST->Reader = nullptr;
1600 // Create a file manager object to provide access to and cache the filesystem.
1601 Clang->setFileManager(&AST->getFileManager());
1603 // Create the source manager.
1604 Clang->setSourceManager(&AST->getSourceManager());
1606 FrontendAction *Act = Action;
1608 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1610 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1611 Act = TrackerAct.get();
1614 // Recover resources if we crash before exiting this method.
1615 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1616 ActCleanup(TrackerAct.get());
1618 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1619 AST->transferASTDataFromCompilerInstance(*Clang);
1620 if (OwnAST && ErrAST)
1621 ErrAST->swap(OwnAST);
1626 if (Persistent && !TrackerAct) {
1627 Clang->getPreprocessor().addPPCallbacks(
1628 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1629 AST->getCurrentTopLevelHashValue()));
1630 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1631 if (Clang->hasASTConsumer())
1632 Consumers.push_back(Clang->takeASTConsumer());
1633 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1634 *AST, AST->getCurrentTopLevelHashValue()));
1635 Clang->setASTConsumer(
1636 std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1638 if (llvm::Error Err = Act->Execute()) {
1639 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1640 AST->transferASTDataFromCompilerInstance(*Clang);
1641 if (OwnAST && ErrAST)
1642 ErrAST->swap(OwnAST);
1647 // Steal the created target, context, and preprocessor.
1648 AST->transferASTDataFromCompilerInstance(*Clang);
1650 Act->EndSourceFile();
1653 return OwnAST.release();
1658 bool ASTUnit::LoadFromCompilerInvocation(
1659 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1660 unsigned PrecompilePreambleAfterNParses,
1661 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1665 assert(VFS && "VFS is null");
1667 // We'll manage file buffers ourselves.
1668 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1669 Invocation->getFrontendOpts().DisableFree = false;
1670 getDiagnostics().Reset();
1671 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1673 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1674 if (PrecompilePreambleAfterNParses > 0) {
1675 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1676 OverrideMainBuffer =
1677 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1678 getDiagnostics().Reset();
1679 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1682 SimpleTimer ParsingTimer(WantTiming);
1683 ParsingTimer.setOutput("Parsing " + getMainFileName());
1685 // Recover resources if we crash before exiting this method.
1686 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1687 MemBufferCleanup(OverrideMainBuffer.get());
1689 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1692 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1693 std::shared_ptr<CompilerInvocation> CI,
1694 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1695 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1696 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1697 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1698 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1699 bool UserFilesAreVolatile) {
1700 // Create the AST unit.
1701 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1702 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1703 AST->Diagnostics = Diags;
1704 AST->OnlyLocalDecls = OnlyLocalDecls;
1705 AST->CaptureDiagnostics = CaptureDiagnostics;
1706 AST->TUKind = TUKind;
1707 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1708 AST->IncludeBriefCommentsInCodeCompletion
1709 = IncludeBriefCommentsInCodeCompletion;
1710 AST->Invocation = std::move(CI);
1711 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1712 AST->FileMgr = FileMgr;
1713 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1715 // Recover resources if we crash before exiting this method.
1716 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1717 ASTUnitCleanup(AST.get());
1718 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1719 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1720 DiagCleanup(Diags.get());
1722 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1723 PrecompilePreambleAfterNParses,
1724 &AST->FileMgr->getVirtualFileSystem()))
1729 ASTUnit *ASTUnit::LoadFromCommandLine(
1730 const char **ArgBegin, const char **ArgEnd,
1731 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1732 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1733 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1734 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1735 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1736 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1737 bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
1738 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1739 bool RetainExcludedConditionalBlocks,
1740 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1741 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1742 assert(Diags.get() && "no DiagnosticsEngine was provided");
1744 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1746 std::shared_ptr<CompilerInvocation> CI;
1749 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1750 &StoredDiagnostics, nullptr);
1752 CI = createInvocationFromCommandLine(
1753 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1758 // Override any files that need remapping
1759 for (const auto &RemappedFile : RemappedFiles) {
1760 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1761 RemappedFile.second);
1763 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1764 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1765 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1766 PPOpts.SingleFileParseMode = SingleFileParse;
1767 PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
1769 // Override the resources path.
1770 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1772 CI->getFrontendOpts().SkipFunctionBodies =
1773 SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
1776 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1778 // Create the AST unit.
1779 std::unique_ptr<ASTUnit> AST;
1780 AST.reset(new ASTUnit(false));
1781 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1782 AST->StoredDiagnostics.swap(StoredDiagnostics);
1783 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1784 AST->Diagnostics = Diags;
1785 AST->FileSystemOpts = CI->getFileSystemOpts();
1787 VFS = llvm::vfs::getRealFileSystem();
1788 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1789 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1790 AST->ModuleCache = new InMemoryModuleCache;
1791 AST->OnlyLocalDecls = OnlyLocalDecls;
1792 AST->CaptureDiagnostics = CaptureDiagnostics;
1793 AST->TUKind = TUKind;
1794 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1795 AST->IncludeBriefCommentsInCodeCompletion
1796 = IncludeBriefCommentsInCodeCompletion;
1797 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1798 AST->Invocation = CI;
1799 AST->SkipFunctionBodies = SkipFunctionBodies;
1800 if (ForSerialization)
1801 AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
1802 // Zero out now to ease cleanup during crash recovery.
1806 // Recover resources if we crash before exiting this method.
1807 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1808 ASTUnitCleanup(AST.get());
1810 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1811 PrecompilePreambleAfterNParses,
1813 // Some error occurred, if caller wants to examine diagnostics, pass it the
1816 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1822 return AST.release();
1825 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1826 ArrayRef<RemappedFile> RemappedFiles,
1827 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1832 assert(FileMgr && "FileMgr is null on Reparse call");
1833 VFS = &FileMgr->getVirtualFileSystem();
1836 clearFileLevelDecls();
1838 SimpleTimer ParsingTimer(WantTiming);
1839 ParsingTimer.setOutput("Reparsing " + getMainFileName());
1842 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1843 for (const auto &RB : PPOpts.RemappedFileBuffers)
1846 Invocation->getPreprocessorOpts().clearRemappedFiles();
1847 for (const auto &RemappedFile : RemappedFiles) {
1848 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1849 RemappedFile.second);
1852 // If we have a preamble file lying around, or if we might try to
1853 // build a precompiled preamble, do so now.
1854 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1855 if (Preamble || PreambleRebuildCountdown > 0)
1856 OverrideMainBuffer =
1857 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1859 // Clear out the diagnostics state.
1861 getDiagnostics().Reset();
1862 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1863 if (OverrideMainBuffer)
1864 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1866 // Parse the sources
1868 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1870 // If we're caching global code-completion results, and the top-level
1871 // declarations have changed, clear out the code-completion cache.
1872 if (!Result && ShouldCacheCodeCompletionResults &&
1873 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1874 CacheCodeCompletionResults();
1876 // We now need to clear out the completion info related to this translation
1877 // unit; it'll be recreated if necessary.
1883 void ASTUnit::ResetForParse() {
1884 SavedMainFileBuffer.reset();
1892 TopLevelDecls.clear();
1893 clearFileLevelDecls();
1896 //----------------------------------------------------------------------------//
1898 //----------------------------------------------------------------------------//
1902 /// Code completion consumer that combines the cached code-completion
1903 /// results from an ASTUnit with the code-completion results provided to it,
1904 /// then passes the result on to
1905 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1906 uint64_t NormalContexts;
1908 CodeCompleteConsumer &Next;
1911 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1912 const CodeCompleteOptions &CodeCompleteOpts)
1913 : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
1914 // Compute the set of contexts in which we will look when we don't have
1915 // any information about the specific context.
1917 = (1LL << CodeCompletionContext::CCC_TopLevel)
1918 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1919 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1920 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1921 | (1LL << CodeCompletionContext::CCC_Statement)
1922 | (1LL << CodeCompletionContext::CCC_Expression)
1923 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1924 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1925 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1926 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1927 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1928 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1929 | (1LL << CodeCompletionContext::CCC_Recovery);
1931 if (AST.getASTContext().getLangOpts().CPlusPlus)
1932 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1933 | (1LL << CodeCompletionContext::CCC_UnionTag)
1934 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1937 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1938 CodeCompletionResult *Results,
1939 unsigned NumResults) override;
1941 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1942 OverloadCandidate *Candidates,
1943 unsigned NumCandidates,
1944 SourceLocation OpenParLoc) override {
1945 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1949 CodeCompletionAllocator &getAllocator() override {
1950 return Next.getAllocator();
1953 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1954 return Next.getCodeCompletionTUInfo();
1960 /// Helper function that computes which global names are hidden by the
1961 /// local code-completion results.
1962 static void CalculateHiddenNames(const CodeCompletionContext &Context,
1963 CodeCompletionResult *Results,
1964 unsigned NumResults,
1966 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1967 bool OnlyTagNames = false;
1968 switch (Context.getKind()) {
1969 case CodeCompletionContext::CCC_Recovery:
1970 case CodeCompletionContext::CCC_TopLevel:
1971 case CodeCompletionContext::CCC_ObjCInterface:
1972 case CodeCompletionContext::CCC_ObjCImplementation:
1973 case CodeCompletionContext::CCC_ObjCIvarList:
1974 case CodeCompletionContext::CCC_ClassStructUnion:
1975 case CodeCompletionContext::CCC_Statement:
1976 case CodeCompletionContext::CCC_Expression:
1977 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1978 case CodeCompletionContext::CCC_DotMemberAccess:
1979 case CodeCompletionContext::CCC_ArrowMemberAccess:
1980 case CodeCompletionContext::CCC_ObjCPropertyAccess:
1981 case CodeCompletionContext::CCC_Namespace:
1982 case CodeCompletionContext::CCC_Type:
1983 case CodeCompletionContext::CCC_Symbol:
1984 case CodeCompletionContext::CCC_SymbolOrNewName:
1985 case CodeCompletionContext::CCC_ParenthesizedExpression:
1986 case CodeCompletionContext::CCC_ObjCInterfaceName:
1989 case CodeCompletionContext::CCC_EnumTag:
1990 case CodeCompletionContext::CCC_UnionTag:
1991 case CodeCompletionContext::CCC_ClassOrStructTag:
1992 OnlyTagNames = true;
1995 case CodeCompletionContext::CCC_ObjCProtocolName:
1996 case CodeCompletionContext::CCC_MacroName:
1997 case CodeCompletionContext::CCC_MacroNameUse:
1998 case CodeCompletionContext::CCC_PreprocessorExpression:
1999 case CodeCompletionContext::CCC_PreprocessorDirective:
2000 case CodeCompletionContext::CCC_NaturalLanguage:
2001 case CodeCompletionContext::CCC_SelectorName:
2002 case CodeCompletionContext::CCC_TypeQualifiers:
2003 case CodeCompletionContext::CCC_Other:
2004 case CodeCompletionContext::CCC_OtherWithMacros:
2005 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2006 case CodeCompletionContext::CCC_ObjCClassMessage:
2007 case CodeCompletionContext::CCC_ObjCCategoryName:
2008 case CodeCompletionContext::CCC_IncludedFile:
2009 case CodeCompletionContext::CCC_NewName:
2010 // We're looking for nothing, or we're looking for names that cannot
2015 using Result = CodeCompletionResult;
2016 for (unsigned I = 0; I != NumResults; ++I) {
2017 if (Results[I].Kind != Result::RK_Declaration)
2021 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2023 bool Hiding = false;
2025 Hiding = (IDNS & Decl::IDNS_Tag);
2027 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2028 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2029 Decl::IDNS_NonMemberOperator);
2030 if (Ctx.getLangOpts().CPlusPlus)
2031 HiddenIDNS |= Decl::IDNS_Tag;
2032 Hiding = (IDNS & HiddenIDNS);
2038 DeclarationName Name = Results[I].Declaration->getDeclName();
2039 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2040 HiddenNames.insert(Identifier->getName());
2042 HiddenNames.insert(Name.getAsString());
2046 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2047 CodeCompletionContext Context,
2048 CodeCompletionResult *Results,
2049 unsigned NumResults) {
2050 // Merge the results we were given with the results we cached.
2051 bool AddedResult = false;
2052 uint64_t InContexts =
2053 Context.getKind() == CodeCompletionContext::CCC_Recovery
2054 ? NormalContexts : (1LL << Context.getKind());
2055 // Contains the set of names that are hidden by "local" completion results.
2056 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2057 using Result = CodeCompletionResult;
2058 SmallVector<Result, 8> AllResults;
2059 for (ASTUnit::cached_completion_iterator
2060 C = AST.cached_completion_begin(),
2061 CEnd = AST.cached_completion_end();
2063 // If the context we are in matches any of the contexts we are
2064 // interested in, we'll add this result.
2065 if ((C->ShowInContexts & InContexts) == 0)
2068 // If we haven't added any results previously, do so now.
2070 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2072 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2076 // Determine whether this global completion result is hidden by a local
2077 // completion result. If so, skip it.
2078 if (C->Kind != CXCursor_MacroDefinition &&
2079 HiddenNames.count(C->Completion->getTypedText()))
2082 // Adjust priority based on similar type classes.
2083 unsigned Priority = C->Priority;
2084 CodeCompletionString *Completion = C->Completion;
2085 if (!Context.getPreferredType().isNull()) {
2086 if (C->Kind == CXCursor_MacroDefinition) {
2087 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2089 Context.getPreferredType()->isAnyPointerType());
2090 } else if (C->Type) {
2091 CanQualType Expected
2092 = S.Context.getCanonicalType(
2093 Context.getPreferredType().getUnqualifiedType());
2094 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2095 if (ExpectedSTC == C->TypeClass) {
2096 // We know this type is similar; check for an exact match.
2097 llvm::StringMap<unsigned> &CachedCompletionTypes
2098 = AST.getCachedCompletionTypes();
2099 llvm::StringMap<unsigned>::iterator Pos
2100 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2101 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2102 Priority /= CCF_ExactTypeMatch;
2104 Priority /= CCF_SimilarTypeMatch;
2109 // Adjust the completion string, if required.
2110 if (C->Kind == CXCursor_MacroDefinition &&
2111 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2112 // Create a new code-completion string that just contains the
2113 // macro name, without its arguments.
2114 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2115 CCP_CodePattern, C->Availability);
2116 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2117 Priority = CCP_CodePattern;
2118 Completion = Builder.TakeString();
2121 AllResults.push_back(Result(Completion, Priority, C->Kind,
2125 // If we did not add any cached completion results, just forward the
2126 // results we were given to the next consumer.
2128 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2132 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2136 void ASTUnit::CodeComplete(
2137 StringRef File, unsigned Line, unsigned Column,
2138 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2139 bool IncludeCodePatterns, bool IncludeBriefComments,
2140 CodeCompleteConsumer &Consumer,
2141 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2142 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2143 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2144 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2148 SimpleTimer CompletionTimer(WantTiming);
2149 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2150 Twine(Line) + ":" + Twine(Column));
2152 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2154 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2155 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2156 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2158 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2159 CachedCompletionResults.empty();
2160 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2161 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2162 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2163 CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
2164 CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
2166 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2168 FrontendOpts.CodeCompletionAt.FileName = File;
2169 FrontendOpts.CodeCompletionAt.Line = Line;
2170 FrontendOpts.CodeCompletionAt.Column = Column;
2172 // Set the language options appropriately.
2173 LangOpts = *CCInvocation->getLangOpts();
2175 // Spell-checking and warnings are wasteful during code-completion.
2176 LangOpts.SpellChecking = false;
2177 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2179 std::unique_ptr<CompilerInstance> Clang(
2180 new CompilerInstance(PCHContainerOps));
2182 // Recover resources if we crash before exiting this method.
2183 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2184 CICleanup(Clang.get());
2186 auto &Inv = *CCInvocation;
2187 Clang->setInvocation(std::move(CCInvocation));
2188 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2190 // Set up diagnostics, capturing any diagnostics produced.
2191 Clang->setDiagnostics(&Diag);
2192 CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
2193 Clang->getDiagnostics(),
2194 &StoredDiagnostics, nullptr);
2195 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2197 // Create the target instance.
2198 Clang->setTarget(TargetInfo::CreateTargetInfo(
2199 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2200 if (!Clang->hasTarget()) {
2201 Clang->setInvocation(nullptr);
2205 // Inform the target of the language options.
2207 // FIXME: We shouldn't need to do this, the target should be immutable once
2208 // created. This complexity should be lifted elsewhere.
2209 Clang->getTarget().adjust(Clang->getLangOpts());
2211 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2212 "Invocation must have exactly one source file!");
2213 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2214 InputKind::Source &&
2215 "FIXME: AST inputs not yet supported here!");
2216 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2217 Language::LLVM_IR &&
2218 "IR inputs not support here!");
2220 // Use the source and file managers that we were given.
2221 Clang->setFileManager(&FileMgr);
2222 Clang->setSourceManager(&SourceMgr);
2225 PreprocessorOpts.clearRemappedFiles();
2226 PreprocessorOpts.RetainRemappedFileBuffers = true;
2227 for (const auto &RemappedFile : RemappedFiles) {
2228 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2229 OwnedBuffers.push_back(RemappedFile.second);
2232 // Use the code completion consumer we were given, but adding any cached
2233 // code-completion results.
2234 AugmentedCodeCompleteConsumer *AugmentedConsumer
2235 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2236 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2238 // If we have a precompiled preamble, try to use it. We only allow
2239 // the use of the precompiled preamble if we're if the completion
2240 // point is within the main file, after the end of the precompiled
2242 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2244 std::string CompleteFilePath(File);
2246 auto &VFS = FileMgr.getVirtualFileSystem();
2247 auto CompleteFileStatus = VFS.status(CompleteFilePath);
2248 if (CompleteFileStatus) {
2249 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2251 std::string MainPath(OriginalSourceFile);
2252 auto MainStatus = VFS.status(MainPath);
2254 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2255 if (CompleteFileID == MainID && Line > 1)
2256 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2257 PCHContainerOps, Inv, &VFS, false, Line - 1);
2262 // If the main file has been overridden due to the use of a preamble,
2263 // make that override happen and introduce the preamble.
2264 if (OverrideMainBuffer) {
2266 "No preamble was built, but OverrideMainBuffer is not null");
2268 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
2269 &FileMgr.getVirtualFileSystem();
2270 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2271 OverrideMainBuffer.get());
2272 // FIXME: there is no way to update VFS if it was changed by
2273 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2274 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2275 // PCH files are always readable.
2276 OwnedBuffers.push_back(OverrideMainBuffer.release());
2278 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2279 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2282 // Disable the preprocessing record if modules are not enabled.
2283 if (!Clang->getLangOpts().Modules)
2284 PreprocessorOpts.DetailedRecord = false;
2286 std::unique_ptr<SyntaxOnlyAction> Act;
2287 Act.reset(new SyntaxOnlyAction);
2288 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2289 if (llvm::Error Err = Act->Execute()) {
2290 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2292 Act->EndSourceFile();
2296 bool ASTUnit::Save(StringRef File) {
2297 if (HadModuleLoaderFatalFailure)
2300 // Write to a temporary file and later rename it to the actual file, to avoid
2301 // possible race conditions.
2302 SmallString<128> TempPath;
2304 TempPath += "-%%%%%%%%";
2305 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2306 // unconditionally create a stat cache when we parse the file?
2308 if (llvm::Error Err = llvm::writeFileAtomically(
2309 TempPath, File, [this](llvm::raw_ostream &Out) {
2310 return serialize(Out) ? llvm::make_error<llvm::StringError>(
2311 "ASTUnit serialization failed",
2312 llvm::inconvertibleErrorCode())
2313 : llvm::Error::success();
2315 consumeError(std::move(Err));
2321 static bool serializeUnit(ASTWriter &Writer,
2322 SmallVectorImpl<char> &Buffer,
2326 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2328 // Write the generated bitstream to "Out".
2329 if (!Buffer.empty())
2330 OS.write(Buffer.data(), Buffer.size());
2335 bool ASTUnit::serialize(raw_ostream &OS) {
2336 // For serialization we are lenient if the errors were only warn-as-error kind.
2337 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2340 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2341 getSema(), hasErrors, OS);
2343 SmallString<128> Buffer;
2344 llvm::BitstreamWriter Stream(Buffer);
2345 InMemoryModuleCache ModuleCache;
2346 ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2347 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2350 using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
2352 void ASTUnit::TranslateStoredDiagnostics(
2353 FileManager &FileMgr,
2354 SourceManager &SrcMgr,
2355 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2356 SmallVectorImpl<StoredDiagnostic> &Out) {
2357 // Map the standalone diagnostic into the new source manager. We also need to
2358 // remap all the locations to the new view. This includes the diag location,
2359 // any associated source ranges, and the source ranges of associated fix-its.
2360 // FIXME: There should be a cleaner way to do this.
2361 SmallVector<StoredDiagnostic, 4> Result;
2362 Result.reserve(Diags.size());
2364 for (const auto &SD : Diags) {
2365 // Rebuild the StoredDiagnostic.
2366 if (SD.Filename.empty())
2368 auto FE = FileMgr.getFile(SD.Filename);
2371 SourceLocation FileLoc;
2372 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2373 if (ItFileID == PreambleSrcLocCache.end()) {
2374 FileID FID = SrcMgr.translateFile(*FE);
2375 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2376 PreambleSrcLocCache[SD.Filename] = FileLoc;
2378 FileLoc = ItFileID->getValue();
2381 if (FileLoc.isInvalid())
2383 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2384 FullSourceLoc Loc(L, SrcMgr);
2386 SmallVector<CharSourceRange, 4> Ranges;
2387 Ranges.reserve(SD.Ranges.size());
2388 for (const auto &Range : SD.Ranges) {
2389 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2390 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2391 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2394 SmallVector<FixItHint, 2> FixIts;
2395 FixIts.reserve(SD.FixIts.size());
2396 for (const auto &FixIt : SD.FixIts) {
2397 FixIts.push_back(FixItHint());
2398 FixItHint &FH = FixIts.back();
2399 FH.CodeToInsert = FixIt.CodeToInsert;
2400 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2401 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2402 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2405 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2406 SD.Message, Loc, Ranges, FixIts));
2411 void ASTUnit::addFileLevelDecl(Decl *D) {
2414 // We only care about local declarations.
2415 if (D->isFromASTFile())
2418 SourceManager &SM = *SourceMgr;
2419 SourceLocation Loc = D->getLocation();
2420 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2423 // We only keep track of the file-level declarations of each file.
2424 if (!D->getLexicalDeclContext()->isFileContext())
2427 SourceLocation FileLoc = SM.getFileLoc(Loc);
2428 assert(SM.isLocalSourceLocation(FileLoc));
2431 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2432 if (FID.isInvalid())
2435 LocDeclsTy *&Decls = FileDecls[FID];
2437 Decls = new LocDeclsTy();
2439 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2441 if (Decls->empty() || Decls->back().first <= Offset) {
2442 Decls->push_back(LocDecl);
2446 LocDeclsTy::iterator I =
2447 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2449 Decls->insert(I, LocDecl);
2452 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2453 SmallVectorImpl<Decl *> &Decls) {
2454 if (File.isInvalid())
2457 if (SourceMgr->isLoadedFileID(File)) {
2458 assert(Ctx->getExternalSource() && "No external source!");
2459 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2463 FileDeclsTy::iterator I = FileDecls.find(File);
2464 if (I == FileDecls.end())
2467 LocDeclsTy &LocDecls = *I->second;
2468 if (LocDecls.empty())
2471 LocDeclsTy::iterator BeginIt =
2472 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2473 return LD.first < Offset;
2475 if (BeginIt != LocDecls.begin())
2478 // If we are pointing at a top-level decl inside an objc container, we need
2479 // to backtrack until we find it otherwise we will fail to report that the
2480 // region overlaps with an objc container.
2481 while (BeginIt != LocDecls.begin() &&
2482 BeginIt->second->isTopLevelDeclInObjCContainer())
2485 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2486 LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2487 llvm::less_first());
2488 if (EndIt != LocDecls.end())
2491 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2492 Decls.push_back(DIt->second);
2495 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2496 unsigned Line, unsigned Col) const {
2497 const SourceManager &SM = getSourceManager();
2498 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2499 return SM.getMacroArgExpandedLocation(Loc);
2502 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2503 unsigned Offset) const {
2504 const SourceManager &SM = getSourceManager();
2505 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2506 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2509 /// If \arg Loc is a loaded location from the preamble, returns
2510 /// the corresponding local location of the main file, otherwise it returns
2512 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
2515 PreambleID = SourceMgr->getPreambleFileID();
2517 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2521 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2522 SourceLocation FileLoc
2523 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2524 return FileLoc.getLocWithOffset(Offs);
2530 /// If \arg Loc is a local location of the main file but inside the
2531 /// preamble chunk, returns the corresponding loaded location from the
2532 /// preamble, otherwise it returns \arg Loc.
2533 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
2536 PreambleID = SourceMgr->getPreambleFileID();
2538 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2542 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2543 Offs < Preamble->getBounds().Size) {
2544 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2545 return FileLoc.getLocWithOffset(Offs);
2551 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
2554 FID = SourceMgr->getPreambleFileID();
2556 if (Loc.isInvalid() || FID.isInvalid())
2559 return SourceMgr->isInFileID(Loc, FID);
2562 bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
2565 FID = SourceMgr->getMainFileID();
2567 if (Loc.isInvalid() || FID.isInvalid())
2570 return SourceMgr->isInFileID(Loc, FID);
2573 SourceLocation ASTUnit::getEndOfPreambleFileID() const {
2576 FID = SourceMgr->getPreambleFileID();
2578 if (FID.isInvalid())
2581 return SourceMgr->getLocForEndOfFile(FID);
2584 SourceLocation ASTUnit::getStartOfMainFileID() const {
2587 FID = SourceMgr->getMainFileID();
2589 if (FID.isInvalid())
2592 return SourceMgr->getLocForStartOfFile(FID);
2595 llvm::iterator_range<PreprocessingRecord::iterator>
2596 ASTUnit::getLocalPreprocessingEntities() const {
2597 if (isMainFileAST()) {
2598 serialization::ModuleFile &
2599 Mod = Reader->getModuleManager().getPrimaryModule();
2600 return Reader->getModulePreprocessedEntities(Mod);
2603 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2604 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2606 return llvm::make_range(PreprocessingRecord::iterator(),
2607 PreprocessingRecord::iterator());
2610 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2611 if (isMainFileAST()) {
2612 serialization::ModuleFile &
2613 Mod = Reader->getModuleManager().getPrimaryModule();
2614 for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2615 if (!Fn(context, D))
2622 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2623 TLEnd = top_level_end();
2624 TL != TLEnd; ++TL) {
2625 if (!Fn(context, *TL))
2632 const FileEntry *ASTUnit::getPCHFile() {
2636 serialization::ModuleFile *Mod = nullptr;
2637 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2639 case serialization::MK_ImplicitModule:
2640 case serialization::MK_ExplicitModule:
2641 case serialization::MK_PrebuiltModule:
2642 return true; // skip dependencies.
2643 case serialization::MK_PCH:
2645 return true; // found it.
2646 case serialization::MK_Preamble:
2647 return false; // look in dependencies.
2648 case serialization::MK_MainFile:
2649 return false; // look in dependencies.
2660 bool ASTUnit::isModuleFile() const {
2661 return isMainFileAST() && getLangOpts().isCompilingModule();
2664 InputKind ASTUnit::getInputKind() const {
2665 auto &LangOpts = getLangOpts();
2668 if (LangOpts.OpenCL)
2669 Lang = Language::OpenCL;
2670 else if (LangOpts.CUDA)
2671 Lang = Language::CUDA;
2672 else if (LangOpts.RenderScript)
2673 Lang = Language::RenderScript;
2674 else if (LangOpts.CPlusPlus)
2675 Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
2677 Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
2679 InputKind::Format Fmt = InputKind::Source;
2680 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2681 Fmt = InputKind::ModuleMap;
2683 // We don't know if input was preprocessed. Assume not.
2686 return InputKind(Lang, Fmt, PP);
2690 ASTUnit::ConcurrencyState::ConcurrencyState() {
2691 Mutex = new std::recursive_mutex;
2694 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2695 delete static_cast<std::recursive_mutex *>(Mutex);
2698 void ASTUnit::ConcurrencyState::start() {
2699 bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
2700 assert(acquired && "Concurrent access to ASTUnit!");
2703 void ASTUnit::ConcurrencyState::finish() {
2704 static_cast<std::recursive_mutex *>(Mutex)->unlock();
2709 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2710 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2711 void ASTUnit::ConcurrencyState::start() {}
2712 void ASTUnit::ConcurrencyState::finish() {}