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