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