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