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