1 //===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit Implementation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeOrdering.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/MemoryBufferCache.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Basic/VirtualFileSystem.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/FrontendActions.h"
27 #include "clang/Frontend/FrontendDiagnostic.h"
28 #include "clang/Frontend/FrontendOptions.h"
29 #include "clang/Frontend/MultiplexConsumer.h"
30 #include "clang/Frontend/Utils.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Serialization/ASTReader.h"
36 #include "clang/Serialization/ASTWriter.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringSet.h"
40 #include "llvm/Support/CrashRecoveryContext.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Mutex.h"
44 #include "llvm/Support/MutexGuard.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
53 using llvm::TimeRecord;
62 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
64 Start = TimeRecord::getCurrentTime();
67 void setOutput(const Twine &Output) {
69 this->Output = Output.str();
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
84 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
87 return std::move(*Val);
91 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
94 Output = std::move(*Val);
98 /// \brief Get a source buffer for \p MainFilePath, handling all file-to-file
99 /// and file-to-buffer remappings inside \p Invocation.
100 static std::unique_ptr<llvm::MemoryBuffer>
101 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
102 vfs::FileSystem *VFS,
103 StringRef FilePath) {
104 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
106 // Try to determine if the main file has been remapped, either from the
107 // command line (to another file) or directly through the compiler
108 // invocation (to a memory buffer).
109 llvm::MemoryBuffer *Buffer = nullptr;
110 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
111 auto FileStatus = VFS->status(FilePath);
113 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
115 // Check whether there is a file-file remapping of the main file
116 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
117 std::string MPath(RF.first);
118 auto MPathStatus = VFS->status(MPath);
120 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
121 if (MainFileID == MID) {
122 // We found a remapping. Try to load the resulting, remapped source.
123 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
130 // Check whether there is a file-buffer remapping. It supercedes the
131 // file-file remapping.
132 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
133 std::string MPath(RB.first);
134 auto MPathStatus = VFS->status(MPath);
136 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
137 if (MainFileID == MID) {
138 // We found a remapping.
140 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
146 // If the main source file was not remapped, load it now.
147 if (!Buffer && !BufferOwner) {
148 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
157 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
161 struct ASTUnit::ASTWriterData {
162 SmallString<128> Buffer;
163 llvm::BitstreamWriter Stream;
166 ASTWriterData(MemoryBufferCache &PCMCache)
167 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
170 void ASTUnit::clearFileLevelDecls() {
171 llvm::DeleteContainerSeconds(FileDecls);
174 /// \brief After failing to build a precompiled preamble (due to
175 /// errors in the source that occurs in the preamble), the number of
176 /// reparses during which we'll skip even trying to precompile the
178 const unsigned DefaultPreambleRebuildInterval = 5;
180 /// \brief Tracks the number of ASTUnit objects that are currently active.
182 /// Used for debugging purposes only.
183 static std::atomic<unsigned> ActiveASTUnitObjects;
185 ASTUnit::ASTUnit(bool _MainFileIsAST)
186 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
187 OnlyLocalDecls(false), CaptureDiagnostics(false),
188 MainFileIsAST(_MainFileIsAST),
189 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
190 OwnsRemappedFileBuffers(true),
191 NumStoredDiagnosticsFromDriver(0),
192 PreambleRebuildCounter(0),
193 NumWarningsInPreamble(0),
194 ShouldCacheCodeCompletionResults(false),
195 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
196 CompletionCacheTopLevelHashValue(0),
197 PreambleTopLevelHashValue(0),
198 CurrentTopLevelHashValue(0),
199 UnsafeToFree(false) {
200 if (getenv("LIBCLANG_OBJTRACKING"))
201 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
204 ASTUnit::~ASTUnit() {
205 // If we loaded from an AST file, balance out the BeginSourceFile call.
206 if (MainFileIsAST && getDiagnostics().getClient()) {
207 getDiagnostics().getClient()->EndSourceFile();
210 clearFileLevelDecls();
212 // Free the buffers associated with remapped files. We are required to
213 // perform this operation here because we explicitly request that the
214 // compiler instance *not* free these buffers for each invocation of the
216 if (Invocation && OwnsRemappedFileBuffers) {
217 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
218 for (const auto &RB : PPOpts.RemappedFileBuffers)
222 ClearCachedCompletionResults();
224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
228 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
229 this->PP = std::move(PP);
232 /// \brief Determine the set of code-completion contexts in which this
233 /// declaration should be shown.
234 static unsigned getDeclShowContexts(const NamedDecl *ND,
235 const LangOptions &LangOpts,
236 bool &IsNestedNameSpecifier) {
237 IsNestedNameSpecifier = false;
239 if (isa<UsingShadowDecl>(ND))
240 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
244 uint64_t Contexts = 0;
245 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
246 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
247 // Types can appear in these contexts.
248 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
249 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
250 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
251 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
252 | (1LL << CodeCompletionContext::CCC_Statement)
253 | (1LL << CodeCompletionContext::CCC_Type)
254 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
256 // In C++, types can appear in expressions contexts (for functional casts).
257 if (LangOpts.CPlusPlus)
258 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
260 // In Objective-C, message sends can send interfaces. In Objective-C++,
261 // all types are available due to functional casts.
262 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
263 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
265 // In Objective-C, you can only be a subclass of another Objective-C class
266 if (isa<ObjCInterfaceDecl>(ND))
267 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
269 // Deal with tag names.
270 if (isa<EnumDecl>(ND)) {
271 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
273 // Part of the nested-name-specifier in C++0x.
274 if (LangOpts.CPlusPlus11)
275 IsNestedNameSpecifier = true;
276 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
277 if (Record->isUnion())
278 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
280 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
282 if (LangOpts.CPlusPlus)
283 IsNestedNameSpecifier = true;
284 } else if (isa<ClassTemplateDecl>(ND))
285 IsNestedNameSpecifier = true;
286 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
287 // Values can appear in these contexts.
288 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
289 | (1LL << CodeCompletionContext::CCC_Expression)
290 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
291 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
292 } else if (isa<ObjCProtocolDecl>(ND)) {
293 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
294 } else if (isa<ObjCCategoryDecl>(ND)) {
295 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
296 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
297 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
299 // Part of the nested-name-specifier.
300 IsNestedNameSpecifier = true;
306 void ASTUnit::CacheCodeCompletionResults() {
310 SimpleTimer Timer(WantTiming);
311 Timer.setOutput("Cache global code completions for " + getMainFileName());
313 // Clear out the previous results.
314 ClearCachedCompletionResults();
316 // Gather the set of global code completions.
317 typedef CodeCompletionResult Result;
318 SmallVector<Result, 8> Results;
319 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
320 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
321 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
324 // Translate global code completions into cached completions.
325 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
326 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
328 for (Result &R : Results) {
330 case Result::RK_Declaration: {
331 bool IsNestedNameSpecifier = false;
332 CachedCodeCompletionResult CachedResult;
333 CachedResult.Completion = R.CreateCodeCompletionString(
334 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
335 IncludeBriefCommentsInCodeCompletion);
336 CachedResult.ShowInContexts = getDeclShowContexts(
337 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
338 CachedResult.Priority = R.Priority;
339 CachedResult.Kind = R.CursorKind;
340 CachedResult.Availability = R.Availability;
342 // Keep track of the type of this completion in an ASTContext-agnostic
344 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
345 if (UsageType.isNull()) {
346 CachedResult.TypeClass = STC_Void;
347 CachedResult.Type = 0;
349 CanQualType CanUsageType
350 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
351 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
353 // Determine whether we have already seen this type. If so, we save
354 // ourselves the work of formatting the type string by using the
355 // temporary, CanQualType-based hash table to find the associated value.
356 unsigned &TypeValue = CompletionTypes[CanUsageType];
357 if (TypeValue == 0) {
358 TypeValue = CompletionTypes.size();
359 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
363 CachedResult.Type = TypeValue;
366 CachedCompletionResults.push_back(CachedResult);
368 /// Handle nested-name-specifiers in C++.
369 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
370 !R.StartsNestedNameSpecifier) {
371 // The contexts in which a nested-name-specifier can appear in C++.
373 = (1LL << CodeCompletionContext::CCC_TopLevel)
374 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
375 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
376 | (1LL << CodeCompletionContext::CCC_Statement)
377 | (1LL << CodeCompletionContext::CCC_Expression)
378 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
379 | (1LL << CodeCompletionContext::CCC_EnumTag)
380 | (1LL << CodeCompletionContext::CCC_UnionTag)
381 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
382 | (1LL << CodeCompletionContext::CCC_Type)
383 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
384 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
386 if (isa<NamespaceDecl>(R.Declaration) ||
387 isa<NamespaceAliasDecl>(R.Declaration))
388 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
390 if (unsigned RemainingContexts
391 = NNSContexts & ~CachedResult.ShowInContexts) {
392 // If there any contexts where this completion can be a
393 // nested-name-specifier but isn't already an option, create a
394 // nested-name-specifier completion.
395 R.StartsNestedNameSpecifier = true;
396 CachedResult.Completion = R.CreateCodeCompletionString(
397 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
398 IncludeBriefCommentsInCodeCompletion);
399 CachedResult.ShowInContexts = RemainingContexts;
400 CachedResult.Priority = CCP_NestedNameSpecifier;
401 CachedResult.TypeClass = STC_Void;
402 CachedResult.Type = 0;
403 CachedCompletionResults.push_back(CachedResult);
409 case Result::RK_Keyword:
410 case Result::RK_Pattern:
411 // Ignore keywords and patterns; we don't care, since they are so
412 // easily regenerated.
415 case Result::RK_Macro: {
416 CachedCodeCompletionResult CachedResult;
417 CachedResult.Completion = R.CreateCodeCompletionString(
418 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
419 IncludeBriefCommentsInCodeCompletion);
420 CachedResult.ShowInContexts
421 = (1LL << CodeCompletionContext::CCC_TopLevel)
422 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
423 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
424 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
425 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
426 | (1LL << CodeCompletionContext::CCC_Statement)
427 | (1LL << CodeCompletionContext::CCC_Expression)
428 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
429 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
430 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
431 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
432 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
434 CachedResult.Priority = R.Priority;
435 CachedResult.Kind = R.CursorKind;
436 CachedResult.Availability = R.Availability;
437 CachedResult.TypeClass = STC_Void;
438 CachedResult.Type = 0;
439 CachedCompletionResults.push_back(CachedResult);
445 // Save the current top-level hash value.
446 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
449 void ASTUnit::ClearCachedCompletionResults() {
450 CachedCompletionResults.clear();
451 CachedCompletionTypes.clear();
452 CachedCompletionAllocator = nullptr;
457 /// \brief Gathers information from ASTReader that will be used to initialize
459 class ASTInfoCollector : public ASTReaderListener {
462 HeaderSearchOptions &HSOpts;
463 PreprocessorOptions &PPOpts;
464 LangOptions &LangOpt;
465 std::shared_ptr<TargetOptions> &TargetOpts;
466 IntrusiveRefCntPtr<TargetInfo> &Target;
469 bool InitializedLanguage;
471 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
472 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
473 LangOptions &LangOpt,
474 std::shared_ptr<TargetOptions> &TargetOpts,
475 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
476 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
477 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
478 Counter(Counter), InitializedLanguage(false) {}
480 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
481 bool AllowCompatibleDifferences) override {
482 if (InitializedLanguage)
486 InitializedLanguage = true;
492 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
493 StringRef SpecificModuleCachePath,
494 bool Complain) override {
495 this->HSOpts = HSOpts;
500 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
501 std::string &SuggestedPredefines) override {
502 this->PPOpts = PPOpts;
506 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
507 bool AllowCompatibleDifferences) override {
508 // If we've already initialized the target, don't do it again.
512 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
514 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
520 void ReadCounter(const serialization::ModuleFile &M,
521 unsigned Value) override {
527 if (!Target || !InitializedLanguage)
530 // Inform the target of the language options.
532 // FIXME: We shouldn't need to do this, the target should be immutable once
533 // created. This complexity should be lifted elsewhere.
534 Target->adjust(LangOpt);
536 // Initialize the preprocessor.
537 PP.Initialize(*Target);
542 // Initialize the ASTContext
543 Context->InitBuiltinTypes(*Target);
545 // We didn't have access to the comment options when the ASTContext was
546 // constructed, so register them now.
547 Context->getCommentCommandTraits().registerCommentOptions(
548 LangOpt.CommentOpts);
552 /// \brief Diagnostic consumer that saves each diagnostic it is given.
553 class StoredDiagnosticConsumer : public DiagnosticConsumer {
554 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
555 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
556 const LangOptions *LangOpts;
557 SourceManager *SourceMgr;
560 StoredDiagnosticConsumer(
561 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
562 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
563 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
564 LangOpts(nullptr), SourceMgr(nullptr) {
565 assert((StoredDiags || StandaloneDiags) &&
566 "No output collections were passed to StoredDiagnosticConsumer.");
569 void BeginSourceFile(const LangOptions &LangOpts,
570 const Preprocessor *PP = nullptr) override {
571 this->LangOpts = &LangOpts;
573 SourceMgr = &PP->getSourceManager();
576 void HandleDiagnostic(DiagnosticsEngine::Level Level,
577 const Diagnostic &Info) override;
580 /// \brief RAII object that optionally captures diagnostics, if
581 /// there is no diagnostic client to capture them already.
582 class CaptureDroppedDiagnostics {
583 DiagnosticsEngine &Diags;
584 StoredDiagnosticConsumer Client;
585 DiagnosticConsumer *PreviousClient;
586 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
589 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
590 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
591 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
592 : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(nullptr)
594 if (RequestCapture || Diags.getClient() == nullptr) {
595 OwningPreviousClient = Diags.takeClient();
596 PreviousClient = Diags.getClient();
597 Diags.setClient(&Client, false);
601 ~CaptureDroppedDiagnostics() {
602 if (Diags.getClient() == &Client)
603 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
607 } // anonymous namespace
609 static ASTUnit::StandaloneDiagnostic
610 makeStandaloneDiagnostic(const LangOptions &LangOpts,
611 const StoredDiagnostic &InDiag);
613 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
614 const Diagnostic &Info) {
615 // Default implementation (Warnings/errors count).
616 DiagnosticConsumer::HandleDiagnostic(Level, Info);
618 // Only record the diagnostic if it's part of the source manager we know
619 // about. This effectively drops diagnostics from modules we're building.
620 // FIXME: In the long run, ee don't want to drop source managers from modules.
621 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
622 StoredDiagnostic *ResultDiag = nullptr;
624 StoredDiags->emplace_back(Level, Info);
625 ResultDiag = &StoredDiags->back();
628 if (StandaloneDiags) {
629 llvm::Optional<StoredDiagnostic> StoredDiag = llvm::None;
631 StoredDiag.emplace(Level, Info);
632 ResultDiag = StoredDiag.getPointer();
634 StandaloneDiags->push_back(
635 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
640 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
644 ASTMutationListener *ASTUnit::getASTMutationListener() {
646 return &WriterData->Writer;
650 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
652 return &WriterData->Writer;
656 std::unique_ptr<llvm::MemoryBuffer>
657 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
659 auto Buffer = FileMgr->getBufferForFile(Filename);
661 return std::move(*Buffer);
663 *ErrorStr = Buffer.getError().message();
667 /// \brief Configure the diagnostics object for use with ASTUnit.
668 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
669 ASTUnit &AST, bool CaptureDiagnostics) {
670 assert(Diags.get() && "no DiagnosticsEngine was provided");
671 if (CaptureDiagnostics)
672 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
675 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
676 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
677 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
678 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
679 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
680 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
681 bool UserFilesAreVolatile) {
682 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
684 // Recover resources if we crash before exiting this method.
685 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
686 ASTUnitCleanup(AST.get());
687 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
688 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
689 DiagCleanup(Diags.get());
691 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
693 AST->LangOpts = std::make_shared<LangOptions>();
694 AST->OnlyLocalDecls = OnlyLocalDecls;
695 AST->CaptureDiagnostics = CaptureDiagnostics;
696 AST->Diagnostics = Diags;
697 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
698 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
699 AST->UserFilesAreVolatile = UserFilesAreVolatile;
700 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
701 AST->getFileManager(),
702 UserFilesAreVolatile);
703 AST->PCMCache = new MemoryBufferCache;
704 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
705 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
706 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
707 AST->getSourceManager(),
708 AST->getDiagnostics(),
710 /*Target=*/nullptr));
711 AST->PPOpts = std::make_shared<PreprocessorOptions>();
713 for (const auto &RemappedFile : RemappedFiles)
714 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
716 // Gather Info for preprocessor construction later on.
718 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
721 AST->PP = std::make_shared<Preprocessor>(
722 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
723 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
724 /*IILookup=*/nullptr,
725 /*OwnsHeaderSearch=*/false);
726 Preprocessor &PP = *AST->PP;
728 if (ToLoad >= LoadASTOnly)
729 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
730 PP.getIdentifierTable(), PP.getSelectorTable(),
731 PP.getBuiltinInfo());
733 bool disableValid = false;
734 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
736 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { },
738 /*DisableValidation=*/disableValid,
739 AllowPCHWithCompilerErrors);
741 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
742 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
743 AST->TargetOpts, AST->Target, Counter));
745 // Attach the AST reader to the AST context as an external AST
746 // source, so that declarations will be deserialized from the
747 // AST file as needed.
748 // We need the external source to be set up before we read the AST, because
749 // eagerly-deserialized declarations may use it.
751 AST->Ctx->setExternalSource(AST->Reader);
753 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
754 SourceLocation(), ASTReader::ARR_None)) {
755 case ASTReader::Success:
758 case ASTReader::Failure:
759 case ASTReader::Missing:
760 case ASTReader::OutOfDate:
761 case ASTReader::VersionMismatch:
762 case ASTReader::ConfigurationMismatch:
763 case ASTReader::HadErrors:
764 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
768 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
770 PP.setCounterValue(Counter);
772 // Create an AST consumer, even though it isn't used.
773 if (ToLoad >= LoadASTOnly)
774 AST->Consumer.reset(new ASTConsumer);
776 // Create a semantic analysis object and tell the AST reader about it.
777 if (ToLoad >= LoadEverything) {
778 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
779 AST->TheSema->Initialize();
780 AST->Reader->InitializeSema(*AST->TheSema);
783 // Tell the diagnostic client that we have started a source file.
784 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
791 /// \brief Add the given macro to the hash of all top-level entities.
792 void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
793 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
796 /// \brief Preprocessor callback class that updates a hash value with the names
797 /// of all macros that have been defined by the translation unit.
798 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
802 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
804 void MacroDefined(const Token &MacroNameTok,
805 const MacroDirective *MD) override {
806 AddDefinedMacroToHash(MacroNameTok, Hash);
810 /// \brief Add the given declaration to the hash of all top-level entities.
811 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
815 DeclContext *DC = D->getDeclContext();
819 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
822 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
823 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
824 // For an unscoped enum include the enumerators in the hash since they
825 // enter the top-level namespace.
826 if (!EnumD->isScoped()) {
827 for (const auto *EI : EnumD->enumerators()) {
828 if (EI->getIdentifier())
829 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
834 if (ND->getIdentifier())
835 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
836 else if (DeclarationName Name = ND->getDeclName()) {
837 std::string NameStr = Name.getAsString();
838 Hash = llvm::HashString(NameStr, Hash);
843 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
844 if (Module *Mod = ImportD->getImportedModule()) {
845 std::string ModName = Mod->getFullModuleName();
846 Hash = llvm::HashString(ModName, Hash);
852 class TopLevelDeclTrackerConsumer : public ASTConsumer {
857 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
858 : Unit(_Unit), Hash(Hash) {
862 void handleTopLevelDecl(Decl *D) {
866 // FIXME: Currently ObjC method declarations are incorrectly being
867 // reported as top-level declarations, even though their DeclContext
868 // is the containing ObjC @interface/@implementation. This is a
869 // fundamental problem in the parser right now.
870 if (isa<ObjCMethodDecl>(D))
873 AddTopLevelDeclarationToHash(D, Hash);
874 Unit.addTopLevelDecl(D);
876 handleFileLevelDecl(D);
879 void handleFileLevelDecl(Decl *D) {
880 Unit.addFileLevelDecl(D);
881 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
882 for (auto *I : NSD->decls())
883 handleFileLevelDecl(I);
887 bool HandleTopLevelDecl(DeclGroupRef D) override {
888 for (Decl *TopLevelDecl : D)
889 handleTopLevelDecl(TopLevelDecl);
893 // We're not interested in "interesting" decls.
894 void HandleInterestingDecl(DeclGroupRef) override {}
896 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
897 for (Decl *TopLevelDecl : D)
898 handleTopLevelDecl(TopLevelDecl);
901 ASTMutationListener *GetASTMutationListener() override {
902 return Unit.getASTMutationListener();
905 ASTDeserializationListener *GetASTDeserializationListener() override {
906 return Unit.getDeserializationListener();
910 class TopLevelDeclTrackerAction : public ASTFrontendAction {
914 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
915 StringRef InFile) override {
916 CI.getPreprocessor().addPPCallbacks(
917 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
918 Unit.getCurrentTopLevelHashValue()));
919 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
920 Unit, Unit.getCurrentTopLevelHashValue());
924 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
926 bool hasCodeCompletionSupport() const override { return false; }
927 TranslationUnitKind getTranslationUnitKind() override {
928 return Unit.getTranslationUnitKind();
932 class ASTUnitPreambleCallbacks : public PreambleCallbacks {
934 unsigned getHash() const { return Hash; }
936 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
938 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
939 return std::move(TopLevelDeclIDs);
942 void AfterPCHEmitted(ASTWriter &Writer) override {
943 TopLevelDeclIDs.reserve(TopLevelDecls.size());
944 for (Decl *D : TopLevelDecls) {
945 // Invalid top-level decls may not have been serialized.
946 if (D->isInvalidDecl())
948 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
952 void HandleTopLevelDecl(DeclGroupRef DG) override {
954 // FIXME: Currently ObjC method declarations are incorrectly being
955 // reported as top-level declarations, even though their DeclContext
956 // is the containing ObjC @interface/@implementation. This is a
957 // fundamental problem in the parser right now.
958 if (isa<ObjCMethodDecl>(D))
960 AddTopLevelDeclarationToHash(D, Hash);
961 TopLevelDecls.push_back(D);
965 void HandleMacroDefined(const Token &MacroNameTok,
966 const MacroDirective *MD) override {
967 AddDefinedMacroToHash(MacroNameTok, Hash);
972 std::vector<Decl *> TopLevelDecls;
973 std::vector<serialization::DeclID> TopLevelDeclIDs;
974 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
977 } // anonymous namespace
979 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
980 return StoredDiag.getLocation().isValid();
984 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
985 // Get rid of stored diagnostics except the ones from the driver which do not
986 // have a source location.
988 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
992 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
995 // The stored diagnostic has the old source manager in it; update
996 // the locations to refer into the new source manager. Since we've
997 // been careful to make sure that the source manager's state
998 // before and after are identical, so that we can reuse the source
1000 for (StoredDiagnostic &SD : StoredDiagnostics) {
1001 if (SD.getLocation().isValid()) {
1002 FullSourceLoc Loc(SD.getLocation(), SM);
1003 SD.setLocation(Loc);
1008 /// Parse the source file into a translation unit using the given compiler
1009 /// invocation, replacing the current translation unit.
1011 /// \returns True if a failure occurred that causes the ASTUnit not to
1012 /// contain any translation-unit information, false otherwise.
1013 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1014 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1015 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1019 // Create the compiler instance to use for building the AST.
1020 std::unique_ptr<CompilerInstance> Clang(
1021 new CompilerInstance(std::move(PCHContainerOps)));
1022 if (FileMgr && VFS) {
1023 assert(VFS == FileMgr->getVirtualFileSystem() &&
1024 "VFS passed to Parse and VFS in FileMgr are different");
1026 Clang->setVirtualFileSystem(VFS);
1029 // Recover resources if we crash before exiting this method.
1030 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1031 CICleanup(Clang.get());
1033 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1034 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1036 // Set up diagnostics, capturing any diagnostics that would
1037 // otherwise be dropped.
1038 Clang->setDiagnostics(&getDiagnostics());
1040 // Create the target instance.
1041 Clang->setTarget(TargetInfo::CreateTargetInfo(
1042 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1043 if (!Clang->hasTarget())
1046 // Inform the target of the language options.
1048 // FIXME: We shouldn't need to do this, the target should be immutable once
1049 // created. This complexity should be lifted elsewhere.
1050 Clang->getTarget().adjust(Clang->getLangOpts());
1052 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1053 "Invocation must have exactly one source file!");
1054 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1055 InputKind::Source &&
1056 "FIXME: AST inputs not yet supported here!");
1057 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1058 InputKind::LLVM_IR &&
1059 "IR inputs not support here!");
1061 // Configure the various subsystems.
1062 LangOpts = Clang->getInvocation().LangOpts;
1063 FileSystemOpts = Clang->getFileSystemOpts();
1065 Clang->createFileManager();
1066 FileMgr = &Clang->getFileManager();
1071 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1072 UserFilesAreVolatile);
1073 if (!OverrideMainBuffer) {
1074 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1075 TopLevelDeclsInPreamble.clear();
1078 // Create a file manager object to provide access to and cache the filesystem.
1079 Clang->setFileManager(&getFileManager());
1081 // Create the source manager.
1082 Clang->setSourceManager(&getSourceManager());
1084 // If the main file has been overridden due to the use of a preamble,
1085 // make that override happen and introduce the preamble.
1086 if (OverrideMainBuffer) {
1087 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
1088 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
1090 // The stored diagnostic has the old source manager in it; update
1091 // the locations to refer into the new source manager. Since we've
1092 // been careful to make sure that the source manager's state
1093 // before and after are identical, so that we can reuse the source
1095 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1097 // Keep track of the override buffer;
1098 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1101 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1102 new TopLevelDeclTrackerAction(*this));
1104 // Recover resources if we crash before exiting this method.
1105 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1106 ActCleanup(Act.get());
1108 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1111 if (SavedMainFileBuffer)
1112 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1113 PreambleDiagnostics, StoredDiagnostics);
1115 PreambleSrcLocCache.clear();
1117 if (!Act->Execute())
1120 transferASTDataFromCompilerInstance(*Clang);
1122 Act->EndSourceFile();
1124 FailedParseDiagnostics.clear();
1129 // Remove the overridden buffer we used for the preamble.
1130 SavedMainFileBuffer = nullptr;
1132 // Keep the ownership of the data in the ASTUnit because the client may
1133 // want to see the diagnostics.
1134 transferASTDataFromCompilerInstance(*Clang);
1135 FailedParseDiagnostics.swap(StoredDiagnostics);
1136 StoredDiagnostics.clear();
1137 NumStoredDiagnosticsFromDriver = 0;
1141 static std::pair<unsigned, unsigned>
1142 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1143 const LangOptions &LangOpts) {
1144 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1145 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1146 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1147 return std::make_pair(Offset, EndOffset);
1150 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1151 const LangOptions &LangOpts,
1152 const FixItHint &InFix) {
1153 ASTUnit::StandaloneFixIt OutFix;
1154 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1155 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1157 OutFix.CodeToInsert = InFix.CodeToInsert;
1158 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1162 static ASTUnit::StandaloneDiagnostic
1163 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1164 const StoredDiagnostic &InDiag) {
1165 ASTUnit::StandaloneDiagnostic OutDiag;
1166 OutDiag.ID = InDiag.getID();
1167 OutDiag.Level = InDiag.getLevel();
1168 OutDiag.Message = InDiag.getMessage();
1169 OutDiag.LocOffset = 0;
1170 if (InDiag.getLocation().isInvalid())
1172 const SourceManager &SM = InDiag.getLocation().getManager();
1173 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1174 OutDiag.Filename = SM.getFilename(FileLoc);
1175 if (OutDiag.Filename.empty())
1177 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1178 for (const CharSourceRange &Range : InDiag.getRanges())
1179 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1180 for (const FixItHint &FixIt : InDiag.getFixIts())
1181 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1186 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1187 /// the source file.
1189 /// This routine will compute the preamble of the main source file. If a
1190 /// non-trivial preamble is found, it will precompile that preamble into a
1191 /// precompiled header so that the precompiled preamble can be used to reduce
1192 /// reparsing time. If a precompiled preamble has already been constructed,
1193 /// this routine will determine if it is still valid and, if so, avoid
1194 /// rebuilding the precompiled preamble.
1196 /// \param AllowRebuild When true (the default), this routine is
1197 /// allowed to rebuild the precompiled preamble if it is found to be
1200 /// \param MaxLines When non-zero, the maximum number of lines that
1201 /// can occur within the preamble.
1203 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1204 /// buffer that should be used in place of the main file when doing so.
1205 /// Otherwise, returns a NULL pointer.
1206 std::unique_ptr<llvm::MemoryBuffer>
1207 ASTUnit::getMainBufferWithPrecompiledPreamble(
1208 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1209 const CompilerInvocation &PreambleInvocationIn,
1210 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
1211 unsigned MaxLines) {
1214 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1215 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1216 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1218 if (!MainFileBuffer)
1221 PreambleBounds Bounds =
1222 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1223 MainFileBuffer.get(), MaxLines);
1228 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1230 // Okay! We can re-use the precompiled preamble.
1232 // Set the state of the diagnostic object to mimic its state
1233 // after parsing the preamble.
1234 getDiagnostics().Reset();
1235 ProcessWarningOptions(getDiagnostics(),
1236 PreambleInvocationIn.getDiagnosticOpts());
1237 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1239 PreambleRebuildCounter = 1;
1240 return MainFileBuffer;
1243 PreambleDiagnostics.clear();
1244 TopLevelDeclsInPreamble.clear();
1245 PreambleRebuildCounter = 1;
1249 // If the preamble rebuild counter > 1, it's because we previously
1250 // failed to build a preamble and we're not yet ready to try
1251 // again. Decrement the counter and return a failure.
1252 if (PreambleRebuildCounter > 1) {
1253 --PreambleRebuildCounter;
1257 assert(!Preamble && "No Preamble should be stored at that point");
1258 // If we aren't allowed to rebuild the precompiled preamble, just
1263 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1264 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1265 ASTUnitPreambleCallbacks Callbacks;
1267 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1268 if (CaptureDiagnostics)
1269 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1270 &NewPreambleDiagsStandalone);
1272 // We did not previously compute a preamble, or it can't be reused anyway.
1273 SimpleTimer PreambleTimer(WantTiming);
1274 PreambleTimer.setOutput("Precompiling preamble");
1276 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1277 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1278 PCHContainerOps, Callbacks);
1280 Preamble = std::move(*NewPreamble);
1281 PreambleRebuildCounter = 1;
1283 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1284 case BuildPreambleError::CouldntCreateTempFile:
1285 case BuildPreambleError::PreambleIsEmpty:
1286 // Try again next time.
1287 PreambleRebuildCounter = 1;
1289 case BuildPreambleError::CouldntCreateTargetInfo:
1290 case BuildPreambleError::BeginSourceFileFailed:
1291 case BuildPreambleError::CouldntEmitPCH:
1292 case BuildPreambleError::CouldntCreateVFSOverlay:
1293 // These erros are more likely to repeat, retry after some period.
1294 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1297 llvm_unreachable("unexpected BuildPreambleError");
1301 assert(Preamble && "Preamble wasn't built");
1303 TopLevelDecls.clear();
1304 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1305 PreambleTopLevelHashValue = Callbacks.getHash();
1307 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1309 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1310 StoredDiagnostics = std::move(NewPreambleDiags);
1311 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1313 // If the hash of top-level entities differs from the hash of the top-level
1314 // entities the last time we rebuilt the preamble, clear out the completion
1316 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1317 CompletionCacheTopLevelHashValue = 0;
1318 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1321 return MainFileBuffer;
1324 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1325 assert(Preamble && "Should only be called when preamble was built");
1327 std::vector<Decl *> Resolved;
1328 Resolved.reserve(TopLevelDeclsInPreamble.size());
1329 ExternalASTSource &Source = *getASTContext().getExternalSource();
1330 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1331 // Resolve the declaration ID to an actual declaration, possibly
1332 // deserializing the declaration in the process.
1333 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1334 Resolved.push_back(D);
1336 TopLevelDeclsInPreamble.clear();
1337 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1340 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1341 // Steal the created target, context, and preprocessor if they have been
1343 assert(CI.hasInvocation() && "missing invocation");
1344 LangOpts = CI.getInvocation().LangOpts;
1345 TheSema = CI.takeSema();
1346 Consumer = CI.takeASTConsumer();
1347 if (CI.hasASTContext())
1348 Ctx = &CI.getASTContext();
1349 if (CI.hasPreprocessor())
1350 PP = CI.getPreprocessorPtr();
1351 CI.setSourceManager(nullptr);
1352 CI.setFileManager(nullptr);
1354 Target = &CI.getTarget();
1355 Reader = CI.getModuleManager();
1356 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1359 StringRef ASTUnit::getMainFileName() const {
1360 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1361 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1363 return Input.getFile();
1365 return Input.getBuffer()->getBufferIdentifier();
1369 if (const FileEntry *
1370 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1371 return FE->getName();
1377 StringRef ASTUnit::getASTFileName() const {
1378 if (!isMainFileAST())
1381 serialization::ModuleFile &
1382 Mod = Reader->getModuleManager().getPrimaryModule();
1383 return Mod.FileName;
1386 std::unique_ptr<ASTUnit>
1387 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1388 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1389 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1390 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1391 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1392 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1393 createVFSFromCompilerInvocation(*CI, *Diags);
1396 AST->Diagnostics = Diags;
1397 AST->FileSystemOpts = CI->getFileSystemOpts();
1398 AST->Invocation = std::move(CI);
1399 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1400 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1401 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1402 UserFilesAreVolatile);
1403 AST->PCMCache = new MemoryBufferCache;
1408 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1409 std::shared_ptr<CompilerInvocation> CI,
1410 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1411 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1412 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1413 bool OnlyLocalDecls, bool CaptureDiagnostics,
1414 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1415 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1416 std::unique_ptr<ASTUnit> *ErrAST) {
1417 assert(CI && "A CompilerInvocation is required");
1419 std::unique_ptr<ASTUnit> OwnAST;
1420 ASTUnit *AST = Unit;
1422 // Create the AST unit.
1423 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1429 if (!ResourceFilesPath.empty()) {
1430 // Override the resources path.
1431 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1433 AST->OnlyLocalDecls = OnlyLocalDecls;
1434 AST->CaptureDiagnostics = CaptureDiagnostics;
1435 if (PrecompilePreambleAfterNParses > 0)
1436 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1437 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1438 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1439 AST->IncludeBriefCommentsInCodeCompletion
1440 = IncludeBriefCommentsInCodeCompletion;
1442 // Recover resources if we crash before exiting this method.
1443 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1444 ASTUnitCleanup(OwnAST.get());
1445 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1446 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1447 DiagCleanup(Diags.get());
1449 // We'll manage file buffers ourselves.
1450 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1451 CI->getFrontendOpts().DisableFree = false;
1452 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1454 // Create the compiler instance to use for building the AST.
1455 std::unique_ptr<CompilerInstance> Clang(
1456 new CompilerInstance(std::move(PCHContainerOps)));
1458 // Recover resources if we crash before exiting this method.
1459 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1460 CICleanup(Clang.get());
1462 Clang->setInvocation(std::move(CI));
1463 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1465 // Set up diagnostics, capturing any diagnostics that would
1466 // otherwise be dropped.
1467 Clang->setDiagnostics(&AST->getDiagnostics());
1469 // Create the target instance.
1470 Clang->setTarget(TargetInfo::CreateTargetInfo(
1471 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1472 if (!Clang->hasTarget())
1475 // Inform the target of the language options.
1477 // FIXME: We shouldn't need to do this, the target should be immutable once
1478 // created. This complexity should be lifted elsewhere.
1479 Clang->getTarget().adjust(Clang->getLangOpts());
1481 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1482 "Invocation must have exactly one source file!");
1483 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1484 InputKind::Source &&
1485 "FIXME: AST inputs not yet supported here!");
1486 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1487 InputKind::LLVM_IR &&
1488 "IR inputs not support here!");
1490 // Configure the various subsystems.
1491 AST->TheSema.reset();
1494 AST->Reader = nullptr;
1496 // Create a file manager object to provide access to and cache the filesystem.
1497 Clang->setFileManager(&AST->getFileManager());
1499 // Create the source manager.
1500 Clang->setSourceManager(&AST->getSourceManager());
1502 FrontendAction *Act = Action;
1504 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1506 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1507 Act = TrackerAct.get();
1510 // Recover resources if we crash before exiting this method.
1511 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1512 ActCleanup(TrackerAct.get());
1514 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1515 AST->transferASTDataFromCompilerInstance(*Clang);
1516 if (OwnAST && ErrAST)
1517 ErrAST->swap(OwnAST);
1522 if (Persistent && !TrackerAct) {
1523 Clang->getPreprocessor().addPPCallbacks(
1524 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1525 AST->getCurrentTopLevelHashValue()));
1526 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1527 if (Clang->hasASTConsumer())
1528 Consumers.push_back(Clang->takeASTConsumer());
1529 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1530 *AST, AST->getCurrentTopLevelHashValue()));
1531 Clang->setASTConsumer(
1532 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1534 if (!Act->Execute()) {
1535 AST->transferASTDataFromCompilerInstance(*Clang);
1536 if (OwnAST && ErrAST)
1537 ErrAST->swap(OwnAST);
1542 // Steal the created target, context, and preprocessor.
1543 AST->transferASTDataFromCompilerInstance(*Clang);
1545 Act->EndSourceFile();
1548 return OwnAST.release();
1553 bool ASTUnit::LoadFromCompilerInvocation(
1554 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1555 unsigned PrecompilePreambleAfterNParses,
1556 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1560 assert(VFS && "VFS is null");
1562 // We'll manage file buffers ourselves.
1563 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1564 Invocation->getFrontendOpts().DisableFree = false;
1565 getDiagnostics().Reset();
1566 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1568 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1569 if (PrecompilePreambleAfterNParses > 0) {
1570 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1571 OverrideMainBuffer =
1572 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1573 getDiagnostics().Reset();
1574 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1577 SimpleTimer ParsingTimer(WantTiming);
1578 ParsingTimer.setOutput("Parsing " + getMainFileName());
1580 // Recover resources if we crash before exiting this method.
1581 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1582 MemBufferCleanup(OverrideMainBuffer.get());
1584 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1587 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1588 std::shared_ptr<CompilerInvocation> CI,
1589 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1590 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1591 bool OnlyLocalDecls, bool CaptureDiagnostics,
1592 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1593 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1594 bool UserFilesAreVolatile) {
1595 // Create the AST unit.
1596 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1597 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1598 AST->Diagnostics = Diags;
1599 AST->OnlyLocalDecls = OnlyLocalDecls;
1600 AST->CaptureDiagnostics = CaptureDiagnostics;
1601 AST->TUKind = TUKind;
1602 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1603 AST->IncludeBriefCommentsInCodeCompletion
1604 = IncludeBriefCommentsInCodeCompletion;
1605 AST->Invocation = std::move(CI);
1606 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1607 AST->FileMgr = FileMgr;
1608 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1610 // Recover resources if we crash before exiting this method.
1611 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1612 ASTUnitCleanup(AST.get());
1613 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1614 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1615 DiagCleanup(Diags.get());
1617 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1618 PrecompilePreambleAfterNParses,
1619 AST->FileMgr->getVirtualFileSystem()))
1624 ASTUnit *ASTUnit::LoadFromCommandLine(
1625 const char **ArgBegin, const char **ArgEnd,
1626 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1627 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1628 bool OnlyLocalDecls, bool CaptureDiagnostics,
1629 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1630 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1631 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1632 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1633 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1634 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1635 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1636 assert(Diags.get() && "no DiagnosticsEngine was provided");
1638 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1640 std::shared_ptr<CompilerInvocation> CI;
1644 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1645 &StoredDiagnostics, nullptr);
1647 CI = clang::createInvocationFromCommandLine(
1648 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1653 // Override any files that need remapping
1654 for (const auto &RemappedFile : RemappedFiles) {
1655 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1656 RemappedFile.second);
1658 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1659 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1660 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1661 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
1662 PPOpts.SingleFileParseMode = SingleFileParse;
1664 // Override the resources path.
1665 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1667 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1670 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1672 // Create the AST unit.
1673 std::unique_ptr<ASTUnit> AST;
1674 AST.reset(new ASTUnit(false));
1675 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1676 AST->Diagnostics = Diags;
1677 AST->FileSystemOpts = CI->getFileSystemOpts();
1679 VFS = vfs::getRealFileSystem();
1680 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1683 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1684 AST->PCMCache = new MemoryBufferCache;
1685 AST->OnlyLocalDecls = OnlyLocalDecls;
1686 AST->CaptureDiagnostics = CaptureDiagnostics;
1687 AST->TUKind = TUKind;
1688 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1689 AST->IncludeBriefCommentsInCodeCompletion
1690 = IncludeBriefCommentsInCodeCompletion;
1691 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1692 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1693 AST->StoredDiagnostics.swap(StoredDiagnostics);
1694 AST->Invocation = CI;
1695 if (ForSerialization)
1696 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
1697 // Zero out now to ease cleanup during crash recovery.
1701 // Recover resources if we crash before exiting this method.
1702 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1703 ASTUnitCleanup(AST.get());
1705 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1706 PrecompilePreambleAfterNParses,
1708 // Some error occurred, if caller wants to examine diagnostics, pass it the
1711 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1717 return AST.release();
1720 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1721 ArrayRef<RemappedFile> RemappedFiles,
1722 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1727 assert(FileMgr && "FileMgr is null on Reparse call");
1728 VFS = FileMgr->getVirtualFileSystem();
1731 clearFileLevelDecls();
1733 SimpleTimer ParsingTimer(WantTiming);
1734 ParsingTimer.setOutput("Reparsing " + getMainFileName());
1737 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1738 for (const auto &RB : PPOpts.RemappedFileBuffers)
1741 Invocation->getPreprocessorOpts().clearRemappedFiles();
1742 for (const auto &RemappedFile : RemappedFiles) {
1743 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1744 RemappedFile.second);
1747 // If we have a preamble file lying around, or if we might try to
1748 // build a precompiled preamble, do so now.
1749 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1750 if (Preamble || PreambleRebuildCounter > 0)
1751 OverrideMainBuffer =
1752 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1755 // Clear out the diagnostics state.
1757 getDiagnostics().Reset();
1758 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1759 if (OverrideMainBuffer)
1760 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1762 // Parse the sources
1764 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1766 // If we're caching global code-completion results, and the top-level
1767 // declarations have changed, clear out the code-completion cache.
1768 if (!Result && ShouldCacheCodeCompletionResults &&
1769 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1770 CacheCodeCompletionResults();
1772 // We now need to clear out the completion info related to this translation
1773 // unit; it'll be recreated if necessary.
1779 void ASTUnit::ResetForParse() {
1780 SavedMainFileBuffer.reset();
1788 TopLevelDecls.clear();
1789 clearFileLevelDecls();
1792 //----------------------------------------------------------------------------//
1794 //----------------------------------------------------------------------------//
1797 /// \brief Code completion consumer that combines the cached code-completion
1798 /// results from an ASTUnit with the code-completion results provided to it,
1799 /// then passes the result on to
1800 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1801 uint64_t NormalContexts;
1803 CodeCompleteConsumer &Next;
1806 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1807 const CodeCompleteOptions &CodeCompleteOpts)
1808 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1809 AST(AST), Next(Next)
1811 // Compute the set of contexts in which we will look when we don't have
1812 // any information about the specific context.
1814 = (1LL << CodeCompletionContext::CCC_TopLevel)
1815 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1816 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1817 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1818 | (1LL << CodeCompletionContext::CCC_Statement)
1819 | (1LL << CodeCompletionContext::CCC_Expression)
1820 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1821 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1822 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1823 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1824 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1825 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1826 | (1LL << CodeCompletionContext::CCC_Recovery);
1828 if (AST.getASTContext().getLangOpts().CPlusPlus)
1829 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1830 | (1LL << CodeCompletionContext::CCC_UnionTag)
1831 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1834 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1835 CodeCompletionResult *Results,
1836 unsigned NumResults) override;
1838 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1839 OverloadCandidate *Candidates,
1840 unsigned NumCandidates) override {
1841 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1844 CodeCompletionAllocator &getAllocator() override {
1845 return Next.getAllocator();
1848 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1849 return Next.getCodeCompletionTUInfo();
1852 } // anonymous namespace
1854 /// \brief Helper function that computes which global names are hidden by the
1855 /// local code-completion results.
1856 static void CalculateHiddenNames(const CodeCompletionContext &Context,
1857 CodeCompletionResult *Results,
1858 unsigned NumResults,
1860 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1861 bool OnlyTagNames = false;
1862 switch (Context.getKind()) {
1863 case CodeCompletionContext::CCC_Recovery:
1864 case CodeCompletionContext::CCC_TopLevel:
1865 case CodeCompletionContext::CCC_ObjCInterface:
1866 case CodeCompletionContext::CCC_ObjCImplementation:
1867 case CodeCompletionContext::CCC_ObjCIvarList:
1868 case CodeCompletionContext::CCC_ClassStructUnion:
1869 case CodeCompletionContext::CCC_Statement:
1870 case CodeCompletionContext::CCC_Expression:
1871 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1872 case CodeCompletionContext::CCC_DotMemberAccess:
1873 case CodeCompletionContext::CCC_ArrowMemberAccess:
1874 case CodeCompletionContext::CCC_ObjCPropertyAccess:
1875 case CodeCompletionContext::CCC_Namespace:
1876 case CodeCompletionContext::CCC_Type:
1877 case CodeCompletionContext::CCC_Name:
1878 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
1879 case CodeCompletionContext::CCC_ParenthesizedExpression:
1880 case CodeCompletionContext::CCC_ObjCInterfaceName:
1883 case CodeCompletionContext::CCC_EnumTag:
1884 case CodeCompletionContext::CCC_UnionTag:
1885 case CodeCompletionContext::CCC_ClassOrStructTag:
1886 OnlyTagNames = true;
1889 case CodeCompletionContext::CCC_ObjCProtocolName:
1890 case CodeCompletionContext::CCC_MacroName:
1891 case CodeCompletionContext::CCC_MacroNameUse:
1892 case CodeCompletionContext::CCC_PreprocessorExpression:
1893 case CodeCompletionContext::CCC_PreprocessorDirective:
1894 case CodeCompletionContext::CCC_NaturalLanguage:
1895 case CodeCompletionContext::CCC_SelectorName:
1896 case CodeCompletionContext::CCC_TypeQualifiers:
1897 case CodeCompletionContext::CCC_Other:
1898 case CodeCompletionContext::CCC_OtherWithMacros:
1899 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1900 case CodeCompletionContext::CCC_ObjCClassMessage:
1901 case CodeCompletionContext::CCC_ObjCCategoryName:
1902 // We're looking for nothing, or we're looking for names that cannot
1907 typedef CodeCompletionResult Result;
1908 for (unsigned I = 0; I != NumResults; ++I) {
1909 if (Results[I].Kind != Result::RK_Declaration)
1913 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1915 bool Hiding = false;
1917 Hiding = (IDNS & Decl::IDNS_Tag);
1919 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
1920 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1921 Decl::IDNS_NonMemberOperator);
1922 if (Ctx.getLangOpts().CPlusPlus)
1923 HiddenIDNS |= Decl::IDNS_Tag;
1924 Hiding = (IDNS & HiddenIDNS);
1930 DeclarationName Name = Results[I].Declaration->getDeclName();
1931 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1932 HiddenNames.insert(Identifier->getName());
1934 HiddenNames.insert(Name.getAsString());
1938 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1939 CodeCompletionContext Context,
1940 CodeCompletionResult *Results,
1941 unsigned NumResults) {
1942 // Merge the results we were given with the results we cached.
1943 bool AddedResult = false;
1944 uint64_t InContexts =
1945 Context.getKind() == CodeCompletionContext::CCC_Recovery
1946 ? NormalContexts : (1LL << Context.getKind());
1947 // Contains the set of names that are hidden by "local" completion results.
1948 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
1949 typedef CodeCompletionResult Result;
1950 SmallVector<Result, 8> AllResults;
1951 for (ASTUnit::cached_completion_iterator
1952 C = AST.cached_completion_begin(),
1953 CEnd = AST.cached_completion_end();
1955 // If the context we are in matches any of the contexts we are
1956 // interested in, we'll add this result.
1957 if ((C->ShowInContexts & InContexts) == 0)
1960 // If we haven't added any results previously, do so now.
1962 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1964 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1968 // Determine whether this global completion result is hidden by a local
1969 // completion result. If so, skip it.
1970 if (C->Kind != CXCursor_MacroDefinition &&
1971 HiddenNames.count(C->Completion->getTypedText()))
1974 // Adjust priority based on similar type classes.
1975 unsigned Priority = C->Priority;
1976 CodeCompletionString *Completion = C->Completion;
1977 if (!Context.getPreferredType().isNull()) {
1978 if (C->Kind == CXCursor_MacroDefinition) {
1979 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1981 Context.getPreferredType()->isAnyPointerType());
1982 } else if (C->Type) {
1983 CanQualType Expected
1984 = S.Context.getCanonicalType(
1985 Context.getPreferredType().getUnqualifiedType());
1986 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1987 if (ExpectedSTC == C->TypeClass) {
1988 // We know this type is similar; check for an exact match.
1989 llvm::StringMap<unsigned> &CachedCompletionTypes
1990 = AST.getCachedCompletionTypes();
1991 llvm::StringMap<unsigned>::iterator Pos
1992 = CachedCompletionTypes.find(QualType(Expected).getAsString());
1993 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1994 Priority /= CCF_ExactTypeMatch;
1996 Priority /= CCF_SimilarTypeMatch;
2001 // Adjust the completion string, if required.
2002 if (C->Kind == CXCursor_MacroDefinition &&
2003 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2004 // Create a new code-completion string that just contains the
2005 // macro name, without its arguments.
2006 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2007 CCP_CodePattern, C->Availability);
2008 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2009 Priority = CCP_CodePattern;
2010 Completion = Builder.TakeString();
2013 AllResults.push_back(Result(Completion, Priority, C->Kind,
2017 // If we did not add any cached completion results, just forward the
2018 // results we were given to the next consumer.
2020 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2024 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2028 void ASTUnit::CodeComplete(
2029 StringRef File, unsigned Line, unsigned Column,
2030 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2031 bool IncludeCodePatterns, bool IncludeBriefComments,
2032 CodeCompleteConsumer &Consumer,
2033 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2034 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2035 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2036 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2040 SimpleTimer CompletionTimer(WantTiming);
2041 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2042 Twine(Line) + ":" + Twine(Column));
2044 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2046 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2047 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2048 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2050 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2051 CachedCompletionResults.empty();
2052 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2053 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2054 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2056 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2058 FrontendOpts.CodeCompletionAt.FileName = File;
2059 FrontendOpts.CodeCompletionAt.Line = Line;
2060 FrontendOpts.CodeCompletionAt.Column = Column;
2062 // Set the language options appropriately.
2063 LangOpts = *CCInvocation->getLangOpts();
2065 // Spell-checking and warnings are wasteful during code-completion.
2066 LangOpts.SpellChecking = false;
2067 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2069 std::unique_ptr<CompilerInstance> Clang(
2070 new CompilerInstance(PCHContainerOps));
2072 // Recover resources if we crash before exiting this method.
2073 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2074 CICleanup(Clang.get());
2076 auto &Inv = *CCInvocation;
2077 Clang->setInvocation(std::move(CCInvocation));
2078 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2080 // Set up diagnostics, capturing any diagnostics produced.
2081 Clang->setDiagnostics(&Diag);
2082 CaptureDroppedDiagnostics Capture(true,
2083 Clang->getDiagnostics(),
2084 &StoredDiagnostics, nullptr);
2085 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2087 // Create the target instance.
2088 Clang->setTarget(TargetInfo::CreateTargetInfo(
2089 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2090 if (!Clang->hasTarget()) {
2091 Clang->setInvocation(nullptr);
2095 // Inform the target of the language options.
2097 // FIXME: We shouldn't need to do this, the target should be immutable once
2098 // created. This complexity should be lifted elsewhere.
2099 Clang->getTarget().adjust(Clang->getLangOpts());
2101 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2102 "Invocation must have exactly one source file!");
2103 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2104 InputKind::Source &&
2105 "FIXME: AST inputs not yet supported here!");
2106 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2107 InputKind::LLVM_IR &&
2108 "IR inputs not support here!");
2110 // Use the source and file managers that we were given.
2111 Clang->setFileManager(&FileMgr);
2112 Clang->setSourceManager(&SourceMgr);
2115 PreprocessorOpts.clearRemappedFiles();
2116 PreprocessorOpts.RetainRemappedFileBuffers = true;
2117 for (const auto &RemappedFile : RemappedFiles) {
2118 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2119 OwnedBuffers.push_back(RemappedFile.second);
2122 // Use the code completion consumer we were given, but adding any cached
2123 // code-completion results.
2124 AugmentedCodeCompleteConsumer *AugmentedConsumer
2125 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2126 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2128 // If we have a precompiled preamble, try to use it. We only allow
2129 // the use of the precompiled preamble if we're if the completion
2130 // point is within the main file, after the end of the precompiled
2132 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2134 std::string CompleteFilePath(File);
2136 auto VFS = FileMgr.getVirtualFileSystem();
2137 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2138 if (CompleteFileStatus) {
2139 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2141 std::string MainPath(OriginalSourceFile);
2142 auto MainStatus = VFS->status(MainPath);
2144 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2145 if (CompleteFileID == MainID && Line > 1)
2146 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2147 PCHContainerOps, Inv, VFS, false, Line - 1);
2152 // If the main file has been overridden due to the use of a preamble,
2153 // make that override happen and introduce the preamble.
2154 if (OverrideMainBuffer) {
2155 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
2156 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
2157 OwnedBuffers.push_back(OverrideMainBuffer.release());
2159 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2160 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2163 // Disable the preprocessing record if modules are not enabled.
2164 if (!Clang->getLangOpts().Modules)
2165 PreprocessorOpts.DetailedRecord = false;
2167 std::unique_ptr<SyntaxOnlyAction> Act;
2168 Act.reset(new SyntaxOnlyAction);
2169 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2171 Act->EndSourceFile();
2175 bool ASTUnit::Save(StringRef File) {
2176 if (HadModuleLoaderFatalFailure)
2179 // Write to a temporary file and later rename it to the actual file, to avoid
2180 // possible race conditions.
2181 SmallString<128> TempPath;
2183 TempPath += "-%%%%%%%%";
2185 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2188 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2189 // unconditionally create a stat cache when we parse the file?
2190 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2194 if (Out.has_error()) {
2199 if (llvm::sys::fs::rename(TempPath, File)) {
2200 llvm::sys::fs::remove(TempPath);
2207 static bool serializeUnit(ASTWriter &Writer,
2208 SmallVectorImpl<char> &Buffer,
2212 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2214 // Write the generated bitstream to "Out".
2215 if (!Buffer.empty())
2216 OS.write(Buffer.data(), Buffer.size());
2221 bool ASTUnit::serialize(raw_ostream &OS) {
2222 // For serialization we are lenient if the errors were only warn-as-error kind.
2223 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2226 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2227 getSema(), hasErrors, OS);
2229 SmallString<128> Buffer;
2230 llvm::BitstreamWriter Stream(Buffer);
2231 MemoryBufferCache PCMCache;
2232 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2233 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2236 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2238 void ASTUnit::TranslateStoredDiagnostics(
2239 FileManager &FileMgr,
2240 SourceManager &SrcMgr,
2241 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2242 SmallVectorImpl<StoredDiagnostic> &Out) {
2243 // Map the standalone diagnostic into the new source manager. We also need to
2244 // remap all the locations to the new view. This includes the diag location,
2245 // any associated source ranges, and the source ranges of associated fix-its.
2246 // FIXME: There should be a cleaner way to do this.
2247 SmallVector<StoredDiagnostic, 4> Result;
2248 Result.reserve(Diags.size());
2250 for (const StandaloneDiagnostic &SD : Diags) {
2251 // Rebuild the StoredDiagnostic.
2252 if (SD.Filename.empty())
2254 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2257 SourceLocation FileLoc;
2258 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2259 if (ItFileID == PreambleSrcLocCache.end()) {
2260 FileID FID = SrcMgr.translateFile(FE);
2261 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2262 PreambleSrcLocCache[SD.Filename] = FileLoc;
2264 FileLoc = ItFileID->getValue();
2267 if (FileLoc.isInvalid())
2269 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2270 FullSourceLoc Loc(L, SrcMgr);
2272 SmallVector<CharSourceRange, 4> Ranges;
2273 Ranges.reserve(SD.Ranges.size());
2274 for (const auto &Range : SD.Ranges) {
2275 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2276 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2277 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2280 SmallVector<FixItHint, 2> FixIts;
2281 FixIts.reserve(SD.FixIts.size());
2282 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2283 FixIts.push_back(FixItHint());
2284 FixItHint &FH = FixIts.back();
2285 FH.CodeToInsert = FixIt.CodeToInsert;
2286 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2287 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2288 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2291 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2292 SD.Message, Loc, Ranges, FixIts));
2297 void ASTUnit::addFileLevelDecl(Decl *D) {
2300 // We only care about local declarations.
2301 if (D->isFromASTFile())
2304 SourceManager &SM = *SourceMgr;
2305 SourceLocation Loc = D->getLocation();
2306 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2309 // We only keep track of the file-level declarations of each file.
2310 if (!D->getLexicalDeclContext()->isFileContext())
2313 SourceLocation FileLoc = SM.getFileLoc(Loc);
2314 assert(SM.isLocalSourceLocation(FileLoc));
2317 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2318 if (FID.isInvalid())
2321 LocDeclsTy *&Decls = FileDecls[FID];
2323 Decls = new LocDeclsTy();
2325 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2327 if (Decls->empty() || Decls->back().first <= Offset) {
2328 Decls->push_back(LocDecl);
2332 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2333 LocDecl, llvm::less_first());
2335 Decls->insert(I, LocDecl);
2338 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2339 SmallVectorImpl<Decl *> &Decls) {
2340 if (File.isInvalid())
2343 if (SourceMgr->isLoadedFileID(File)) {
2344 assert(Ctx->getExternalSource() && "No external source!");
2345 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2349 FileDeclsTy::iterator I = FileDecls.find(File);
2350 if (I == FileDecls.end())
2353 LocDeclsTy &LocDecls = *I->second;
2354 if (LocDecls.empty())
2357 LocDeclsTy::iterator BeginIt =
2358 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2359 std::make_pair(Offset, (Decl *)nullptr),
2360 llvm::less_first());
2361 if (BeginIt != LocDecls.begin())
2364 // If we are pointing at a top-level decl inside an objc container, we need
2365 // to backtrack until we find it otherwise we will fail to report that the
2366 // region overlaps with an objc container.
2367 while (BeginIt != LocDecls.begin() &&
2368 BeginIt->second->isTopLevelDeclInObjCContainer())
2371 LocDeclsTy::iterator EndIt = std::upper_bound(
2372 LocDecls.begin(), LocDecls.end(),
2373 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2374 if (EndIt != LocDecls.end())
2377 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2378 Decls.push_back(DIt->second);
2381 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2382 unsigned Line, unsigned Col) const {
2383 const SourceManager &SM = getSourceManager();
2384 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2385 return SM.getMacroArgExpandedLocation(Loc);
2388 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2389 unsigned Offset) const {
2390 const SourceManager &SM = getSourceManager();
2391 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2392 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2395 /// \brief If \arg Loc is a loaded location from the preamble, returns
2396 /// the corresponding local location of the main file, otherwise it returns
2398 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2401 PreambleID = SourceMgr->getPreambleFileID();
2403 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2407 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2408 SourceLocation FileLoc
2409 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2410 return FileLoc.getLocWithOffset(Offs);
2416 /// \brief If \arg Loc is a local location of the main file but inside the
2417 /// preamble chunk, returns the corresponding loaded location from the
2418 /// preamble, otherwise it returns \arg Loc.
2419 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2422 PreambleID = SourceMgr->getPreambleFileID();
2424 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2428 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2429 Offs < Preamble->getBounds().Size) {
2430 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2431 return FileLoc.getLocWithOffset(Offs);
2437 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2440 FID = SourceMgr->getPreambleFileID();
2442 if (Loc.isInvalid() || FID.isInvalid())
2445 return SourceMgr->isInFileID(Loc, FID);
2448 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2451 FID = SourceMgr->getMainFileID();
2453 if (Loc.isInvalid() || FID.isInvalid())
2456 return SourceMgr->isInFileID(Loc, FID);
2459 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2462 FID = SourceMgr->getPreambleFileID();
2464 if (FID.isInvalid())
2465 return SourceLocation();
2467 return SourceMgr->getLocForEndOfFile(FID);
2470 SourceLocation ASTUnit::getStartOfMainFileID() {
2473 FID = SourceMgr->getMainFileID();
2475 if (FID.isInvalid())
2476 return SourceLocation();
2478 return SourceMgr->getLocForStartOfFile(FID);
2481 llvm::iterator_range<PreprocessingRecord::iterator>
2482 ASTUnit::getLocalPreprocessingEntities() const {
2483 if (isMainFileAST()) {
2484 serialization::ModuleFile &
2485 Mod = Reader->getModuleManager().getPrimaryModule();
2486 return Reader->getModulePreprocessedEntities(Mod);
2489 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2490 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2492 return llvm::make_range(PreprocessingRecord::iterator(),
2493 PreprocessingRecord::iterator());
2496 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2497 if (isMainFileAST()) {
2498 serialization::ModuleFile &
2499 Mod = Reader->getModuleManager().getPrimaryModule();
2500 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2501 if (!Fn(context, D))
2508 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2509 TLEnd = top_level_end();
2510 TL != TLEnd; ++TL) {
2511 if (!Fn(context, *TL))
2518 const FileEntry *ASTUnit::getPCHFile() {
2522 serialization::ModuleFile *Mod = nullptr;
2523 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2525 case serialization::MK_ImplicitModule:
2526 case serialization::MK_ExplicitModule:
2527 case serialization::MK_PrebuiltModule:
2528 return true; // skip dependencies.
2529 case serialization::MK_PCH:
2531 return true; // found it.
2532 case serialization::MK_Preamble:
2533 return false; // look in dependencies.
2534 case serialization::MK_MainFile:
2535 return false; // look in dependencies.
2546 bool ASTUnit::isModuleFile() {
2547 return isMainFileAST() && getLangOpts().isCompilingModule();
2550 InputKind ASTUnit::getInputKind() const {
2551 auto &LangOpts = getLangOpts();
2553 InputKind::Language Lang;
2554 if (LangOpts.OpenCL)
2555 Lang = InputKind::OpenCL;
2556 else if (LangOpts.CUDA)
2557 Lang = InputKind::CUDA;
2558 else if (LangOpts.RenderScript)
2559 Lang = InputKind::RenderScript;
2560 else if (LangOpts.CPlusPlus)
2561 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2563 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2565 InputKind::Format Fmt = InputKind::Source;
2566 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2567 Fmt = InputKind::ModuleMap;
2569 // We don't know if input was preprocessed. Assume not.
2572 return InputKind(Lang, Fmt, PP);
2576 ASTUnit::ConcurrencyState::ConcurrencyState() {
2577 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2580 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2581 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2584 void ASTUnit::ConcurrencyState::start() {
2585 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2586 assert(acquired && "Concurrent access to ASTUnit!");
2589 void ASTUnit::ConcurrencyState::finish() {
2590 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2595 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2596 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2597 void ASTUnit::ConcurrencyState::start() {}
2598 void ASTUnit::ConcurrencyState::finish() {}