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 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
87 /// \brief Erase the preamble file.
88 void CleanPreambleFile();
90 /// \brief Erase temporary files and the preamble file.
95 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
98 return std::move(*Val);
102 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
105 Output = std::move(*Val);
110 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
111 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
115 static void cleanupOnDiskMapAtExit();
117 typedef llvm::DenseMap<const ASTUnit *,
118 std::unique_ptr<OnDiskData>> OnDiskDataMap;
119 static OnDiskDataMap &getOnDiskDataMap() {
120 static OnDiskDataMap M;
121 static bool hasRegisteredAtExit = false;
122 if (!hasRegisteredAtExit) {
123 hasRegisteredAtExit = true;
124 atexit(cleanupOnDiskMapAtExit);
129 static void cleanupOnDiskMapAtExit() {
130 // Use the mutex because there can be an alive thread destroying an ASTUnit.
131 llvm::MutexGuard Guard(getOnDiskMutex());
132 for (const auto &I : getOnDiskDataMap()) {
133 // We don't worry about freeing the memory associated with OnDiskDataMap.
134 // All we care about is erasing stale files.
139 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
140 // We require the mutex since we are modifying the structure of the
142 llvm::MutexGuard Guard(getOnDiskMutex());
143 OnDiskDataMap &M = getOnDiskDataMap();
146 D = llvm::make_unique<OnDiskData>();
150 static void erasePreambleFile(const ASTUnit *AU) {
151 getOnDiskData(AU).CleanPreambleFile();
154 static void removeOnDiskEntry(const ASTUnit *AU) {
155 // We require the mutex since we are modifying the structure of the
157 llvm::MutexGuard Guard(getOnDiskMutex());
158 OnDiskDataMap &M = getOnDiskDataMap();
159 OnDiskDataMap::iterator I = M.find(AU);
161 I->second->Cleanup();
166 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
167 getOnDiskData(AU).PreambleFile = preambleFile;
170 static const std::string &getPreambleFile(const ASTUnit *AU) {
171 return getOnDiskData(AU).PreambleFile;
174 void OnDiskData::CleanPreambleFile() {
175 if (!PreambleFile.empty()) {
176 llvm::sys::fs::remove(PreambleFile);
177 PreambleFile.clear();
181 void OnDiskData::Cleanup() {
185 struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
190 ASTWriterData(MemoryBufferCache &PCMCache)
191 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
194 void ASTUnit::clearFileLevelDecls() {
195 llvm::DeleteContainerSeconds(FileDecls);
198 /// \brief After failing to build a precompiled preamble (due to
199 /// errors in the source that occurs in the preamble), the number of
200 /// reparses during which we'll skip even trying to precompile the
202 const unsigned DefaultPreambleRebuildInterval = 5;
204 /// \brief Tracks the number of ASTUnit objects that are currently active.
206 /// Used for debugging purposes only.
207 static std::atomic<unsigned> ActiveASTUnitObjects;
209 ASTUnit::ASTUnit(bool _MainFileIsAST)
210 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
211 OnlyLocalDecls(false), CaptureDiagnostics(false),
212 MainFileIsAST(_MainFileIsAST),
213 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
214 OwnsRemappedFileBuffers(true),
215 NumStoredDiagnosticsFromDriver(0),
216 PreambleRebuildCounter(0),
217 NumWarningsInPreamble(0),
218 ShouldCacheCodeCompletionResults(false),
219 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
220 CompletionCacheTopLevelHashValue(0),
221 PreambleTopLevelHashValue(0),
222 CurrentTopLevelHashValue(0),
223 UnsafeToFree(false) {
224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
228 ASTUnit::~ASTUnit() {
229 // If we loaded from an AST file, balance out the BeginSourceFile call.
230 if (MainFileIsAST && getDiagnostics().getClient()) {
231 getDiagnostics().getClient()->EndSourceFile();
234 clearFileLevelDecls();
236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
243 if (Invocation && OwnsRemappedFileBuffers) {
244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
245 for (const auto &RB : PPOpts.RemappedFileBuffers)
249 ClearCachedCompletionResults();
251 if (getenv("LIBCLANG_OBJTRACKING"))
252 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
255 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
256 this->PP = std::move(PP);
259 /// \brief Determine the set of code-completion contexts in which this
260 /// declaration should be shown.
261 static unsigned getDeclShowContexts(const NamedDecl *ND,
262 const LangOptions &LangOpts,
263 bool &IsNestedNameSpecifier) {
264 IsNestedNameSpecifier = false;
266 if (isa<UsingShadowDecl>(ND))
267 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
271 uint64_t Contexts = 0;
272 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
273 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
274 // Types can appear in these contexts.
275 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
276 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
277 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
278 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
279 | (1LL << CodeCompletionContext::CCC_Statement)
280 | (1LL << CodeCompletionContext::CCC_Type)
281 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
283 // In C++, types can appear in expressions contexts (for functional casts).
284 if (LangOpts.CPlusPlus)
285 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
287 // In Objective-C, message sends can send interfaces. In Objective-C++,
288 // all types are available due to functional casts.
289 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
290 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
292 // In Objective-C, you can only be a subclass of another Objective-C class
293 if (isa<ObjCInterfaceDecl>(ND))
294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
296 // Deal with tag names.
297 if (isa<EnumDecl>(ND)) {
298 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
300 // Part of the nested-name-specifier in C++0x.
301 if (LangOpts.CPlusPlus11)
302 IsNestedNameSpecifier = true;
303 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
304 if (Record->isUnion())
305 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
307 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
309 if (LangOpts.CPlusPlus)
310 IsNestedNameSpecifier = true;
311 } else if (isa<ClassTemplateDecl>(ND))
312 IsNestedNameSpecifier = true;
313 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
314 // Values can appear in these contexts.
315 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
316 | (1LL << CodeCompletionContext::CCC_Expression)
317 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
318 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
319 } else if (isa<ObjCProtocolDecl>(ND)) {
320 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
321 } else if (isa<ObjCCategoryDecl>(ND)) {
322 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
323 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
324 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
326 // Part of the nested-name-specifier.
327 IsNestedNameSpecifier = true;
333 void ASTUnit::CacheCodeCompletionResults() {
337 SimpleTimer Timer(WantTiming);
338 Timer.setOutput("Cache global code completions for " + getMainFileName());
340 // Clear out the previous results.
341 ClearCachedCompletionResults();
343 // Gather the set of global code completions.
344 typedef CodeCompletionResult Result;
345 SmallVector<Result, 8> Results;
346 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
347 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
348 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
351 // Translate global code completions into cached completions.
352 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
353 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
355 for (Result &R : Results) {
357 case Result::RK_Declaration: {
358 bool IsNestedNameSpecifier = false;
359 CachedCodeCompletionResult CachedResult;
360 CachedResult.Completion = R.CreateCodeCompletionString(
361 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
362 IncludeBriefCommentsInCodeCompletion);
363 CachedResult.ShowInContexts = getDeclShowContexts(
364 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
365 CachedResult.Priority = R.Priority;
366 CachedResult.Kind = R.CursorKind;
367 CachedResult.Availability = R.Availability;
369 // Keep track of the type of this completion in an ASTContext-agnostic
371 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
372 if (UsageType.isNull()) {
373 CachedResult.TypeClass = STC_Void;
374 CachedResult.Type = 0;
376 CanQualType CanUsageType
377 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
378 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
380 // Determine whether we have already seen this type. If so, we save
381 // ourselves the work of formatting the type string by using the
382 // temporary, CanQualType-based hash table to find the associated value.
383 unsigned &TypeValue = CompletionTypes[CanUsageType];
384 if (TypeValue == 0) {
385 TypeValue = CompletionTypes.size();
386 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
390 CachedResult.Type = TypeValue;
393 CachedCompletionResults.push_back(CachedResult);
395 /// Handle nested-name-specifiers in C++.
396 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
397 !R.StartsNestedNameSpecifier) {
398 // The contexts in which a nested-name-specifier can appear in C++.
400 = (1LL << CodeCompletionContext::CCC_TopLevel)
401 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
402 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
403 | (1LL << CodeCompletionContext::CCC_Statement)
404 | (1LL << CodeCompletionContext::CCC_Expression)
405 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
406 | (1LL << CodeCompletionContext::CCC_EnumTag)
407 | (1LL << CodeCompletionContext::CCC_UnionTag)
408 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
409 | (1LL << CodeCompletionContext::CCC_Type)
410 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
411 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
413 if (isa<NamespaceDecl>(R.Declaration) ||
414 isa<NamespaceAliasDecl>(R.Declaration))
415 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
417 if (unsigned RemainingContexts
418 = NNSContexts & ~CachedResult.ShowInContexts) {
419 // If there any contexts where this completion can be a
420 // nested-name-specifier but isn't already an option, create a
421 // nested-name-specifier completion.
422 R.StartsNestedNameSpecifier = true;
423 CachedResult.Completion = R.CreateCodeCompletionString(
424 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
425 IncludeBriefCommentsInCodeCompletion);
426 CachedResult.ShowInContexts = RemainingContexts;
427 CachedResult.Priority = CCP_NestedNameSpecifier;
428 CachedResult.TypeClass = STC_Void;
429 CachedResult.Type = 0;
430 CachedCompletionResults.push_back(CachedResult);
436 case Result::RK_Keyword:
437 case Result::RK_Pattern:
438 // Ignore keywords and patterns; we don't care, since they are so
439 // easily regenerated.
442 case Result::RK_Macro: {
443 CachedCodeCompletionResult CachedResult;
444 CachedResult.Completion = R.CreateCodeCompletionString(
445 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
446 IncludeBriefCommentsInCodeCompletion);
447 CachedResult.ShowInContexts
448 = (1LL << CodeCompletionContext::CCC_TopLevel)
449 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
450 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
451 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
452 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
453 | (1LL << CodeCompletionContext::CCC_Statement)
454 | (1LL << CodeCompletionContext::CCC_Expression)
455 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
456 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
457 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
458 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
459 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
461 CachedResult.Priority = R.Priority;
462 CachedResult.Kind = R.CursorKind;
463 CachedResult.Availability = R.Availability;
464 CachedResult.TypeClass = STC_Void;
465 CachedResult.Type = 0;
466 CachedCompletionResults.push_back(CachedResult);
472 // Save the current top-level hash value.
473 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
476 void ASTUnit::ClearCachedCompletionResults() {
477 CachedCompletionResults.clear();
478 CachedCompletionTypes.clear();
479 CachedCompletionAllocator = nullptr;
484 /// \brief Gathers information from ASTReader that will be used to initialize
486 class ASTInfoCollector : public ASTReaderListener {
489 LangOptions &LangOpt;
490 std::shared_ptr<TargetOptions> &TargetOpts;
491 IntrusiveRefCntPtr<TargetInfo> &Target;
494 bool InitializedLanguage;
496 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
497 std::shared_ptr<TargetOptions> &TargetOpts,
498 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
499 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
500 Target(Target), Counter(Counter), InitializedLanguage(false) {}
502 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
503 bool AllowCompatibleDifferences) override {
504 if (InitializedLanguage)
508 InitializedLanguage = true;
514 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
515 bool AllowCompatibleDifferences) override {
516 // If we've already initialized the target, don't do it again.
520 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
522 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
528 void ReadCounter(const serialization::ModuleFile &M,
529 unsigned Value) override {
535 if (!Target || !InitializedLanguage)
538 // Inform the target of the language options.
540 // FIXME: We shouldn't need to do this, the target should be immutable once
541 // created. This complexity should be lifted elsewhere.
542 Target->adjust(LangOpt);
544 // Initialize the preprocessor.
545 PP.Initialize(*Target);
547 // Initialize the ASTContext
548 Context.InitBuiltinTypes(*Target);
550 // We didn't have access to the comment options when the ASTContext was
551 // constructed, so register them now.
552 Context.getCommentCommandTraits().registerCommentOptions(
553 LangOpt.CommentOpts);
557 /// \brief Diagnostic consumer that saves each diagnostic it is given.
558 class StoredDiagnosticConsumer : public DiagnosticConsumer {
559 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
560 SourceManager *SourceMgr;
563 explicit StoredDiagnosticConsumer(
564 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
565 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
567 void BeginSourceFile(const LangOptions &LangOpts,
568 const Preprocessor *PP = nullptr) override {
570 SourceMgr = &PP->getSourceManager();
573 void HandleDiagnostic(DiagnosticsEngine::Level Level,
574 const Diagnostic &Info) override;
577 /// \brief RAII object that optionally captures diagnostics, if
578 /// there is no diagnostic client to capture them already.
579 class CaptureDroppedDiagnostics {
580 DiagnosticsEngine &Diags;
581 StoredDiagnosticConsumer Client;
582 DiagnosticConsumer *PreviousClient;
583 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
586 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
587 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
588 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
590 if (RequestCapture || Diags.getClient() == nullptr) {
591 OwningPreviousClient = Diags.takeClient();
592 PreviousClient = Diags.getClient();
593 Diags.setClient(&Client, false);
597 ~CaptureDroppedDiagnostics() {
598 if (Diags.getClient() == &Client)
599 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
603 } // anonymous namespace
605 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
606 const Diagnostic &Info) {
607 // Default implementation (Warnings/errors count).
608 DiagnosticConsumer::HandleDiagnostic(Level, Info);
610 // Only record the diagnostic if it's part of the source manager we know
611 // about. This effectively drops diagnostics from modules we're building.
612 // FIXME: In the long run, ee don't want to drop source managers from modules.
613 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
614 StoredDiags.emplace_back(Level, Info);
617 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
621 ASTMutationListener *ASTUnit::getASTMutationListener() {
623 return &WriterData->Writer;
627 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
629 return &WriterData->Writer;
633 std::unique_ptr<llvm::MemoryBuffer>
634 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
636 auto Buffer = FileMgr->getBufferForFile(Filename);
638 return std::move(*Buffer);
640 *ErrorStr = Buffer.getError().message();
644 /// \brief Configure the diagnostics object for use with ASTUnit.
645 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
646 ASTUnit &AST, bool CaptureDiagnostics) {
647 assert(Diags.get() && "no DiagnosticsEngine was provided");
648 if (CaptureDiagnostics)
649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
652 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
653 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
655 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
656 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
657 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
658 bool UserFilesAreVolatile) {
659 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
661 // Recover resources if we crash before exiting this method.
662 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
663 ASTUnitCleanup(AST.get());
664 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
665 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
666 DiagCleanup(Diags.get());
668 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
670 AST->OnlyLocalDecls = OnlyLocalDecls;
671 AST->CaptureDiagnostics = CaptureDiagnostics;
672 AST->Diagnostics = Diags;
673 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
674 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
675 AST->UserFilesAreVolatile = UserFilesAreVolatile;
676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
677 AST->getFileManager(),
678 UserFilesAreVolatile);
679 AST->PCMCache = new MemoryBufferCache;
680 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
681 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
682 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
683 AST->getSourceManager(),
684 AST->getDiagnostics(),
685 AST->ASTFileLangOpts,
686 /*Target=*/nullptr));
688 auto PPOpts = std::make_shared<PreprocessorOptions>();
690 for (const auto &RemappedFile : RemappedFiles)
691 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
693 // Gather Info for preprocessor construction later on.
695 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
698 AST->PP = std::make_shared<Preprocessor>(
699 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
700 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
701 /*IILookup=*/nullptr,
702 /*OwnsHeaderSearch=*/false);
703 Preprocessor &PP = *AST->PP;
705 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
706 PP.getIdentifierTable(), PP.getSelectorTable(),
707 PP.getBuiltinInfo());
708 ASTContext &Context = *AST->Ctx;
710 bool disableValid = false;
711 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
713 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
715 /*DisableValidation=*/disableValid,
716 AllowPCHWithCompilerErrors);
718 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
719 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
722 // Attach the AST reader to the AST context as an external AST
723 // source, so that declarations will be deserialized from the
724 // AST file as needed.
725 // We need the external source to be set up before we read the AST, because
726 // eagerly-deserialized declarations may use it.
727 Context.setExternalSource(AST->Reader);
729 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
730 SourceLocation(), ASTReader::ARR_None)) {
731 case ASTReader::Success:
734 case ASTReader::Failure:
735 case ASTReader::Missing:
736 case ASTReader::OutOfDate:
737 case ASTReader::VersionMismatch:
738 case ASTReader::ConfigurationMismatch:
739 case ASTReader::HadErrors:
740 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
744 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
746 PP.setCounterValue(Counter);
748 // Create an AST consumer, even though it isn't used.
749 AST->Consumer.reset(new ASTConsumer);
751 // Create a semantic analysis object and tell the AST reader about it.
752 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
753 AST->TheSema->Initialize();
754 AST->Reader->InitializeSema(*AST->TheSema);
756 // Tell the diagnostic client that we have started a source file.
757 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
764 /// \brief Preprocessor callback class that updates a hash value with the names
765 /// of all macros that have been defined by the translation unit.
766 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
770 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
772 void MacroDefined(const Token &MacroNameTok,
773 const MacroDirective *MD) override {
774 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
778 /// \brief Add the given declaration to the hash of all top-level entities.
779 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
783 DeclContext *DC = D->getDeclContext();
787 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
790 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
791 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
792 // For an unscoped enum include the enumerators in the hash since they
793 // enter the top-level namespace.
794 if (!EnumD->isScoped()) {
795 for (const auto *EI : EnumD->enumerators()) {
796 if (EI->getIdentifier())
797 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
802 if (ND->getIdentifier())
803 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
804 else if (DeclarationName Name = ND->getDeclName()) {
805 std::string NameStr = Name.getAsString();
806 Hash = llvm::HashString(NameStr, Hash);
811 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
812 if (Module *Mod = ImportD->getImportedModule()) {
813 std::string ModName = Mod->getFullModuleName();
814 Hash = llvm::HashString(ModName, Hash);
820 class TopLevelDeclTrackerConsumer : public ASTConsumer {
825 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
826 : Unit(_Unit), Hash(Hash) {
830 void handleTopLevelDecl(Decl *D) {
834 // FIXME: Currently ObjC method declarations are incorrectly being
835 // reported as top-level declarations, even though their DeclContext
836 // is the containing ObjC @interface/@implementation. This is a
837 // fundamental problem in the parser right now.
838 if (isa<ObjCMethodDecl>(D))
841 AddTopLevelDeclarationToHash(D, Hash);
842 Unit.addTopLevelDecl(D);
844 handleFileLevelDecl(D);
847 void handleFileLevelDecl(Decl *D) {
848 Unit.addFileLevelDecl(D);
849 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
850 for (auto *I : NSD->decls())
851 handleFileLevelDecl(I);
855 bool HandleTopLevelDecl(DeclGroupRef D) override {
856 for (Decl *TopLevelDecl : D)
857 handleTopLevelDecl(TopLevelDecl);
861 // We're not interested in "interesting" decls.
862 void HandleInterestingDecl(DeclGroupRef) override {}
864 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
865 for (Decl *TopLevelDecl : D)
866 handleTopLevelDecl(TopLevelDecl);
869 ASTMutationListener *GetASTMutationListener() override {
870 return Unit.getASTMutationListener();
873 ASTDeserializationListener *GetASTDeserializationListener() override {
874 return Unit.getDeserializationListener();
878 class TopLevelDeclTrackerAction : public ASTFrontendAction {
882 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
883 StringRef InFile) override {
884 CI.getPreprocessor().addPPCallbacks(
885 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
886 Unit.getCurrentTopLevelHashValue()));
887 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
888 Unit, Unit.getCurrentTopLevelHashValue());
892 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
894 bool hasCodeCompletionSupport() const override { return false; }
895 TranslationUnitKind getTranslationUnitKind() override {
896 return Unit.getTranslationUnitKind();
900 class PrecompilePreambleAction : public ASTFrontendAction {
902 bool HasEmittedPreamblePCH;
905 explicit PrecompilePreambleAction(ASTUnit &Unit)
906 : Unit(Unit), HasEmittedPreamblePCH(false) {}
908 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
909 StringRef InFile) override;
910 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
911 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
912 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
914 bool hasCodeCompletionSupport() const override { return false; }
915 bool hasASTFileSupport() const override { return false; }
916 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
919 class PrecompilePreambleConsumer : public PCHGenerator {
922 std::vector<Decl *> TopLevelDecls;
923 PrecompilePreambleAction *Action;
924 std::unique_ptr<raw_ostream> Out;
927 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
928 const Preprocessor &PP, StringRef isysroot,
929 std::unique_ptr<raw_ostream> Out)
930 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
931 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
932 /*AllowASTWithErrors=*/true),
933 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
934 Out(std::move(Out)) {
938 bool HandleTopLevelDecl(DeclGroupRef DG) override {
940 // FIXME: Currently ObjC method declarations are incorrectly being
941 // reported as top-level declarations, even though their DeclContext
942 // is the containing ObjC @interface/@implementation. This is a
943 // fundamental problem in the parser right now.
944 if (isa<ObjCMethodDecl>(D))
946 AddTopLevelDeclarationToHash(D, Hash);
947 TopLevelDecls.push_back(D);
952 void HandleTranslationUnit(ASTContext &Ctx) override {
953 PCHGenerator::HandleTranslationUnit(Ctx);
954 if (hasEmittedPCH()) {
955 // Write the generated bitstream to "Out".
957 // Make sure it hits disk now.
960 llvm::SmallVector<char, 0> Empty;
961 getPCH() = std::move(Empty);
963 // Translate the top-level declarations we captured during
964 // parsing into declaration IDs in the precompiled
965 // preamble. This will allow us to deserialize those top-level
966 // declarations when requested.
967 for (Decl *D : TopLevelDecls) {
968 // Invalid top-level decls may not have been serialized.
969 if (D->isInvalidDecl())
971 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
974 Action->setHasEmittedPreamblePCH();
979 } // anonymous namespace
981 std::unique_ptr<ASTConsumer>
982 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
985 std::string OutputFile;
986 std::unique_ptr<raw_ostream> OS =
987 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
992 if (!CI.getFrontendOpts().RelocatablePCH)
995 CI.getPreprocessor().addPPCallbacks(
996 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
997 Unit.getCurrentTopLevelHashValue()));
998 return llvm::make_unique<PrecompilePreambleConsumer>(
999 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
1002 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1003 return StoredDiag.getLocation().isValid();
1007 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1008 // Get rid of stored diagnostics except the ones from the driver which do not
1009 // have a source location.
1011 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1015 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1017 SourceManager &SM) {
1018 // The stored diagnostic has the old source manager in it; update
1019 // the locations to refer into the new source manager. Since we've
1020 // been careful to make sure that the source manager's state
1021 // before and after are identical, so that we can reuse the source
1023 for (StoredDiagnostic &SD : StoredDiagnostics) {
1024 if (SD.getLocation().isValid()) {
1025 FullSourceLoc Loc(SD.getLocation(), SM);
1026 SD.setLocation(Loc);
1031 /// Parse the source file into a translation unit using the given compiler
1032 /// invocation, replacing the current translation unit.
1034 /// \returns True if a failure occurred that causes the ASTUnit not to
1035 /// contain any translation-unit information, false otherwise.
1036 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1037 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1038 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1039 SavedMainFileBuffer.reset();
1044 // Create the compiler instance to use for building the AST.
1045 std::unique_ptr<CompilerInstance> Clang(
1046 new CompilerInstance(std::move(PCHContainerOps)));
1047 if (FileMgr && VFS) {
1048 assert(VFS == FileMgr->getVirtualFileSystem() &&
1049 "VFS passed to Parse and VFS in FileMgr are different");
1051 Clang->setVirtualFileSystem(VFS);
1054 // Recover resources if we crash before exiting this method.
1055 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1056 CICleanup(Clang.get());
1058 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1059 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1061 // Set up diagnostics, capturing any diagnostics that would
1062 // otherwise be dropped.
1063 Clang->setDiagnostics(&getDiagnostics());
1065 // Create the target instance.
1066 Clang->setTarget(TargetInfo::CreateTargetInfo(
1067 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1068 if (!Clang->hasTarget())
1071 // Inform the target of the language options.
1073 // FIXME: We shouldn't need to do this, the target should be immutable once
1074 // created. This complexity should be lifted elsewhere.
1075 Clang->getTarget().adjust(Clang->getLangOpts());
1077 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1078 "Invocation must have exactly one source file!");
1079 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1080 InputKind::Source &&
1081 "FIXME: AST inputs not yet supported here!");
1082 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1083 InputKind::LLVM_IR &&
1084 "IR inputs not support here!");
1086 // Configure the various subsystems.
1087 LangOpts = Clang->getInvocation().LangOpts;
1088 FileSystemOpts = Clang->getFileSystemOpts();
1090 Clang->createFileManager();
1091 FileMgr = &Clang->getFileManager();
1093 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1094 UserFilesAreVolatile);
1100 // Clear out old caches and data.
1101 TopLevelDecls.clear();
1102 clearFileLevelDecls();
1104 if (!OverrideMainBuffer) {
1105 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1106 TopLevelDeclsInPreamble.clear();
1109 // Create a file manager object to provide access to and cache the filesystem.
1110 Clang->setFileManager(&getFileManager());
1112 // Create the source manager.
1113 Clang->setSourceManager(&getSourceManager());
1115 // If the main file has been overridden due to the use of a preamble,
1116 // make that override happen and introduce the preamble.
1117 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1118 if (OverrideMainBuffer) {
1119 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1120 OverrideMainBuffer.get());
1121 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1122 PreprocessorOpts.PrecompiledPreambleBytes.second
1123 = PreambleEndsAtStartOfLine;
1124 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1125 PreprocessorOpts.DisablePCHValidation = true;
1127 // The stored diagnostic has the old source manager in it; update
1128 // the locations to refer into the new source manager. Since we've
1129 // been careful to make sure that the source manager's state
1130 // before and after are identical, so that we can reuse the source
1132 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1134 // Keep track of the override buffer;
1135 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1138 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1139 new TopLevelDeclTrackerAction(*this));
1141 // Recover resources if we crash before exiting this method.
1142 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1143 ActCleanup(Act.get());
1145 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1148 if (SavedMainFileBuffer)
1149 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1150 PreambleDiagnostics, StoredDiagnostics);
1152 if (!Act->Execute())
1155 transferASTDataFromCompilerInstance(*Clang);
1157 Act->EndSourceFile();
1159 FailedParseDiagnostics.clear();
1164 // Remove the overridden buffer we used for the preamble.
1165 SavedMainFileBuffer = nullptr;
1167 // Keep the ownership of the data in the ASTUnit because the client may
1168 // want to see the diagnostics.
1169 transferASTDataFromCompilerInstance(*Clang);
1170 FailedParseDiagnostics.swap(StoredDiagnostics);
1171 StoredDiagnostics.clear();
1172 NumStoredDiagnosticsFromDriver = 0;
1176 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1177 static std::string GetPreamblePCHPath() {
1178 // FIXME: This is a hack so that we can override the preamble file during
1179 // crash-recovery testing, which is the only case where the preamble files
1180 // are not necessarily cleaned up.
1181 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1185 SmallString<128> Path;
1186 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1191 /// \brief Compute the preamble for the main file, providing the source buffer
1192 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1193 /// that describes the preamble.
1194 ASTUnit::ComputedPreamble
1195 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines,
1196 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1197 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1198 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1200 // Try to determine if the main file has been remapped, either from the
1201 // command line (to another file) or directly through the compiler invocation
1202 // (to a memory buffer).
1203 llvm::MemoryBuffer *Buffer = nullptr;
1204 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1205 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1206 auto MainFileStatus = VFS->status(MainFilePath);
1207 if (MainFileStatus) {
1208 llvm::sys::fs::UniqueID MainFileID = MainFileStatus->getUniqueID();
1210 // Check whether there is a file-file remapping of the main file
1211 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1212 std::string MPath(RF.first);
1213 auto MPathStatus = VFS->status(MPath);
1215 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
1216 if (MainFileID == MID) {
1217 // We found a remapping. Try to load the resulting, remapped source.
1218 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
1220 return ComputedPreamble(nullptr, nullptr, 0, true);
1225 // Check whether there is a file-buffer remapping. It supercedes the
1226 // file-file remapping.
1227 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1228 std::string MPath(RB.first);
1229 auto MPathStatus = VFS->status(MPath);
1231 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
1232 if (MainFileID == MID) {
1233 // We found a remapping.
1234 BufferOwner.reset();
1235 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1241 // If the main source file was not remapped, load it now.
1242 if (!Buffer && !BufferOwner) {
1243 BufferOwner = valueOrNull(VFS->getBufferForFile(FrontendOpts.Inputs[0].getFile()));
1245 return ComputedPreamble(nullptr, nullptr, 0, true);
1249 Buffer = BufferOwner.get();
1250 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1251 *Invocation.getLangOpts(), MaxLines);
1252 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1256 ASTUnit::PreambleFileHash
1257 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1258 PreambleFileHash Result;
1260 Result.ModTime = ModTime;
1265 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1266 const llvm::MemoryBuffer *Buffer) {
1267 PreambleFileHash Result;
1268 Result.Size = Buffer->getBufferSize();
1272 MD5Ctx.update(Buffer->getBuffer().data());
1273 MD5Ctx.final(Result.MD5);
1279 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1280 const ASTUnit::PreambleFileHash &RHS) {
1281 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1284 } // namespace clang
1286 static std::pair<unsigned, unsigned>
1287 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1288 const LangOptions &LangOpts) {
1289 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1290 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1291 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1292 return std::make_pair(Offset, EndOffset);
1295 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1296 const LangOptions &LangOpts,
1297 const FixItHint &InFix) {
1298 ASTUnit::StandaloneFixIt OutFix;
1299 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1300 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1302 OutFix.CodeToInsert = InFix.CodeToInsert;
1303 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1307 static ASTUnit::StandaloneDiagnostic
1308 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1309 const StoredDiagnostic &InDiag) {
1310 ASTUnit::StandaloneDiagnostic OutDiag;
1311 OutDiag.ID = InDiag.getID();
1312 OutDiag.Level = InDiag.getLevel();
1313 OutDiag.Message = InDiag.getMessage();
1314 OutDiag.LocOffset = 0;
1315 if (InDiag.getLocation().isInvalid())
1317 const SourceManager &SM = InDiag.getLocation().getManager();
1318 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1319 OutDiag.Filename = SM.getFilename(FileLoc);
1320 if (OutDiag.Filename.empty())
1322 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1323 for (const CharSourceRange &Range : InDiag.getRanges())
1324 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1325 for (const FixItHint &FixIt : InDiag.getFixIts())
1326 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1331 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1332 /// the source file.
1334 /// This routine will compute the preamble of the main source file. If a
1335 /// non-trivial preamble is found, it will precompile that preamble into a
1336 /// precompiled header so that the precompiled preamble can be used to reduce
1337 /// reparsing time. If a precompiled preamble has already been constructed,
1338 /// this routine will determine if it is still valid and, if so, avoid
1339 /// rebuilding the precompiled preamble.
1341 /// \param AllowRebuild When true (the default), this routine is
1342 /// allowed to rebuild the precompiled preamble if it is found to be
1345 /// \param MaxLines When non-zero, the maximum number of lines that
1346 /// can occur within the preamble.
1348 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1349 /// buffer that should be used in place of the main file when doing so.
1350 /// Otherwise, returns a NULL pointer.
1351 std::unique_ptr<llvm::MemoryBuffer>
1352 ASTUnit::getMainBufferWithPrecompiledPreamble(
1353 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1354 const CompilerInvocation &PreambleInvocationIn,
1355 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
1356 unsigned MaxLines) {
1357 assert(VFS && "VFS is null");
1359 auto PreambleInvocation =
1360 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1361 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1362 PreprocessorOptions &PreprocessorOpts
1363 = PreambleInvocation->getPreprocessorOpts();
1365 ComputedPreamble NewPreamble =
1366 ComputePreamble(*PreambleInvocation, MaxLines, VFS);
1368 if (!NewPreamble.Size) {
1369 // We couldn't find a preamble in the main source. Clear out the current
1370 // preamble, if we have one. It's obviously no good any more.
1372 erasePreambleFile(this);
1374 // The next time we actually see a preamble, precompile it.
1375 PreambleRebuildCounter = 1;
1379 if (!Preamble.empty()) {
1380 // We've previously computed a preamble. Check whether we have the same
1381 // preamble now that we did before, and that there's enough space in
1382 // the main-file buffer within the precompiled preamble to fit the
1384 if (Preamble.size() == NewPreamble.Size &&
1385 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1386 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1387 NewPreamble.Size) == 0) {
1388 // The preamble has not changed. We may be able to re-use the precompiled
1391 // Check that none of the files used by the preamble have changed.
1392 bool AnyFileChanged = false;
1394 // First, make a record of those files that have been overridden via
1395 // remapping or unsaved_files.
1396 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1397 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1402 if (!moveOnNoError(VFS->status(R.second), Status)) {
1403 // If we can't stat the file we're remapping to, assume that something
1404 // horrible happened.
1405 AnyFileChanged = true;
1409 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1411 llvm::sys::toTimeT(Status.getLastModificationTime()));
1414 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1419 if (!moveOnNoError(VFS->status(RB.first), Status)) {
1420 AnyFileChanged = true;
1424 OverriddenFiles[Status.getUniqueID()] =
1425 PreambleFileHash::createForMemoryBuffer(RB.second);
1428 // Check whether anything has changed.
1429 for (llvm::StringMap<PreambleFileHash>::iterator
1430 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1431 !AnyFileChanged && F != FEnd;
1434 if (!moveOnNoError(VFS->status(F->first()), Status)) {
1435 // If we can't stat the file, assume that something horrible happened.
1436 AnyFileChanged = true;
1440 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1441 = OverriddenFiles.find(Status.getUniqueID());
1442 if (Overridden != OverriddenFiles.end()) {
1443 // This file was remapped; check whether the newly-mapped file
1444 // matches up with the previous mapping.
1445 if (Overridden->second != F->second)
1446 AnyFileChanged = true;
1450 // The file was not remapped; check whether it has changed on disk.
1451 if (Status.getSize() != uint64_t(F->second.Size) ||
1452 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1454 AnyFileChanged = true;
1457 if (!AnyFileChanged) {
1458 // Okay! We can re-use the precompiled preamble.
1460 // Set the state of the diagnostic object to mimic its state
1461 // after parsing the preamble.
1462 getDiagnostics().Reset();
1463 ProcessWarningOptions(getDiagnostics(),
1464 PreambleInvocation->getDiagnosticOpts());
1465 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1467 return llvm::MemoryBuffer::getMemBufferCopy(
1468 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1472 // If we aren't allowed to rebuild the precompiled preamble, just
1477 // We can't reuse the previously-computed preamble. Build a new one.
1479 PreambleDiagnostics.clear();
1480 erasePreambleFile(this);
1481 PreambleRebuildCounter = 1;
1482 } else if (!AllowRebuild) {
1483 // We aren't allowed to rebuild the precompiled preamble; just
1488 // If the preamble rebuild counter > 1, it's because we previously
1489 // failed to build a preamble and we're not yet ready to try
1490 // again. Decrement the counter and return a failure.
1491 if (PreambleRebuildCounter > 1) {
1492 --PreambleRebuildCounter;
1496 // Create a temporary file for the precompiled preamble. In rare
1497 // circumstances, this can fail.
1498 std::string PreamblePCHPath = GetPreamblePCHPath();
1499 if (PreamblePCHPath.empty()) {
1500 // Try again next time.
1501 PreambleRebuildCounter = 1;
1505 // We did not previously compute a preamble, or it can't be reused anyway.
1506 SimpleTimer PreambleTimer(WantTiming);
1507 PreambleTimer.setOutput("Precompiling preamble");
1509 // Save the preamble text for later; we'll need to compare against it for
1510 // subsequent reparses.
1511 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1512 Preamble.assign(FileMgr->getFile(MainFilename),
1513 NewPreamble.Buffer->getBufferStart(),
1514 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1515 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1517 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1518 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1520 // Remap the main source file to the preamble buffer.
1521 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1522 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1524 // Tell the compiler invocation to generate a temporary precompiled header.
1525 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1526 // FIXME: Generate the precompiled header into memory?
1527 FrontendOpts.OutputFile = PreamblePCHPath;
1528 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1529 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1531 // Create the compiler instance to use for building the precompiled preamble.
1532 std::unique_ptr<CompilerInstance> Clang(
1533 new CompilerInstance(std::move(PCHContainerOps)));
1535 // Recover resources if we crash before exiting this method.
1536 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1537 CICleanup(Clang.get());
1539 Clang->setInvocation(std::move(PreambleInvocation));
1540 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1542 // Set up diagnostics, capturing all of the diagnostics produced.
1543 Clang->setDiagnostics(&getDiagnostics());
1545 // Create the target instance.
1546 Clang->setTarget(TargetInfo::CreateTargetInfo(
1547 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1548 if (!Clang->hasTarget()) {
1549 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1551 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1552 PreprocessorOpts.RemappedFileBuffers.pop_back();
1556 // Inform the target of the language options.
1558 // FIXME: We shouldn't need to do this, the target should be immutable once
1559 // created. This complexity should be lifted elsewhere.
1560 Clang->getTarget().adjust(Clang->getLangOpts());
1562 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1563 "Invocation must have exactly one source file!");
1564 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1565 InputKind::Source &&
1566 "FIXME: AST inputs not yet supported here!");
1567 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1568 InputKind::LLVM_IR &&
1569 "IR inputs not support here!");
1571 // Clear out old caches and data.
1572 getDiagnostics().Reset();
1573 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1574 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1575 TopLevelDecls.clear();
1576 TopLevelDeclsInPreamble.clear();
1577 PreambleDiagnostics.clear();
1579 VFS = createVFSFromCompilerInvocation(Clang->getInvocation(),
1580 getDiagnostics(), VFS);
1584 // Create a file manager object to provide access to and cache the filesystem.
1585 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1587 // Create the source manager.
1588 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1589 Clang->getFileManager()));
1591 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1592 Clang->addDependencyCollector(PreambleDepCollector);
1594 std::unique_ptr<PrecompilePreambleAction> Act;
1595 Act.reset(new PrecompilePreambleAction(*this));
1596 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1597 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1599 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1600 PreprocessorOpts.RemappedFileBuffers.pop_back();
1606 // Transfer any diagnostics generated when parsing the preamble into the set
1607 // of preamble diagnostics.
1608 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1609 E = stored_diag_end();
1611 PreambleDiagnostics.push_back(
1612 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1614 Act->EndSourceFile();
1616 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1618 if (!Act->hasEmittedPreamblePCH()) {
1619 // The preamble PCH failed (e.g. there was a module loading fatal error),
1620 // so no precompiled header was generated. Forget that we even tried.
1621 // FIXME: Should we leave a note for ourselves to try again?
1622 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1624 TopLevelDeclsInPreamble.clear();
1625 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1626 PreprocessorOpts.RemappedFileBuffers.pop_back();
1630 // Keep track of the preamble we precompiled.
1631 setPreambleFile(this, FrontendOpts.OutputFile);
1632 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1634 // Keep track of all of the files that the source manager knows about,
1635 // so we can verify whether they have changed or not.
1636 FilesInPreamble.clear();
1637 SourceManager &SourceMgr = Clang->getSourceManager();
1638 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1639 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1640 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1642 if (time_t ModTime = File->getModificationTime()) {
1643 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1644 File->getSize(), ModTime);
1646 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1647 FilesInPreamble[File->getName()] =
1648 PreambleFileHash::createForMemoryBuffer(Buffer);
1652 PreambleRebuildCounter = 1;
1653 PreprocessorOpts.RemappedFileBuffers.pop_back();
1655 // If the hash of top-level entities differs from the hash of the top-level
1656 // entities the last time we rebuilt the preamble, clear out the completion
1658 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1659 CompletionCacheTopLevelHashValue = 0;
1660 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1663 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1667 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1668 std::vector<Decl *> Resolved;
1669 Resolved.reserve(TopLevelDeclsInPreamble.size());
1670 ExternalASTSource &Source = *getASTContext().getExternalSource();
1671 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1672 // Resolve the declaration ID to an actual declaration, possibly
1673 // deserializing the declaration in the process.
1674 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1675 Resolved.push_back(D);
1677 TopLevelDeclsInPreamble.clear();
1678 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1681 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1682 // Steal the created target, context, and preprocessor if they have been
1684 assert(CI.hasInvocation() && "missing invocation");
1685 LangOpts = CI.getInvocation().LangOpts;
1686 TheSema = CI.takeSema();
1687 Consumer = CI.takeASTConsumer();
1688 if (CI.hasASTContext())
1689 Ctx = &CI.getASTContext();
1690 if (CI.hasPreprocessor())
1691 PP = CI.getPreprocessorPtr();
1692 CI.setSourceManager(nullptr);
1693 CI.setFileManager(nullptr);
1695 Target = &CI.getTarget();
1696 Reader = CI.getModuleManager();
1697 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1700 StringRef ASTUnit::getMainFileName() const {
1701 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1702 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1704 return Input.getFile();
1706 return Input.getBuffer()->getBufferIdentifier();
1710 if (const FileEntry *
1711 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1712 return FE->getName();
1718 StringRef ASTUnit::getASTFileName() const {
1719 if (!isMainFileAST())
1722 serialization::ModuleFile &
1723 Mod = Reader->getModuleManager().getPrimaryModule();
1724 return Mod.FileName;
1727 std::unique_ptr<ASTUnit>
1728 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1729 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1730 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1731 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1732 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1733 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1734 createVFSFromCompilerInvocation(*CI, *Diags);
1737 AST->Diagnostics = Diags;
1738 AST->FileSystemOpts = CI->getFileSystemOpts();
1739 AST->Invocation = std::move(CI);
1740 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1741 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1742 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1743 UserFilesAreVolatile);
1744 AST->PCMCache = new MemoryBufferCache;
1749 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1750 std::shared_ptr<CompilerInvocation> CI,
1751 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1752 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1753 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1754 bool OnlyLocalDecls, bool CaptureDiagnostics,
1755 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1756 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1757 std::unique_ptr<ASTUnit> *ErrAST) {
1758 assert(CI && "A CompilerInvocation is required");
1760 std::unique_ptr<ASTUnit> OwnAST;
1761 ASTUnit *AST = Unit;
1763 // Create the AST unit.
1764 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1770 if (!ResourceFilesPath.empty()) {
1771 // Override the resources path.
1772 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1774 AST->OnlyLocalDecls = OnlyLocalDecls;
1775 AST->CaptureDiagnostics = CaptureDiagnostics;
1776 if (PrecompilePreambleAfterNParses > 0)
1777 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1778 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1779 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1780 AST->IncludeBriefCommentsInCodeCompletion
1781 = IncludeBriefCommentsInCodeCompletion;
1783 // Recover resources if we crash before exiting this method.
1784 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1785 ASTUnitCleanup(OwnAST.get());
1786 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1787 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1788 DiagCleanup(Diags.get());
1790 // We'll manage file buffers ourselves.
1791 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1792 CI->getFrontendOpts().DisableFree = false;
1793 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1795 // Create the compiler instance to use for building the AST.
1796 std::unique_ptr<CompilerInstance> Clang(
1797 new CompilerInstance(std::move(PCHContainerOps)));
1799 // Recover resources if we crash before exiting this method.
1800 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1801 CICleanup(Clang.get());
1803 Clang->setInvocation(std::move(CI));
1804 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1806 // Set up diagnostics, capturing any diagnostics that would
1807 // otherwise be dropped.
1808 Clang->setDiagnostics(&AST->getDiagnostics());
1810 // Create the target instance.
1811 Clang->setTarget(TargetInfo::CreateTargetInfo(
1812 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1813 if (!Clang->hasTarget())
1816 // Inform the target of the language options.
1818 // FIXME: We shouldn't need to do this, the target should be immutable once
1819 // created. This complexity should be lifted elsewhere.
1820 Clang->getTarget().adjust(Clang->getLangOpts());
1822 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1823 "Invocation must have exactly one source file!");
1824 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1825 InputKind::Source &&
1826 "FIXME: AST inputs not yet supported here!");
1827 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1828 InputKind::LLVM_IR &&
1829 "IR inputs not support here!");
1831 // Configure the various subsystems.
1832 AST->TheSema.reset();
1835 AST->Reader = nullptr;
1837 // Create a file manager object to provide access to and cache the filesystem.
1838 Clang->setFileManager(&AST->getFileManager());
1840 // Create the source manager.
1841 Clang->setSourceManager(&AST->getSourceManager());
1843 FrontendAction *Act = Action;
1845 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1847 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1848 Act = TrackerAct.get();
1851 // Recover resources if we crash before exiting this method.
1852 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1853 ActCleanup(TrackerAct.get());
1855 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1856 AST->transferASTDataFromCompilerInstance(*Clang);
1857 if (OwnAST && ErrAST)
1858 ErrAST->swap(OwnAST);
1863 if (Persistent && !TrackerAct) {
1864 Clang->getPreprocessor().addPPCallbacks(
1865 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1866 AST->getCurrentTopLevelHashValue()));
1867 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1868 if (Clang->hasASTConsumer())
1869 Consumers.push_back(Clang->takeASTConsumer());
1870 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1871 *AST, AST->getCurrentTopLevelHashValue()));
1872 Clang->setASTConsumer(
1873 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1875 if (!Act->Execute()) {
1876 AST->transferASTDataFromCompilerInstance(*Clang);
1877 if (OwnAST && ErrAST)
1878 ErrAST->swap(OwnAST);
1883 // Steal the created target, context, and preprocessor.
1884 AST->transferASTDataFromCompilerInstance(*Clang);
1886 Act->EndSourceFile();
1889 return OwnAST.release();
1894 bool ASTUnit::LoadFromCompilerInvocation(
1895 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1896 unsigned PrecompilePreambleAfterNParses,
1897 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1901 assert(VFS && "VFS is null");
1903 // We'll manage file buffers ourselves.
1904 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1905 Invocation->getFrontendOpts().DisableFree = false;
1906 getDiagnostics().Reset();
1907 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1909 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1910 if (PrecompilePreambleAfterNParses > 0) {
1911 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1912 OverrideMainBuffer =
1913 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1914 getDiagnostics().Reset();
1915 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1918 SimpleTimer ParsingTimer(WantTiming);
1919 ParsingTimer.setOutput("Parsing " + getMainFileName());
1921 // Recover resources if we crash before exiting this method.
1922 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1923 MemBufferCleanup(OverrideMainBuffer.get());
1925 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1928 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1929 std::shared_ptr<CompilerInvocation> CI,
1930 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1931 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1932 bool OnlyLocalDecls, bool CaptureDiagnostics,
1933 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1934 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1935 bool UserFilesAreVolatile) {
1936 // Create the AST unit.
1937 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1938 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1939 AST->Diagnostics = Diags;
1940 AST->OnlyLocalDecls = OnlyLocalDecls;
1941 AST->CaptureDiagnostics = CaptureDiagnostics;
1942 AST->TUKind = TUKind;
1943 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1944 AST->IncludeBriefCommentsInCodeCompletion
1945 = IncludeBriefCommentsInCodeCompletion;
1946 AST->Invocation = std::move(CI);
1947 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1948 AST->FileMgr = FileMgr;
1949 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1951 // Recover resources if we crash before exiting this method.
1952 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1953 ASTUnitCleanup(AST.get());
1954 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1955 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1956 DiagCleanup(Diags.get());
1958 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1959 PrecompilePreambleAfterNParses,
1960 AST->FileMgr->getVirtualFileSystem()))
1965 ASTUnit *ASTUnit::LoadFromCommandLine(
1966 const char **ArgBegin, const char **ArgEnd,
1967 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1968 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1969 bool OnlyLocalDecls, bool CaptureDiagnostics,
1970 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1971 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1972 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1973 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1974 bool UserFilesAreVolatile, bool ForSerialization,
1975 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1976 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1977 assert(Diags.get() && "no DiagnosticsEngine was provided");
1979 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1981 std::shared_ptr<CompilerInvocation> CI;
1985 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1988 CI = clang::createInvocationFromCommandLine(
1989 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1994 // Override any files that need remapping
1995 for (const auto &RemappedFile : RemappedFiles) {
1996 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1997 RemappedFile.second);
1999 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2000 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2001 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
2003 // Override the resources path.
2004 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
2006 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2009 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
2011 // Create the AST unit.
2012 std::unique_ptr<ASTUnit> AST;
2013 AST.reset(new ASTUnit(false));
2014 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
2015 AST->Diagnostics = Diags;
2016 AST->FileSystemOpts = CI->getFileSystemOpts();
2018 VFS = vfs::getRealFileSystem();
2019 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
2022 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
2023 AST->PCMCache = new MemoryBufferCache;
2024 AST->OnlyLocalDecls = OnlyLocalDecls;
2025 AST->CaptureDiagnostics = CaptureDiagnostics;
2026 AST->TUKind = TUKind;
2027 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2028 AST->IncludeBriefCommentsInCodeCompletion
2029 = IncludeBriefCommentsInCodeCompletion;
2030 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2031 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2032 AST->StoredDiagnostics.swap(StoredDiagnostics);
2033 AST->Invocation = CI;
2034 if (ForSerialization)
2035 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2036 // Zero out now to ease cleanup during crash recovery.
2040 // Recover resources if we crash before exiting this method.
2041 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2042 ASTUnitCleanup(AST.get());
2044 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2045 PrecompilePreambleAfterNParses,
2047 // Some error occurred, if caller wants to examine diagnostics, pass it the
2050 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2056 return AST.release();
2059 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2060 ArrayRef<RemappedFile> RemappedFiles,
2061 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
2066 assert(FileMgr && "FileMgr is null on Reparse call");
2067 VFS = FileMgr->getVirtualFileSystem();
2070 clearFileLevelDecls();
2072 SimpleTimer ParsingTimer(WantTiming);
2073 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2076 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2077 for (const auto &RB : PPOpts.RemappedFileBuffers)
2080 Invocation->getPreprocessorOpts().clearRemappedFiles();
2081 for (const auto &RemappedFile : RemappedFiles) {
2082 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2083 RemappedFile.second);
2086 // If we have a preamble file lying around, or if we might try to
2087 // build a precompiled preamble, do so now.
2088 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2089 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2090 OverrideMainBuffer =
2091 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
2094 // Clear out the diagnostics state.
2096 getDiagnostics().Reset();
2097 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2098 if (OverrideMainBuffer)
2099 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2101 // Parse the sources
2103 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
2105 // If we're caching global code-completion results, and the top-level
2106 // declarations have changed, clear out the code-completion cache.
2107 if (!Result && ShouldCacheCodeCompletionResults &&
2108 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2109 CacheCodeCompletionResults();
2111 // We now need to clear out the completion info related to this translation
2112 // unit; it'll be recreated if necessary.
2118 //----------------------------------------------------------------------------//
2120 //----------------------------------------------------------------------------//
2123 /// \brief Code completion consumer that combines the cached code-completion
2124 /// results from an ASTUnit with the code-completion results provided to it,
2125 /// then passes the result on to
2126 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2127 uint64_t NormalContexts;
2129 CodeCompleteConsumer &Next;
2132 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2133 const CodeCompleteOptions &CodeCompleteOpts)
2134 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2135 AST(AST), Next(Next)
2137 // Compute the set of contexts in which we will look when we don't have
2138 // any information about the specific context.
2140 = (1LL << CodeCompletionContext::CCC_TopLevel)
2141 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2142 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2143 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2144 | (1LL << CodeCompletionContext::CCC_Statement)
2145 | (1LL << CodeCompletionContext::CCC_Expression)
2146 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2147 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2148 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2149 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2150 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2151 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2152 | (1LL << CodeCompletionContext::CCC_Recovery);
2154 if (AST.getASTContext().getLangOpts().CPlusPlus)
2155 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2156 | (1LL << CodeCompletionContext::CCC_UnionTag)
2157 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2160 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2161 CodeCompletionResult *Results,
2162 unsigned NumResults) override;
2164 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2165 OverloadCandidate *Candidates,
2166 unsigned NumCandidates) override {
2167 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2170 CodeCompletionAllocator &getAllocator() override {
2171 return Next.getAllocator();
2174 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2175 return Next.getCodeCompletionTUInfo();
2178 } // anonymous namespace
2180 /// \brief Helper function that computes which global names are hidden by the
2181 /// local code-completion results.
2182 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2183 CodeCompletionResult *Results,
2184 unsigned NumResults,
2186 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2187 bool OnlyTagNames = false;
2188 switch (Context.getKind()) {
2189 case CodeCompletionContext::CCC_Recovery:
2190 case CodeCompletionContext::CCC_TopLevel:
2191 case CodeCompletionContext::CCC_ObjCInterface:
2192 case CodeCompletionContext::CCC_ObjCImplementation:
2193 case CodeCompletionContext::CCC_ObjCIvarList:
2194 case CodeCompletionContext::CCC_ClassStructUnion:
2195 case CodeCompletionContext::CCC_Statement:
2196 case CodeCompletionContext::CCC_Expression:
2197 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2198 case CodeCompletionContext::CCC_DotMemberAccess:
2199 case CodeCompletionContext::CCC_ArrowMemberAccess:
2200 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2201 case CodeCompletionContext::CCC_Namespace:
2202 case CodeCompletionContext::CCC_Type:
2203 case CodeCompletionContext::CCC_Name:
2204 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2205 case CodeCompletionContext::CCC_ParenthesizedExpression:
2206 case CodeCompletionContext::CCC_ObjCInterfaceName:
2209 case CodeCompletionContext::CCC_EnumTag:
2210 case CodeCompletionContext::CCC_UnionTag:
2211 case CodeCompletionContext::CCC_ClassOrStructTag:
2212 OnlyTagNames = true;
2215 case CodeCompletionContext::CCC_ObjCProtocolName:
2216 case CodeCompletionContext::CCC_MacroName:
2217 case CodeCompletionContext::CCC_MacroNameUse:
2218 case CodeCompletionContext::CCC_PreprocessorExpression:
2219 case CodeCompletionContext::CCC_PreprocessorDirective:
2220 case CodeCompletionContext::CCC_NaturalLanguage:
2221 case CodeCompletionContext::CCC_SelectorName:
2222 case CodeCompletionContext::CCC_TypeQualifiers:
2223 case CodeCompletionContext::CCC_Other:
2224 case CodeCompletionContext::CCC_OtherWithMacros:
2225 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2226 case CodeCompletionContext::CCC_ObjCClassMessage:
2227 case CodeCompletionContext::CCC_ObjCCategoryName:
2228 // We're looking for nothing, or we're looking for names that cannot
2233 typedef CodeCompletionResult Result;
2234 for (unsigned I = 0; I != NumResults; ++I) {
2235 if (Results[I].Kind != Result::RK_Declaration)
2239 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2241 bool Hiding = false;
2243 Hiding = (IDNS & Decl::IDNS_Tag);
2245 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2246 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2247 Decl::IDNS_NonMemberOperator);
2248 if (Ctx.getLangOpts().CPlusPlus)
2249 HiddenIDNS |= Decl::IDNS_Tag;
2250 Hiding = (IDNS & HiddenIDNS);
2256 DeclarationName Name = Results[I].Declaration->getDeclName();
2257 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2258 HiddenNames.insert(Identifier->getName());
2260 HiddenNames.insert(Name.getAsString());
2264 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2265 CodeCompletionContext Context,
2266 CodeCompletionResult *Results,
2267 unsigned NumResults) {
2268 // Merge the results we were given with the results we cached.
2269 bool AddedResult = false;
2270 uint64_t InContexts =
2271 Context.getKind() == CodeCompletionContext::CCC_Recovery
2272 ? NormalContexts : (1LL << Context.getKind());
2273 // Contains the set of names that are hidden by "local" completion results.
2274 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2275 typedef CodeCompletionResult Result;
2276 SmallVector<Result, 8> AllResults;
2277 for (ASTUnit::cached_completion_iterator
2278 C = AST.cached_completion_begin(),
2279 CEnd = AST.cached_completion_end();
2281 // If the context we are in matches any of the contexts we are
2282 // interested in, we'll add this result.
2283 if ((C->ShowInContexts & InContexts) == 0)
2286 // If we haven't added any results previously, do so now.
2288 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2290 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2294 // Determine whether this global completion result is hidden by a local
2295 // completion result. If so, skip it.
2296 if (C->Kind != CXCursor_MacroDefinition &&
2297 HiddenNames.count(C->Completion->getTypedText()))
2300 // Adjust priority based on similar type classes.
2301 unsigned Priority = C->Priority;
2302 CodeCompletionString *Completion = C->Completion;
2303 if (!Context.getPreferredType().isNull()) {
2304 if (C->Kind == CXCursor_MacroDefinition) {
2305 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2307 Context.getPreferredType()->isAnyPointerType());
2308 } else if (C->Type) {
2309 CanQualType Expected
2310 = S.Context.getCanonicalType(
2311 Context.getPreferredType().getUnqualifiedType());
2312 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2313 if (ExpectedSTC == C->TypeClass) {
2314 // We know this type is similar; check for an exact match.
2315 llvm::StringMap<unsigned> &CachedCompletionTypes
2316 = AST.getCachedCompletionTypes();
2317 llvm::StringMap<unsigned>::iterator Pos
2318 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2319 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2320 Priority /= CCF_ExactTypeMatch;
2322 Priority /= CCF_SimilarTypeMatch;
2327 // Adjust the completion string, if required.
2328 if (C->Kind == CXCursor_MacroDefinition &&
2329 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2330 // Create a new code-completion string that just contains the
2331 // macro name, without its arguments.
2332 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2333 CCP_CodePattern, C->Availability);
2334 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2335 Priority = CCP_CodePattern;
2336 Completion = Builder.TakeString();
2339 AllResults.push_back(Result(Completion, Priority, C->Kind,
2343 // If we did not add any cached completion results, just forward the
2344 // results we were given to the next consumer.
2346 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2350 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2354 void ASTUnit::CodeComplete(
2355 StringRef File, unsigned Line, unsigned Column,
2356 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2357 bool IncludeCodePatterns, bool IncludeBriefComments,
2358 CodeCompleteConsumer &Consumer,
2359 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2360 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2361 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2362 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2366 SimpleTimer CompletionTimer(WantTiming);
2367 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2368 Twine(Line) + ":" + Twine(Column));
2370 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2372 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2373 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2374 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2376 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2377 CachedCompletionResults.empty();
2378 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2379 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2380 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2382 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2384 FrontendOpts.CodeCompletionAt.FileName = File;
2385 FrontendOpts.CodeCompletionAt.Line = Line;
2386 FrontendOpts.CodeCompletionAt.Column = Column;
2388 // Set the language options appropriately.
2389 LangOpts = *CCInvocation->getLangOpts();
2391 // Spell-checking and warnings are wasteful during code-completion.
2392 LangOpts.SpellChecking = false;
2393 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2395 std::unique_ptr<CompilerInstance> Clang(
2396 new CompilerInstance(PCHContainerOps));
2398 // Recover resources if we crash before exiting this method.
2399 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2400 CICleanup(Clang.get());
2402 auto &Inv = *CCInvocation;
2403 Clang->setInvocation(std::move(CCInvocation));
2404 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2406 // Set up diagnostics, capturing any diagnostics produced.
2407 Clang->setDiagnostics(&Diag);
2408 CaptureDroppedDiagnostics Capture(true,
2409 Clang->getDiagnostics(),
2411 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2413 // Create the target instance.
2414 Clang->setTarget(TargetInfo::CreateTargetInfo(
2415 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2416 if (!Clang->hasTarget()) {
2417 Clang->setInvocation(nullptr);
2421 // Inform the target of the language options.
2423 // FIXME: We shouldn't need to do this, the target should be immutable once
2424 // created. This complexity should be lifted elsewhere.
2425 Clang->getTarget().adjust(Clang->getLangOpts());
2427 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2428 "Invocation must have exactly one source file!");
2429 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2430 InputKind::Source &&
2431 "FIXME: AST inputs not yet supported here!");
2432 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2433 InputKind::LLVM_IR &&
2434 "IR inputs not support here!");
2436 // Use the source and file managers that we were given.
2437 Clang->setFileManager(&FileMgr);
2438 Clang->setSourceManager(&SourceMgr);
2441 PreprocessorOpts.clearRemappedFiles();
2442 PreprocessorOpts.RetainRemappedFileBuffers = true;
2443 for (const auto &RemappedFile : RemappedFiles) {
2444 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2445 OwnedBuffers.push_back(RemappedFile.second);
2448 // Use the code completion consumer we were given, but adding any cached
2449 // code-completion results.
2450 AugmentedCodeCompleteConsumer *AugmentedConsumer
2451 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2452 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2454 // If we have a precompiled preamble, try to use it. We only allow
2455 // the use of the precompiled preamble if we're if the completion
2456 // point is within the main file, after the end of the precompiled
2458 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2459 if (!getPreambleFile(this).empty()) {
2460 std::string CompleteFilePath(File);
2462 auto VFS = FileMgr.getVirtualFileSystem();
2463 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2464 if (CompleteFileStatus) {
2465 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2467 std::string MainPath(OriginalSourceFile);
2468 auto MainStatus = VFS->status(MainPath);
2470 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2471 if (CompleteFileID == MainID && Line > 1)
2472 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2473 PCHContainerOps, Inv, VFS, false, Line - 1);
2478 // If the main file has been overridden due to the use of a preamble,
2479 // make that override happen and introduce the preamble.
2480 if (OverrideMainBuffer) {
2481 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2482 OverrideMainBuffer.get());
2483 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2484 PreprocessorOpts.PrecompiledPreambleBytes.second
2485 = PreambleEndsAtStartOfLine;
2486 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2487 PreprocessorOpts.DisablePCHValidation = true;
2489 OwnedBuffers.push_back(OverrideMainBuffer.release());
2491 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2492 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2495 // Disable the preprocessing record if modules are not enabled.
2496 if (!Clang->getLangOpts().Modules)
2497 PreprocessorOpts.DetailedRecord = false;
2499 std::unique_ptr<SyntaxOnlyAction> Act;
2500 Act.reset(new SyntaxOnlyAction);
2501 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2503 Act->EndSourceFile();
2507 bool ASTUnit::Save(StringRef File) {
2508 if (HadModuleLoaderFatalFailure)
2511 // Write to a temporary file and later rename it to the actual file, to avoid
2512 // possible race conditions.
2513 SmallString<128> TempPath;
2515 TempPath += "-%%%%%%%%";
2517 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2520 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2521 // unconditionally create a stat cache when we parse the file?
2522 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2526 if (Out.has_error()) {
2531 if (llvm::sys::fs::rename(TempPath, File)) {
2532 llvm::sys::fs::remove(TempPath);
2539 static bool serializeUnit(ASTWriter &Writer,
2540 SmallVectorImpl<char> &Buffer,
2544 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2546 // Write the generated bitstream to "Out".
2547 if (!Buffer.empty())
2548 OS.write(Buffer.data(), Buffer.size());
2553 bool ASTUnit::serialize(raw_ostream &OS) {
2554 // For serialization we are lenient if the errors were only warn-as-error kind.
2555 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2558 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2559 getSema(), hasErrors, OS);
2561 SmallString<128> Buffer;
2562 llvm::BitstreamWriter Stream(Buffer);
2563 MemoryBufferCache PCMCache;
2564 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2565 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2568 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2570 void ASTUnit::TranslateStoredDiagnostics(
2571 FileManager &FileMgr,
2572 SourceManager &SrcMgr,
2573 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2574 SmallVectorImpl<StoredDiagnostic> &Out) {
2575 // Map the standalone diagnostic into the new source manager. We also need to
2576 // remap all the locations to the new view. This includes the diag location,
2577 // any associated source ranges, and the source ranges of associated fix-its.
2578 // FIXME: There should be a cleaner way to do this.
2580 SmallVector<StoredDiagnostic, 4> Result;
2581 Result.reserve(Diags.size());
2582 const FileEntry *PreviousFE = nullptr;
2584 for (const StandaloneDiagnostic &SD : Diags) {
2585 // Rebuild the StoredDiagnostic.
2586 if (SD.Filename.empty())
2588 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2591 if (FE != PreviousFE) {
2592 FID = SrcMgr.translateFile(FE);
2595 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2596 if (FileLoc.isInvalid())
2598 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2599 FullSourceLoc Loc(L, SrcMgr);
2601 SmallVector<CharSourceRange, 4> Ranges;
2602 Ranges.reserve(SD.Ranges.size());
2603 for (const auto &Range : SD.Ranges) {
2604 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2605 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2606 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2609 SmallVector<FixItHint, 2> FixIts;
2610 FixIts.reserve(SD.FixIts.size());
2611 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2612 FixIts.push_back(FixItHint());
2613 FixItHint &FH = FixIts.back();
2614 FH.CodeToInsert = FixIt.CodeToInsert;
2615 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2616 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2617 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2620 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2621 SD.Message, Loc, Ranges, FixIts));
2626 void ASTUnit::addFileLevelDecl(Decl *D) {
2629 // We only care about local declarations.
2630 if (D->isFromASTFile())
2633 SourceManager &SM = *SourceMgr;
2634 SourceLocation Loc = D->getLocation();
2635 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2638 // We only keep track of the file-level declarations of each file.
2639 if (!D->getLexicalDeclContext()->isFileContext())
2642 SourceLocation FileLoc = SM.getFileLoc(Loc);
2643 assert(SM.isLocalSourceLocation(FileLoc));
2646 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2647 if (FID.isInvalid())
2650 LocDeclsTy *&Decls = FileDecls[FID];
2652 Decls = new LocDeclsTy();
2654 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2656 if (Decls->empty() || Decls->back().first <= Offset) {
2657 Decls->push_back(LocDecl);
2661 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2662 LocDecl, llvm::less_first());
2664 Decls->insert(I, LocDecl);
2667 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2668 SmallVectorImpl<Decl *> &Decls) {
2669 if (File.isInvalid())
2672 if (SourceMgr->isLoadedFileID(File)) {
2673 assert(Ctx->getExternalSource() && "No external source!");
2674 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2678 FileDeclsTy::iterator I = FileDecls.find(File);
2679 if (I == FileDecls.end())
2682 LocDeclsTy &LocDecls = *I->second;
2683 if (LocDecls.empty())
2686 LocDeclsTy::iterator BeginIt =
2687 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2688 std::make_pair(Offset, (Decl *)nullptr),
2689 llvm::less_first());
2690 if (BeginIt != LocDecls.begin())
2693 // If we are pointing at a top-level decl inside an objc container, we need
2694 // to backtrack until we find it otherwise we will fail to report that the
2695 // region overlaps with an objc container.
2696 while (BeginIt != LocDecls.begin() &&
2697 BeginIt->second->isTopLevelDeclInObjCContainer())
2700 LocDeclsTy::iterator EndIt = std::upper_bound(
2701 LocDecls.begin(), LocDecls.end(),
2702 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2703 if (EndIt != LocDecls.end())
2706 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2707 Decls.push_back(DIt->second);
2710 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2711 unsigned Line, unsigned Col) const {
2712 const SourceManager &SM = getSourceManager();
2713 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2714 return SM.getMacroArgExpandedLocation(Loc);
2717 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2718 unsigned Offset) const {
2719 const SourceManager &SM = getSourceManager();
2720 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2721 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2724 /// \brief If \arg Loc is a loaded location from the preamble, returns
2725 /// the corresponding local location of the main file, otherwise it returns
2727 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2730 PreambleID = SourceMgr->getPreambleFileID();
2732 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2736 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2737 SourceLocation FileLoc
2738 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2739 return FileLoc.getLocWithOffset(Offs);
2745 /// \brief If \arg Loc is a local location of the main file but inside the
2746 /// preamble chunk, returns the corresponding loaded location from the
2747 /// preamble, otherwise it returns \arg Loc.
2748 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2751 PreambleID = SourceMgr->getPreambleFileID();
2753 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2757 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2758 Offs < Preamble.size()) {
2759 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2760 return FileLoc.getLocWithOffset(Offs);
2766 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2769 FID = SourceMgr->getPreambleFileID();
2771 if (Loc.isInvalid() || FID.isInvalid())
2774 return SourceMgr->isInFileID(Loc, FID);
2777 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2780 FID = SourceMgr->getMainFileID();
2782 if (Loc.isInvalid() || FID.isInvalid())
2785 return SourceMgr->isInFileID(Loc, FID);
2788 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2791 FID = SourceMgr->getPreambleFileID();
2793 if (FID.isInvalid())
2794 return SourceLocation();
2796 return SourceMgr->getLocForEndOfFile(FID);
2799 SourceLocation ASTUnit::getStartOfMainFileID() {
2802 FID = SourceMgr->getMainFileID();
2804 if (FID.isInvalid())
2805 return SourceLocation();
2807 return SourceMgr->getLocForStartOfFile(FID);
2810 llvm::iterator_range<PreprocessingRecord::iterator>
2811 ASTUnit::getLocalPreprocessingEntities() const {
2812 if (isMainFileAST()) {
2813 serialization::ModuleFile &
2814 Mod = Reader->getModuleManager().getPrimaryModule();
2815 return Reader->getModulePreprocessedEntities(Mod);
2818 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2819 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2821 return llvm::make_range(PreprocessingRecord::iterator(),
2822 PreprocessingRecord::iterator());
2825 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2826 if (isMainFileAST()) {
2827 serialization::ModuleFile &
2828 Mod = Reader->getModuleManager().getPrimaryModule();
2829 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2830 if (!Fn(context, D))
2837 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2838 TLEnd = top_level_end();
2839 TL != TLEnd; ++TL) {
2840 if (!Fn(context, *TL))
2847 const FileEntry *ASTUnit::getPCHFile() {
2851 serialization::ModuleFile *Mod = nullptr;
2852 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2854 case serialization::MK_ImplicitModule:
2855 case serialization::MK_ExplicitModule:
2856 case serialization::MK_PrebuiltModule:
2857 return true; // skip dependencies.
2858 case serialization::MK_PCH:
2860 return true; // found it.
2861 case serialization::MK_Preamble:
2862 return false; // look in dependencies.
2863 case serialization::MK_MainFile:
2864 return false; // look in dependencies.
2875 bool ASTUnit::isModuleFile() {
2876 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2879 void ASTUnit::PreambleData::countLines() const {
2884 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2886 if (Buffer.back() != '\n')
2891 ASTUnit::ConcurrencyState::ConcurrencyState() {
2892 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2895 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2896 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2899 void ASTUnit::ConcurrencyState::start() {
2900 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2901 assert(acquired && "Concurrent access to ASTUnit!");
2904 void ASTUnit::ConcurrencyState::finish() {
2905 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2910 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2911 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2912 void ASTUnit::ConcurrencyState::start() {}
2913 void ASTUnit::ConcurrencyState::finish() {}