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