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