]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp
Merge ^/head r317808 through r317970.
[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().getFormat() ==
1080              InputKind::Source &&
1081          "FIXME: AST inputs not yet supported here!");
1082   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1083              InputKind::LLVM_IR &&
1084          "IR inputs not support here!");
1085
1086   // Configure the various subsystems.
1087   LangOpts = Clang->getInvocation().LangOpts;
1088   FileSystemOpts = Clang->getFileSystemOpts();
1089   if (!FileMgr) {
1090     Clang->createFileManager();
1091     FileMgr = &Clang->getFileManager();
1092   }
1093   SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1094                                 UserFilesAreVolatile);
1095   TheSema.reset();
1096   Ctx = nullptr;
1097   PP = nullptr;
1098   Reader = nullptr;
1099
1100   // Clear out old caches and data.
1101   TopLevelDecls.clear();
1102   clearFileLevelDecls();
1103   CleanTemporaryFiles();
1104
1105   if (!OverrideMainBuffer) {
1106     checkAndRemoveNonDriverDiags(StoredDiagnostics);
1107     TopLevelDeclsInPreamble.clear();
1108   }
1109
1110   // Create a file manager object to provide access to and cache the filesystem.
1111   Clang->setFileManager(&getFileManager());
1112   
1113   // Create the source manager.
1114   Clang->setSourceManager(&getSourceManager());
1115   
1116   // If the main file has been overridden due to the use of a preamble,
1117   // make that override happen and introduce the preamble.
1118   PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1119   if (OverrideMainBuffer) {
1120     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1121                                      OverrideMainBuffer.get());
1122     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1123     PreprocessorOpts.PrecompiledPreambleBytes.second
1124                                                     = PreambleEndsAtStartOfLine;
1125     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1126     PreprocessorOpts.DisablePCHValidation = true;
1127     
1128     // The stored diagnostic has the old source manager in it; update
1129     // the locations to refer into the new source manager. Since we've
1130     // been careful to make sure that the source manager's state
1131     // before and after are identical, so that we can reuse the source
1132     // location itself.
1133     checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1134
1135     // Keep track of the override buffer;
1136     SavedMainFileBuffer = std::move(OverrideMainBuffer);
1137   }
1138
1139   std::unique_ptr<TopLevelDeclTrackerAction> Act(
1140       new TopLevelDeclTrackerAction(*this));
1141
1142   // Recover resources if we crash before exiting this method.
1143   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1144     ActCleanup(Act.get());
1145
1146   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1147     goto error;
1148
1149   if (SavedMainFileBuffer)
1150     TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1151                                PreambleDiagnostics, StoredDiagnostics);
1152
1153   if (!Act->Execute())
1154     goto error;
1155
1156   transferASTDataFromCompilerInstance(*Clang);
1157   
1158   Act->EndSourceFile();
1159
1160   FailedParseDiagnostics.clear();
1161
1162   return false;
1163
1164 error:
1165   // Remove the overridden buffer we used for the preamble.
1166   SavedMainFileBuffer = nullptr;
1167
1168   // Keep the ownership of the data in the ASTUnit because the client may
1169   // want to see the diagnostics.
1170   transferASTDataFromCompilerInstance(*Clang);
1171   FailedParseDiagnostics.swap(StoredDiagnostics);
1172   StoredDiagnostics.clear();
1173   NumStoredDiagnosticsFromDriver = 0;
1174   return true;
1175 }
1176
1177 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1178 static std::string GetPreamblePCHPath() {
1179   // FIXME: This is a hack so that we can override the preamble file during
1180   // crash-recovery testing, which is the only case where the preamble files
1181   // are not necessarily cleaned up.
1182   const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1183   if (TmpFile)
1184     return TmpFile;
1185
1186   SmallString<128> Path;
1187   llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1188
1189   return Path.str();
1190 }
1191
1192 /// \brief Compute the preamble for the main file, providing the source buffer
1193 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1194 /// that describes the preamble.
1195 ASTUnit::ComputedPreamble
1196 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1197   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1198   PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1199   
1200   // Try to determine if the main file has been remapped, either from the 
1201   // command line (to another file) or directly through the compiler invocation
1202   // (to a memory buffer).
1203   llvm::MemoryBuffer *Buffer = nullptr;
1204   std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1205   std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1206   llvm::sys::fs::UniqueID MainFileID;
1207   if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1208     // Check whether there is a file-file remapping of the main file
1209     for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1210       std::string MPath(RF.first);
1211       llvm::sys::fs::UniqueID MID;
1212       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1213         if (MainFileID == MID) {
1214           // We found a remapping. Try to load the resulting, remapped source.
1215           BufferOwner = getBufferForFile(RF.second);
1216           if (!BufferOwner)
1217             return ComputedPreamble(nullptr, nullptr, 0, true);
1218         }
1219       }
1220     }
1221     
1222     // Check whether there is a file-buffer remapping. It supercedes the
1223     // file-file remapping.
1224     for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1225       std::string MPath(RB.first);
1226       llvm::sys::fs::UniqueID MID;
1227       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1228         if (MainFileID == MID) {
1229           // We found a remapping.
1230           BufferOwner.reset();
1231           Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1232         }
1233       }
1234     }
1235   }
1236   
1237   // If the main source file was not remapped, load it now.
1238   if (!Buffer && !BufferOwner) {
1239     BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1240     if (!BufferOwner)
1241       return ComputedPreamble(nullptr, nullptr, 0, true);
1242   }
1243
1244   if (!Buffer)
1245     Buffer = BufferOwner.get();
1246   auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1247                                     *Invocation.getLangOpts(), MaxLines);
1248   return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1249                           Pre.second);
1250 }
1251
1252 ASTUnit::PreambleFileHash
1253 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1254   PreambleFileHash Result;
1255   Result.Size = Size;
1256   Result.ModTime = ModTime;
1257   Result.MD5 = {};
1258   return Result;
1259 }
1260
1261 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1262     const llvm::MemoryBuffer *Buffer) {
1263   PreambleFileHash Result;
1264   Result.Size = Buffer->getBufferSize();
1265   Result.ModTime = 0;
1266
1267   llvm::MD5 MD5Ctx;
1268   MD5Ctx.update(Buffer->getBuffer().data());
1269   MD5Ctx.final(Result.MD5);
1270
1271   return Result;
1272 }
1273
1274 namespace clang {
1275 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1276                 const ASTUnit::PreambleFileHash &RHS) {
1277   return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1278          LHS.MD5 == RHS.MD5;
1279 }
1280 } // namespace clang
1281
1282 static std::pair<unsigned, unsigned>
1283 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1284                     const LangOptions &LangOpts) {
1285   CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1286   unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1287   unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1288   return std::make_pair(Offset, EndOffset);
1289 }
1290
1291 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1292                                                     const LangOptions &LangOpts,
1293                                                     const FixItHint &InFix) {
1294   ASTUnit::StandaloneFixIt OutFix;
1295   OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1296   OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1297                                                LangOpts);
1298   OutFix.CodeToInsert = InFix.CodeToInsert;
1299   OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1300   return OutFix;
1301 }
1302
1303 static ASTUnit::StandaloneDiagnostic
1304 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1305                          const StoredDiagnostic &InDiag) {
1306   ASTUnit::StandaloneDiagnostic OutDiag;
1307   OutDiag.ID = InDiag.getID();
1308   OutDiag.Level = InDiag.getLevel();
1309   OutDiag.Message = InDiag.getMessage();
1310   OutDiag.LocOffset = 0;
1311   if (InDiag.getLocation().isInvalid())
1312     return OutDiag;
1313   const SourceManager &SM = InDiag.getLocation().getManager();
1314   SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1315   OutDiag.Filename = SM.getFilename(FileLoc);
1316   if (OutDiag.Filename.empty())
1317     return OutDiag;
1318   OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1319   for (const CharSourceRange &Range : InDiag.getRanges())
1320     OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1321   for (const FixItHint &FixIt : InDiag.getFixIts())
1322     OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1323
1324   return OutDiag;
1325 }
1326
1327 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1328 /// the source file.
1329 ///
1330 /// This routine will compute the preamble of the main source file. If a
1331 /// non-trivial preamble is found, it will precompile that preamble into a 
1332 /// precompiled header so that the precompiled preamble can be used to reduce
1333 /// reparsing time. If a precompiled preamble has already been constructed,
1334 /// this routine will determine if it is still valid and, if so, avoid 
1335 /// rebuilding the precompiled preamble.
1336 ///
1337 /// \param AllowRebuild When true (the default), this routine is
1338 /// allowed to rebuild the precompiled preamble if it is found to be
1339 /// out-of-date.
1340 ///
1341 /// \param MaxLines When non-zero, the maximum number of lines that
1342 /// can occur within the preamble.
1343 ///
1344 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1345 /// buffer that should be used in place of the main file when doing so.
1346 /// Otherwise, returns a NULL pointer.
1347 std::unique_ptr<llvm::MemoryBuffer>
1348 ASTUnit::getMainBufferWithPrecompiledPreamble(
1349     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1350     const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1351     unsigned MaxLines) {
1352
1353   auto PreambleInvocation =
1354       std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1355   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1356   PreprocessorOptions &PreprocessorOpts
1357     = PreambleInvocation->getPreprocessorOpts();
1358
1359   ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1360
1361   if (!NewPreamble.Size) {
1362     // We couldn't find a preamble in the main source. Clear out the current
1363     // preamble, if we have one. It's obviously no good any more.
1364     Preamble.clear();
1365     erasePreambleFile(this);
1366
1367     // The next time we actually see a preamble, precompile it.
1368     PreambleRebuildCounter = 1;
1369     return nullptr;
1370   }
1371   
1372   if (!Preamble.empty()) {
1373     // We've previously computed a preamble. Check whether we have the same
1374     // preamble now that we did before, and that there's enough space in
1375     // the main-file buffer within the precompiled preamble to fit the
1376     // new main file.
1377     if (Preamble.size() == NewPreamble.Size &&
1378         PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1379         memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1380                NewPreamble.Size) == 0) {
1381       // The preamble has not changed. We may be able to re-use the precompiled
1382       // preamble.
1383
1384       // Check that none of the files used by the preamble have changed.
1385       bool AnyFileChanged = false;
1386           
1387       // First, make a record of those files that have been overridden via
1388       // remapping or unsaved_files.
1389       std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1390       for (const auto &R : PreprocessorOpts.RemappedFiles) {
1391         if (AnyFileChanged)
1392           break;
1393
1394         vfs::Status Status;
1395         if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1396           // If we can't stat the file we're remapping to, assume that something
1397           // horrible happened.
1398           AnyFileChanged = true;
1399           break;
1400         }
1401
1402         OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1403             Status.getSize(),
1404             llvm::sys::toTimeT(Status.getLastModificationTime()));
1405       }
1406
1407       for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1408         if (AnyFileChanged)
1409           break;
1410
1411         vfs::Status Status;
1412         if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1413           AnyFileChanged = true;
1414           break;
1415         }
1416
1417         OverriddenFiles[Status.getUniqueID()] =
1418             PreambleFileHash::createForMemoryBuffer(RB.second);
1419       }
1420        
1421       // Check whether anything has changed.
1422       for (llvm::StringMap<PreambleFileHash>::iterator
1423              F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1424            !AnyFileChanged && F != FEnd; 
1425            ++F) {
1426         vfs::Status Status;
1427         if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1428           // If we can't stat the file, assume that something horrible happened.
1429           AnyFileChanged = true;
1430           break;
1431         }
1432
1433         std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1434           = OverriddenFiles.find(Status.getUniqueID());
1435         if (Overridden != OverriddenFiles.end()) {
1436           // This file was remapped; check whether the newly-mapped file 
1437           // matches up with the previous mapping.
1438           if (Overridden->second != F->second)
1439             AnyFileChanged = true;
1440           continue;
1441         }
1442         
1443         // The file was not remapped; check whether it has changed on disk.
1444         if (Status.getSize() != uint64_t(F->second.Size) ||
1445             llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1446                 F->second.ModTime)
1447           AnyFileChanged = true;
1448       }
1449           
1450       if (!AnyFileChanged) {
1451         // Okay! We can re-use the precompiled preamble.
1452
1453         // Set the state of the diagnostic object to mimic its state
1454         // after parsing the preamble.
1455         getDiagnostics().Reset();
1456         ProcessWarningOptions(getDiagnostics(), 
1457                               PreambleInvocation->getDiagnosticOpts());
1458         getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1459
1460         return llvm::MemoryBuffer::getMemBufferCopy(
1461             NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1462       }
1463     }
1464
1465     // If we aren't allowed to rebuild the precompiled preamble, just
1466     // return now.
1467     if (!AllowRebuild)
1468       return nullptr;
1469
1470     // We can't reuse the previously-computed preamble. Build a new one.
1471     Preamble.clear();
1472     PreambleDiagnostics.clear();
1473     erasePreambleFile(this);
1474     PreambleRebuildCounter = 1;
1475   } else if (!AllowRebuild) {
1476     // We aren't allowed to rebuild the precompiled preamble; just
1477     // return now.
1478     return nullptr;
1479   }
1480
1481   // If the preamble rebuild counter > 1, it's because we previously
1482   // failed to build a preamble and we're not yet ready to try
1483   // again. Decrement the counter and return a failure.
1484   if (PreambleRebuildCounter > 1) {
1485     --PreambleRebuildCounter;
1486     return nullptr;
1487   }
1488
1489   // Create a temporary file for the precompiled preamble. In rare 
1490   // circumstances, this can fail.
1491   std::string PreamblePCHPath = GetPreamblePCHPath();
1492   if (PreamblePCHPath.empty()) {
1493     // Try again next time.
1494     PreambleRebuildCounter = 1;
1495     return nullptr;
1496   }
1497   
1498   // We did not previously compute a preamble, or it can't be reused anyway.
1499   SimpleTimer PreambleTimer(WantTiming);
1500   PreambleTimer.setOutput("Precompiling preamble");
1501
1502   // Save the preamble text for later; we'll need to compare against it for
1503   // subsequent reparses.
1504   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1505   Preamble.assign(FileMgr->getFile(MainFilename),
1506                   NewPreamble.Buffer->getBufferStart(),
1507                   NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1508   PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1509
1510   PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1511       NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1512
1513   // Remap the main source file to the preamble buffer.
1514   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1515   PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1516
1517   // Tell the compiler invocation to generate a temporary precompiled header.
1518   FrontendOpts.ProgramAction = frontend::GeneratePCH;
1519   // FIXME: Generate the precompiled header into memory?
1520   FrontendOpts.OutputFile = PreamblePCHPath;
1521   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1522   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1523   
1524   // Create the compiler instance to use for building the precompiled preamble.
1525   std::unique_ptr<CompilerInstance> Clang(
1526       new CompilerInstance(std::move(PCHContainerOps)));
1527
1528   // Recover resources if we crash before exiting this method.
1529   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1530     CICleanup(Clang.get());
1531
1532   Clang->setInvocation(std::move(PreambleInvocation));
1533   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1534   
1535   // Set up diagnostics, capturing all of the diagnostics produced.
1536   Clang->setDiagnostics(&getDiagnostics());
1537   
1538   // Create the target instance.
1539   Clang->setTarget(TargetInfo::CreateTargetInfo(
1540       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1541   if (!Clang->hasTarget()) {
1542     llvm::sys::fs::remove(FrontendOpts.OutputFile);
1543     Preamble.clear();
1544     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1545     PreprocessorOpts.RemappedFileBuffers.pop_back();
1546     return nullptr;
1547   }
1548   
1549   // Inform the target of the language options.
1550   //
1551   // FIXME: We shouldn't need to do this, the target should be immutable once
1552   // created. This complexity should be lifted elsewhere.
1553   Clang->getTarget().adjust(Clang->getLangOpts());
1554   
1555   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1556          "Invocation must have exactly one source file!");
1557   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1558              InputKind::Source &&
1559          "FIXME: AST inputs not yet supported here!");
1560   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1561              InputKind::LLVM_IR &&
1562          "IR inputs not support here!");
1563   
1564   // Clear out old caches and data.
1565   getDiagnostics().Reset();
1566   ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1567   checkAndRemoveNonDriverDiags(StoredDiagnostics);
1568   TopLevelDecls.clear();
1569   TopLevelDeclsInPreamble.clear();
1570   PreambleDiagnostics.clear();
1571
1572   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1573       createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1574   if (!VFS)
1575     return nullptr;
1576
1577   // Create a file manager object to provide access to and cache the filesystem.
1578   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1579   
1580   // Create the source manager.
1581   Clang->setSourceManager(new SourceManager(getDiagnostics(),
1582                                             Clang->getFileManager()));
1583
1584   auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1585   Clang->addDependencyCollector(PreambleDepCollector);
1586
1587   std::unique_ptr<PrecompilePreambleAction> Act;
1588   Act.reset(new PrecompilePreambleAction(*this));
1589   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1590     llvm::sys::fs::remove(FrontendOpts.OutputFile);
1591     Preamble.clear();
1592     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1593     PreprocessorOpts.RemappedFileBuffers.pop_back();
1594     return nullptr;
1595   }
1596   
1597   Act->Execute();
1598
1599   // Transfer any diagnostics generated when parsing the preamble into the set
1600   // of preamble diagnostics.
1601   for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1602                             E = stored_diag_end();
1603        I != E; ++I)
1604     PreambleDiagnostics.push_back(
1605         makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1606
1607   Act->EndSourceFile();
1608
1609   checkAndRemoveNonDriverDiags(StoredDiagnostics);
1610
1611   if (!Act->hasEmittedPreamblePCH()) {
1612     // The preamble PCH failed (e.g. there was a module loading fatal error),
1613     // so no precompiled header was generated. Forget that we even tried.
1614     // FIXME: Should we leave a note for ourselves to try again?
1615     llvm::sys::fs::remove(FrontendOpts.OutputFile);
1616     Preamble.clear();
1617     TopLevelDeclsInPreamble.clear();
1618     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1619     PreprocessorOpts.RemappedFileBuffers.pop_back();
1620     return nullptr;
1621   }
1622   
1623   // Keep track of the preamble we precompiled.
1624   setPreambleFile(this, FrontendOpts.OutputFile);
1625   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1626   
1627   // Keep track of all of the files that the source manager knows about,
1628   // so we can verify whether they have changed or not.
1629   FilesInPreamble.clear();
1630   SourceManager &SourceMgr = Clang->getSourceManager();
1631   for (auto &Filename : PreambleDepCollector->getDependencies()) {
1632     const FileEntry *File = Clang->getFileManager().getFile(Filename);
1633     if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1634       continue;
1635     if (time_t ModTime = File->getModificationTime()) {
1636       FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1637           File->getSize(), ModTime);
1638     } else {
1639       llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1640       FilesInPreamble[File->getName()] =
1641           PreambleFileHash::createForMemoryBuffer(Buffer);
1642     }
1643   }
1644
1645   PreambleRebuildCounter = 1;
1646   PreprocessorOpts.RemappedFileBuffers.pop_back();
1647
1648   // If the hash of top-level entities differs from the hash of the top-level
1649   // entities the last time we rebuilt the preamble, clear out the completion
1650   // cache.
1651   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1652     CompletionCacheTopLevelHashValue = 0;
1653     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1654   }
1655
1656   return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1657                                               MainFilename);
1658 }
1659
1660 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1661   std::vector<Decl *> Resolved;
1662   Resolved.reserve(TopLevelDeclsInPreamble.size());
1663   ExternalASTSource &Source = *getASTContext().getExternalSource();
1664   for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1665     // Resolve the declaration ID to an actual declaration, possibly
1666     // deserializing the declaration in the process.
1667     if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1668       Resolved.push_back(D);
1669   }
1670   TopLevelDeclsInPreamble.clear();
1671   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1672 }
1673
1674 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1675   // Steal the created target, context, and preprocessor if they have been
1676   // created.
1677   assert(CI.hasInvocation() && "missing invocation");
1678   LangOpts = CI.getInvocation().LangOpts;
1679   TheSema = CI.takeSema();
1680   Consumer = CI.takeASTConsumer();
1681   if (CI.hasASTContext())
1682     Ctx = &CI.getASTContext();
1683   if (CI.hasPreprocessor())
1684     PP = CI.getPreprocessorPtr();
1685   CI.setSourceManager(nullptr);
1686   CI.setFileManager(nullptr);
1687   if (CI.hasTarget())
1688     Target = &CI.getTarget();
1689   Reader = CI.getModuleManager();
1690   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1691 }
1692
1693 StringRef ASTUnit::getMainFileName() const {
1694   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1695     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1696     if (Input.isFile())
1697       return Input.getFile();
1698     else
1699       return Input.getBuffer()->getBufferIdentifier();
1700   }
1701
1702   if (SourceMgr) {
1703     if (const FileEntry *
1704           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1705       return FE->getName();
1706   }
1707
1708   return StringRef();
1709 }
1710
1711 StringRef ASTUnit::getASTFileName() const {
1712   if (!isMainFileAST())
1713     return StringRef();
1714
1715   serialization::ModuleFile &
1716     Mod = Reader->getModuleManager().getPrimaryModule();
1717   return Mod.FileName;
1718 }
1719
1720 std::unique_ptr<ASTUnit>
1721 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1722                 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1723                 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1724   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1725   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1726   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1727       createVFSFromCompilerInvocation(*CI, *Diags);
1728   if (!VFS)
1729     return nullptr;
1730   AST->Diagnostics = Diags;
1731   AST->FileSystemOpts = CI->getFileSystemOpts();
1732   AST->Invocation = std::move(CI);
1733   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1734   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1735   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1736                                      UserFilesAreVolatile);
1737   AST->PCMCache = new MemoryBufferCache;
1738
1739   return AST;
1740 }
1741
1742 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1743     std::shared_ptr<CompilerInvocation> CI,
1744     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1745     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1746     ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1747     bool OnlyLocalDecls, bool CaptureDiagnostics,
1748     unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1749     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1750     std::unique_ptr<ASTUnit> *ErrAST) {
1751   assert(CI && "A CompilerInvocation is required");
1752
1753   std::unique_ptr<ASTUnit> OwnAST;
1754   ASTUnit *AST = Unit;
1755   if (!AST) {
1756     // Create the AST unit.
1757     OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1758     AST = OwnAST.get();
1759     if (!AST)
1760       return nullptr;
1761   }
1762   
1763   if (!ResourceFilesPath.empty()) {
1764     // Override the resources path.
1765     CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1766   }
1767   AST->OnlyLocalDecls = OnlyLocalDecls;
1768   AST->CaptureDiagnostics = CaptureDiagnostics;
1769   if (PrecompilePreambleAfterNParses > 0)
1770     AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1771   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1772   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1773   AST->IncludeBriefCommentsInCodeCompletion
1774     = IncludeBriefCommentsInCodeCompletion;
1775
1776   // Recover resources if we crash before exiting this method.
1777   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1778     ASTUnitCleanup(OwnAST.get());
1779   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1780     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1781     DiagCleanup(Diags.get());
1782
1783   // We'll manage file buffers ourselves.
1784   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1785   CI->getFrontendOpts().DisableFree = false;
1786   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1787
1788   // Create the compiler instance to use for building the AST.
1789   std::unique_ptr<CompilerInstance> Clang(
1790       new CompilerInstance(std::move(PCHContainerOps)));
1791
1792   // Recover resources if we crash before exiting this method.
1793   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1794     CICleanup(Clang.get());
1795
1796   Clang->setInvocation(std::move(CI));
1797   AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1798     
1799   // Set up diagnostics, capturing any diagnostics that would
1800   // otherwise be dropped.
1801   Clang->setDiagnostics(&AST->getDiagnostics());
1802   
1803   // Create the target instance.
1804   Clang->setTarget(TargetInfo::CreateTargetInfo(
1805       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1806   if (!Clang->hasTarget())
1807     return nullptr;
1808
1809   // Inform the target of the language options.
1810   //
1811   // FIXME: We shouldn't need to do this, the target should be immutable once
1812   // created. This complexity should be lifted elsewhere.
1813   Clang->getTarget().adjust(Clang->getLangOpts());
1814   
1815   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1816          "Invocation must have exactly one source file!");
1817   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1818              InputKind::Source &&
1819          "FIXME: AST inputs not yet supported here!");
1820   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1821              InputKind::LLVM_IR &&
1822          "IR inputs not support here!");
1823
1824   // Configure the various subsystems.
1825   AST->TheSema.reset();
1826   AST->Ctx = nullptr;
1827   AST->PP = nullptr;
1828   AST->Reader = nullptr;
1829
1830   // Create a file manager object to provide access to and cache the filesystem.
1831   Clang->setFileManager(&AST->getFileManager());
1832   
1833   // Create the source manager.
1834   Clang->setSourceManager(&AST->getSourceManager());
1835
1836   FrontendAction *Act = Action;
1837
1838   std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1839   if (!Act) {
1840     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1841     Act = TrackerAct.get();
1842   }
1843
1844   // Recover resources if we crash before exiting this method.
1845   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1846     ActCleanup(TrackerAct.get());
1847
1848   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1849     AST->transferASTDataFromCompilerInstance(*Clang);
1850     if (OwnAST && ErrAST)
1851       ErrAST->swap(OwnAST);
1852
1853     return nullptr;
1854   }
1855
1856   if (Persistent && !TrackerAct) {
1857     Clang->getPreprocessor().addPPCallbacks(
1858         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1859                                            AST->getCurrentTopLevelHashValue()));
1860     std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1861     if (Clang->hasASTConsumer())
1862       Consumers.push_back(Clang->takeASTConsumer());
1863     Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1864         *AST, AST->getCurrentTopLevelHashValue()));
1865     Clang->setASTConsumer(
1866         llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1867   }
1868   if (!Act->Execute()) {
1869     AST->transferASTDataFromCompilerInstance(*Clang);
1870     if (OwnAST && ErrAST)
1871       ErrAST->swap(OwnAST);
1872
1873     return nullptr;
1874   }
1875
1876   // Steal the created target, context, and preprocessor.
1877   AST->transferASTDataFromCompilerInstance(*Clang);
1878   
1879   Act->EndSourceFile();
1880
1881   if (OwnAST)
1882     return OwnAST.release();
1883   else
1884     return AST;
1885 }
1886
1887 bool ASTUnit::LoadFromCompilerInvocation(
1888     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1889     unsigned PrecompilePreambleAfterNParses) {
1890   if (!Invocation)
1891     return true;
1892   
1893   // We'll manage file buffers ourselves.
1894   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1895   Invocation->getFrontendOpts().DisableFree = false;
1896   getDiagnostics().Reset();
1897   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1898
1899   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1900   if (PrecompilePreambleAfterNParses > 0) {
1901     PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1902     OverrideMainBuffer =
1903         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1904     getDiagnostics().Reset();
1905     ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1906   }
1907   
1908   SimpleTimer ParsingTimer(WantTiming);
1909   ParsingTimer.setOutput("Parsing " + getMainFileName());
1910   
1911   // Recover resources if we crash before exiting this method.
1912   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1913     MemBufferCleanup(OverrideMainBuffer.get());
1914
1915   return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1916 }
1917
1918 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1919     std::shared_ptr<CompilerInvocation> CI,
1920     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1921     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1922     bool OnlyLocalDecls, bool CaptureDiagnostics,
1923     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1924     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1925     bool UserFilesAreVolatile) {
1926   // Create the AST unit.
1927   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1928   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1929   AST->Diagnostics = Diags;
1930   AST->OnlyLocalDecls = OnlyLocalDecls;
1931   AST->CaptureDiagnostics = CaptureDiagnostics;
1932   AST->TUKind = TUKind;
1933   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1934   AST->IncludeBriefCommentsInCodeCompletion
1935     = IncludeBriefCommentsInCodeCompletion;
1936   AST->Invocation = std::move(CI);
1937   AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1938   AST->FileMgr = FileMgr;
1939   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1940   
1941   // Recover resources if we crash before exiting this method.
1942   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1943     ASTUnitCleanup(AST.get());
1944   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1945     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1946     DiagCleanup(Diags.get());
1947
1948   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1949                                       PrecompilePreambleAfterNParses))
1950     return nullptr;
1951   return AST;
1952 }
1953
1954 ASTUnit *ASTUnit::LoadFromCommandLine(
1955     const char **ArgBegin, const char **ArgEnd,
1956     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1957     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1958     bool OnlyLocalDecls, bool CaptureDiagnostics,
1959     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1960     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1961     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1962     bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1963     bool UserFilesAreVolatile, bool ForSerialization,
1964     llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
1965   assert(Diags.get() && "no DiagnosticsEngine was provided");
1966
1967   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1968
1969   std::shared_ptr<CompilerInvocation> CI;
1970
1971   {
1972
1973     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, 
1974                                       StoredDiagnostics);
1975
1976     CI = clang::createInvocationFromCommandLine(
1977         llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1978     if (!CI)
1979       return nullptr;
1980   }
1981
1982   // Override any files that need remapping
1983   for (const auto &RemappedFile : RemappedFiles) {
1984     CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1985                                               RemappedFile.second);
1986   }
1987   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1988   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1989   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1990   
1991   // Override the resources path.
1992   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1993
1994   CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1995
1996   if (ModuleFormat)
1997     CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1998
1999   // Create the AST unit.
2000   std::unique_ptr<ASTUnit> AST;
2001   AST.reset(new ASTUnit(false));
2002   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
2003   AST->Diagnostics = Diags;
2004   AST->FileSystemOpts = CI->getFileSystemOpts();
2005   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2006       createVFSFromCompilerInvocation(*CI, *Diags);
2007   if (!VFS)
2008     return nullptr;
2009   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
2010   AST->PCMCache = new MemoryBufferCache;
2011   AST->OnlyLocalDecls = OnlyLocalDecls;
2012   AST->CaptureDiagnostics = CaptureDiagnostics;
2013   AST->TUKind = TUKind;
2014   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2015   AST->IncludeBriefCommentsInCodeCompletion
2016     = IncludeBriefCommentsInCodeCompletion;
2017   AST->UserFilesAreVolatile = UserFilesAreVolatile;
2018   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2019   AST->StoredDiagnostics.swap(StoredDiagnostics);
2020   AST->Invocation = CI;
2021   if (ForSerialization)
2022     AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2023   // Zero out now to ease cleanup during crash recovery.
2024   CI = nullptr;
2025   Diags = nullptr;
2026
2027   // Recover resources if we crash before exiting this method.
2028   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2029     ASTUnitCleanup(AST.get());
2030
2031   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2032                                       PrecompilePreambleAfterNParses)) {
2033     // Some error occurred, if caller wants to examine diagnostics, pass it the
2034     // ASTUnit.
2035     if (ErrAST) {
2036       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2037       ErrAST->swap(AST);
2038     }
2039     return nullptr;
2040   }
2041
2042   return AST.release();
2043 }
2044
2045 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2046                       ArrayRef<RemappedFile> RemappedFiles) {
2047   if (!Invocation)
2048     return true;
2049
2050   clearFileLevelDecls();
2051   
2052   SimpleTimer ParsingTimer(WantTiming);
2053   ParsingTimer.setOutput("Reparsing " + getMainFileName());
2054
2055   // Remap files.
2056   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2057   for (const auto &RB : PPOpts.RemappedFileBuffers)
2058     delete RB.second;
2059
2060   Invocation->getPreprocessorOpts().clearRemappedFiles();
2061   for (const auto &RemappedFile : RemappedFiles) {
2062     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2063                                                       RemappedFile.second);
2064   }
2065
2066   // If we have a preamble file lying around, or if we might try to
2067   // build a precompiled preamble, do so now.
2068   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2069   if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2070     OverrideMainBuffer =
2071         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2072
2073   // Clear out the diagnostics state.
2074   FileMgr.reset();
2075   getDiagnostics().Reset();
2076   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2077   if (OverrideMainBuffer)
2078     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2079
2080   // Parse the sources
2081   bool Result =
2082       Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2083
2084   // If we're caching global code-completion results, and the top-level 
2085   // declarations have changed, clear out the code-completion cache.
2086   if (!Result && ShouldCacheCodeCompletionResults &&
2087       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2088     CacheCodeCompletionResults();
2089
2090   // We now need to clear out the completion info related to this translation
2091   // unit; it'll be recreated if necessary.
2092   CCTUInfo.reset();
2093   
2094   return Result;
2095 }
2096
2097 //----------------------------------------------------------------------------//
2098 // Code completion
2099 //----------------------------------------------------------------------------//
2100
2101 namespace {
2102   /// \brief Code completion consumer that combines the cached code-completion
2103   /// results from an ASTUnit with the code-completion results provided to it,
2104   /// then passes the result on to 
2105   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2106     uint64_t NormalContexts;
2107     ASTUnit &AST;
2108     CodeCompleteConsumer &Next;
2109     
2110   public:
2111     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2112                                   const CodeCompleteOptions &CodeCompleteOpts)
2113       : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2114         AST(AST), Next(Next)
2115     { 
2116       // Compute the set of contexts in which we will look when we don't have
2117       // any information about the specific context.
2118       NormalContexts 
2119         = (1LL << CodeCompletionContext::CCC_TopLevel)
2120         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2121         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2122         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2123         | (1LL << CodeCompletionContext::CCC_Statement)
2124         | (1LL << CodeCompletionContext::CCC_Expression)
2125         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2126         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2127         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2128         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2129         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2130         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2131         | (1LL << CodeCompletionContext::CCC_Recovery);
2132
2133       if (AST.getASTContext().getLangOpts().CPlusPlus)
2134         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2135                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
2136                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2137     }
2138
2139     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2140                                     CodeCompletionResult *Results,
2141                                     unsigned NumResults) override;
2142
2143     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2144                                    OverloadCandidate *Candidates,
2145                                    unsigned NumCandidates) override {
2146       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2147     }
2148
2149     CodeCompletionAllocator &getAllocator() override {
2150       return Next.getAllocator();
2151     }
2152
2153     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2154       return Next.getCodeCompletionTUInfo();
2155     }
2156   };
2157 } // anonymous namespace
2158
2159 /// \brief Helper function that computes which global names are hidden by the
2160 /// local code-completion results.
2161 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2162                                  CodeCompletionResult *Results,
2163                                  unsigned NumResults,
2164                                  ASTContext &Ctx,
2165                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2166   bool OnlyTagNames = false;
2167   switch (Context.getKind()) {
2168   case CodeCompletionContext::CCC_Recovery:
2169   case CodeCompletionContext::CCC_TopLevel:
2170   case CodeCompletionContext::CCC_ObjCInterface:
2171   case CodeCompletionContext::CCC_ObjCImplementation:
2172   case CodeCompletionContext::CCC_ObjCIvarList:
2173   case CodeCompletionContext::CCC_ClassStructUnion:
2174   case CodeCompletionContext::CCC_Statement:
2175   case CodeCompletionContext::CCC_Expression:
2176   case CodeCompletionContext::CCC_ObjCMessageReceiver:
2177   case CodeCompletionContext::CCC_DotMemberAccess:
2178   case CodeCompletionContext::CCC_ArrowMemberAccess:
2179   case CodeCompletionContext::CCC_ObjCPropertyAccess:
2180   case CodeCompletionContext::CCC_Namespace:
2181   case CodeCompletionContext::CCC_Type:
2182   case CodeCompletionContext::CCC_Name:
2183   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2184   case CodeCompletionContext::CCC_ParenthesizedExpression:
2185   case CodeCompletionContext::CCC_ObjCInterfaceName:
2186     break;
2187     
2188   case CodeCompletionContext::CCC_EnumTag:
2189   case CodeCompletionContext::CCC_UnionTag:
2190   case CodeCompletionContext::CCC_ClassOrStructTag:
2191     OnlyTagNames = true;
2192     break;
2193     
2194   case CodeCompletionContext::CCC_ObjCProtocolName:
2195   case CodeCompletionContext::CCC_MacroName:
2196   case CodeCompletionContext::CCC_MacroNameUse:
2197   case CodeCompletionContext::CCC_PreprocessorExpression:
2198   case CodeCompletionContext::CCC_PreprocessorDirective:
2199   case CodeCompletionContext::CCC_NaturalLanguage:
2200   case CodeCompletionContext::CCC_SelectorName:
2201   case CodeCompletionContext::CCC_TypeQualifiers:
2202   case CodeCompletionContext::CCC_Other:
2203   case CodeCompletionContext::CCC_OtherWithMacros:
2204   case CodeCompletionContext::CCC_ObjCInstanceMessage:
2205   case CodeCompletionContext::CCC_ObjCClassMessage:
2206   case CodeCompletionContext::CCC_ObjCCategoryName:
2207     // We're looking for nothing, or we're looking for names that cannot
2208     // be hidden.
2209     return;
2210   }
2211   
2212   typedef CodeCompletionResult Result;
2213   for (unsigned I = 0; I != NumResults; ++I) {
2214     if (Results[I].Kind != Result::RK_Declaration)
2215       continue;
2216     
2217     unsigned IDNS
2218       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2219
2220     bool Hiding = false;
2221     if (OnlyTagNames)
2222       Hiding = (IDNS & Decl::IDNS_Tag);
2223     else {
2224       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 
2225                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2226                              Decl::IDNS_NonMemberOperator);
2227       if (Ctx.getLangOpts().CPlusPlus)
2228         HiddenIDNS |= Decl::IDNS_Tag;
2229       Hiding = (IDNS & HiddenIDNS);
2230     }
2231   
2232     if (!Hiding)
2233       continue;
2234     
2235     DeclarationName Name = Results[I].Declaration->getDeclName();
2236     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2237       HiddenNames.insert(Identifier->getName());
2238     else
2239       HiddenNames.insert(Name.getAsString());
2240   }
2241 }
2242
2243 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2244                                             CodeCompletionContext Context,
2245                                             CodeCompletionResult *Results,
2246                                             unsigned NumResults) { 
2247   // Merge the results we were given with the results we cached.
2248   bool AddedResult = false;
2249   uint64_t InContexts =
2250       Context.getKind() == CodeCompletionContext::CCC_Recovery
2251         ? NormalContexts : (1LL << Context.getKind());
2252   // Contains the set of names that are hidden by "local" completion results.
2253   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2254   typedef CodeCompletionResult Result;
2255   SmallVector<Result, 8> AllResults;
2256   for (ASTUnit::cached_completion_iterator 
2257             C = AST.cached_completion_begin(),
2258          CEnd = AST.cached_completion_end();
2259        C != CEnd; ++C) {
2260     // If the context we are in matches any of the contexts we are 
2261     // interested in, we'll add this result.
2262     if ((C->ShowInContexts & InContexts) == 0)
2263       continue;
2264     
2265     // If we haven't added any results previously, do so now.
2266     if (!AddedResult) {
2267       CalculateHiddenNames(Context, Results, NumResults, S.Context, 
2268                            HiddenNames);
2269       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2270       AddedResult = true;
2271     }
2272     
2273     // Determine whether this global completion result is hidden by a local
2274     // completion result. If so, skip it.
2275     if (C->Kind != CXCursor_MacroDefinition &&
2276         HiddenNames.count(C->Completion->getTypedText()))
2277       continue;
2278     
2279     // Adjust priority based on similar type classes.
2280     unsigned Priority = C->Priority;
2281     CodeCompletionString *Completion = C->Completion;
2282     if (!Context.getPreferredType().isNull()) {
2283       if (C->Kind == CXCursor_MacroDefinition) {
2284         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2285                                          S.getLangOpts(),
2286                                Context.getPreferredType()->isAnyPointerType());        
2287       } else if (C->Type) {
2288         CanQualType Expected
2289           = S.Context.getCanonicalType(
2290                                Context.getPreferredType().getUnqualifiedType());
2291         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2292         if (ExpectedSTC == C->TypeClass) {
2293           // We know this type is similar; check for an exact match.
2294           llvm::StringMap<unsigned> &CachedCompletionTypes
2295             = AST.getCachedCompletionTypes();
2296           llvm::StringMap<unsigned>::iterator Pos
2297             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2298           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2299             Priority /= CCF_ExactTypeMatch;
2300           else
2301             Priority /= CCF_SimilarTypeMatch;
2302         }
2303       }
2304     }
2305     
2306     // Adjust the completion string, if required.
2307     if (C->Kind == CXCursor_MacroDefinition &&
2308         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2309       // Create a new code-completion string that just contains the
2310       // macro name, without its arguments.
2311       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2312                                     CCP_CodePattern, C->Availability);
2313       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2314       Priority = CCP_CodePattern;
2315       Completion = Builder.TakeString();
2316     }
2317     
2318     AllResults.push_back(Result(Completion, Priority, C->Kind,
2319                                 C->Availability));
2320   }
2321   
2322   // If we did not add any cached completion results, just forward the
2323   // results we were given to the next consumer.
2324   if (!AddedResult) {
2325     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2326     return;
2327   }
2328   
2329   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2330                                   AllResults.size());
2331 }
2332
2333 void ASTUnit::CodeComplete(
2334     StringRef File, unsigned Line, unsigned Column,
2335     ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2336     bool IncludeCodePatterns, bool IncludeBriefComments,
2337     CodeCompleteConsumer &Consumer,
2338     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2339     DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2340     FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2341     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2342   if (!Invocation)
2343     return;
2344
2345   SimpleTimer CompletionTimer(WantTiming);
2346   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2347                             Twine(Line) + ":" + Twine(Column));
2348
2349   auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2350
2351   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2352   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2353   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2354
2355   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2356                                    CachedCompletionResults.empty();
2357   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2358   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2359   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2360
2361   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2362
2363   FrontendOpts.CodeCompletionAt.FileName = File;
2364   FrontendOpts.CodeCompletionAt.Line = Line;
2365   FrontendOpts.CodeCompletionAt.Column = Column;
2366
2367   // Set the language options appropriately.
2368   LangOpts = *CCInvocation->getLangOpts();
2369
2370   // Spell-checking and warnings are wasteful during code-completion.
2371   LangOpts.SpellChecking = false;
2372   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2373
2374   std::unique_ptr<CompilerInstance> Clang(
2375       new CompilerInstance(PCHContainerOps));
2376
2377   // Recover resources if we crash before exiting this method.
2378   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2379     CICleanup(Clang.get());
2380
2381   auto &Inv = *CCInvocation;
2382   Clang->setInvocation(std::move(CCInvocation));
2383   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2384     
2385   // Set up diagnostics, capturing any diagnostics produced.
2386   Clang->setDiagnostics(&Diag);
2387   CaptureDroppedDiagnostics Capture(true, 
2388                                     Clang->getDiagnostics(), 
2389                                     StoredDiagnostics);
2390   ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2391
2392   // Create the target instance.
2393   Clang->setTarget(TargetInfo::CreateTargetInfo(
2394       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2395   if (!Clang->hasTarget()) {
2396     Clang->setInvocation(nullptr);
2397     return;
2398   }
2399   
2400   // Inform the target of the language options.
2401   //
2402   // FIXME: We shouldn't need to do this, the target should be immutable once
2403   // created. This complexity should be lifted elsewhere.
2404   Clang->getTarget().adjust(Clang->getLangOpts());
2405   
2406   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2407          "Invocation must have exactly one source file!");
2408   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2409              InputKind::Source &&
2410          "FIXME: AST inputs not yet supported here!");
2411   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2412              InputKind::LLVM_IR &&
2413          "IR inputs not support here!");
2414   
2415   // Use the source and file managers that we were given.
2416   Clang->setFileManager(&FileMgr);
2417   Clang->setSourceManager(&SourceMgr);
2418
2419   // Remap files.
2420   PreprocessorOpts.clearRemappedFiles();
2421   PreprocessorOpts.RetainRemappedFileBuffers = true;
2422   for (const auto &RemappedFile : RemappedFiles) {
2423     PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2424     OwnedBuffers.push_back(RemappedFile.second);
2425   }
2426
2427   // Use the code completion consumer we were given, but adding any cached
2428   // code-completion results.
2429   AugmentedCodeCompleteConsumer *AugmentedConsumer
2430     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2431   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2432
2433   // If we have a precompiled preamble, try to use it. We only allow
2434   // the use of the precompiled preamble if we're if the completion
2435   // point is within the main file, after the end of the precompiled
2436   // preamble.
2437   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2438   if (!getPreambleFile(this).empty()) {
2439     std::string CompleteFilePath(File);
2440     llvm::sys::fs::UniqueID CompleteFileID;
2441
2442     if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2443       std::string MainPath(OriginalSourceFile);
2444       llvm::sys::fs::UniqueID MainID;
2445       if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2446         if (CompleteFileID == MainID && Line > 1)
2447           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2448               PCHContainerOps, Inv, false, Line - 1);
2449       }
2450     }
2451   }
2452
2453   // If the main file has been overridden due to the use of a preamble,
2454   // make that override happen and introduce the preamble.
2455   if (OverrideMainBuffer) {
2456     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2457                                      OverrideMainBuffer.get());
2458     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2459     PreprocessorOpts.PrecompiledPreambleBytes.second
2460                                                     = PreambleEndsAtStartOfLine;
2461     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2462     PreprocessorOpts.DisablePCHValidation = true;
2463
2464     OwnedBuffers.push_back(OverrideMainBuffer.release());
2465   } else {
2466     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2467     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2468   }
2469
2470   // Disable the preprocessing record if modules are not enabled.
2471   if (!Clang->getLangOpts().Modules)
2472     PreprocessorOpts.DetailedRecord = false;
2473
2474   std::unique_ptr<SyntaxOnlyAction> Act;
2475   Act.reset(new SyntaxOnlyAction);
2476   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2477     Act->Execute();
2478     Act->EndSourceFile();
2479   }
2480 }
2481
2482 bool ASTUnit::Save(StringRef File) {
2483   if (HadModuleLoaderFatalFailure)
2484     return true;
2485
2486   // Write to a temporary file and later rename it to the actual file, to avoid
2487   // possible race conditions.
2488   SmallString<128> TempPath;
2489   TempPath = File;
2490   TempPath += "-%%%%%%%%";
2491   int fd;
2492   if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2493     return true;
2494
2495   // FIXME: Can we somehow regenerate the stat cache here, or do we need to 
2496   // unconditionally create a stat cache when we parse the file?
2497   llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2498
2499   serialize(Out);
2500   Out.close();
2501   if (Out.has_error()) {
2502     Out.clear_error();
2503     return true;
2504   }
2505
2506   if (llvm::sys::fs::rename(TempPath, File)) {
2507     llvm::sys::fs::remove(TempPath);
2508     return true;
2509   }
2510
2511   return false;
2512 }
2513
2514 static bool serializeUnit(ASTWriter &Writer,
2515                           SmallVectorImpl<char> &Buffer,
2516                           Sema &S,
2517                           bool hasErrors,
2518                           raw_ostream &OS) {
2519   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2520
2521   // Write the generated bitstream to "Out".
2522   if (!Buffer.empty())
2523     OS.write(Buffer.data(), Buffer.size());
2524
2525   return false;
2526 }
2527
2528 bool ASTUnit::serialize(raw_ostream &OS) {
2529   // For serialization we are lenient if the errors were only warn-as-error kind.
2530   bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2531
2532   if (WriterData)
2533     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2534                          getSema(), hasErrors, OS);
2535
2536   SmallString<128> Buffer;
2537   llvm::BitstreamWriter Stream(Buffer);
2538   MemoryBufferCache PCMCache;
2539   ASTWriter Writer(Stream, Buffer, PCMCache, {});
2540   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2541 }
2542
2543 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2544
2545 void ASTUnit::TranslateStoredDiagnostics(
2546                           FileManager &FileMgr,
2547                           SourceManager &SrcMgr,
2548                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2549                           SmallVectorImpl<StoredDiagnostic> &Out) {
2550   // Map the standalone diagnostic into the new source manager. We also need to
2551   // remap all the locations to the new view. This includes the diag location,
2552   // any associated source ranges, and the source ranges of associated fix-its.
2553   // FIXME: There should be a cleaner way to do this.
2554
2555   SmallVector<StoredDiagnostic, 4> Result;
2556   Result.reserve(Diags.size());
2557   const FileEntry *PreviousFE = nullptr;
2558   FileID FID;
2559   for (const StandaloneDiagnostic &SD : Diags) {
2560     // Rebuild the StoredDiagnostic.
2561     if (SD.Filename.empty())
2562       continue;
2563     const FileEntry *FE = FileMgr.getFile(SD.Filename);
2564     if (!FE)
2565       continue;
2566     if (FE != PreviousFE) {
2567       FID = SrcMgr.translateFile(FE);
2568       PreviousFE = FE;
2569     }
2570     SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2571     if (FileLoc.isInvalid())
2572       continue;
2573     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2574     FullSourceLoc Loc(L, SrcMgr);
2575
2576     SmallVector<CharSourceRange, 4> Ranges;
2577     Ranges.reserve(SD.Ranges.size());
2578     for (const auto &Range : SD.Ranges) {
2579       SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2580       SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2581       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2582     }
2583
2584     SmallVector<FixItHint, 2> FixIts;
2585     FixIts.reserve(SD.FixIts.size());
2586     for (const StandaloneFixIt &FixIt : SD.FixIts) {
2587       FixIts.push_back(FixItHint());
2588       FixItHint &FH = FixIts.back();
2589       FH.CodeToInsert = FixIt.CodeToInsert;
2590       SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2591       SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2592       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2593     }
2594
2595     Result.push_back(StoredDiagnostic(SD.Level, SD.ID, 
2596                                       SD.Message, Loc, Ranges, FixIts));
2597   }
2598   Result.swap(Out);
2599 }
2600
2601 void ASTUnit::addFileLevelDecl(Decl *D) {
2602   assert(D);
2603   
2604   // We only care about local declarations.
2605   if (D->isFromASTFile())
2606     return;
2607
2608   SourceManager &SM = *SourceMgr;
2609   SourceLocation Loc = D->getLocation();
2610   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2611     return;
2612
2613   // We only keep track of the file-level declarations of each file.
2614   if (!D->getLexicalDeclContext()->isFileContext())
2615     return;
2616
2617   SourceLocation FileLoc = SM.getFileLoc(Loc);
2618   assert(SM.isLocalSourceLocation(FileLoc));
2619   FileID FID;
2620   unsigned Offset;
2621   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2622   if (FID.isInvalid())
2623     return;
2624
2625   LocDeclsTy *&Decls = FileDecls[FID];
2626   if (!Decls)
2627     Decls = new LocDeclsTy();
2628
2629   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2630
2631   if (Decls->empty() || Decls->back().first <= Offset) {
2632     Decls->push_back(LocDecl);
2633     return;
2634   }
2635
2636   LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2637                                             LocDecl, llvm::less_first());
2638
2639   Decls->insert(I, LocDecl);
2640 }
2641
2642 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2643                                   SmallVectorImpl<Decl *> &Decls) {
2644   if (File.isInvalid())
2645     return;
2646
2647   if (SourceMgr->isLoadedFileID(File)) {
2648     assert(Ctx->getExternalSource() && "No external source!");
2649     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2650                                                          Decls);
2651   }
2652
2653   FileDeclsTy::iterator I = FileDecls.find(File);
2654   if (I == FileDecls.end())
2655     return;
2656
2657   LocDeclsTy &LocDecls = *I->second;
2658   if (LocDecls.empty())
2659     return;
2660
2661   LocDeclsTy::iterator BeginIt =
2662       std::lower_bound(LocDecls.begin(), LocDecls.end(),
2663                        std::make_pair(Offset, (Decl *)nullptr),
2664                        llvm::less_first());
2665   if (BeginIt != LocDecls.begin())
2666     --BeginIt;
2667
2668   // If we are pointing at a top-level decl inside an objc container, we need
2669   // to backtrack until we find it otherwise we will fail to report that the
2670   // region overlaps with an objc container.
2671   while (BeginIt != LocDecls.begin() &&
2672          BeginIt->second->isTopLevelDeclInObjCContainer())
2673     --BeginIt;
2674
2675   LocDeclsTy::iterator EndIt = std::upper_bound(
2676       LocDecls.begin(), LocDecls.end(),
2677       std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2678   if (EndIt != LocDecls.end())
2679     ++EndIt;
2680   
2681   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2682     Decls.push_back(DIt->second);
2683 }
2684
2685 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2686                                     unsigned Line, unsigned Col) const {
2687   const SourceManager &SM = getSourceManager();
2688   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2689   return SM.getMacroArgExpandedLocation(Loc);
2690 }
2691
2692 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2693                                     unsigned Offset) const {
2694   const SourceManager &SM = getSourceManager();
2695   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2696   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2697 }
2698
2699 /// \brief If \arg Loc is a loaded location from the preamble, returns
2700 /// the corresponding local location of the main file, otherwise it returns
2701 /// \arg Loc.
2702 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2703   FileID PreambleID;
2704   if (SourceMgr)
2705     PreambleID = SourceMgr->getPreambleFileID();
2706
2707   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2708     return Loc;
2709
2710   unsigned Offs;
2711   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2712     SourceLocation FileLoc
2713         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2714     return FileLoc.getLocWithOffset(Offs);
2715   }
2716
2717   return Loc;
2718 }
2719
2720 /// \brief If \arg Loc is a local location of the main file but inside the
2721 /// preamble chunk, returns the corresponding loaded location from the
2722 /// preamble, otherwise it returns \arg Loc.
2723 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2724   FileID PreambleID;
2725   if (SourceMgr)
2726     PreambleID = SourceMgr->getPreambleFileID();
2727
2728   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2729     return Loc;
2730
2731   unsigned Offs;
2732   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2733       Offs < Preamble.size()) {
2734     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2735     return FileLoc.getLocWithOffset(Offs);
2736   }
2737
2738   return Loc;
2739 }
2740
2741 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2742   FileID FID;
2743   if (SourceMgr)
2744     FID = SourceMgr->getPreambleFileID();
2745   
2746   if (Loc.isInvalid() || FID.isInvalid())
2747     return false;
2748   
2749   return SourceMgr->isInFileID(Loc, FID);
2750 }
2751
2752 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2753   FileID FID;
2754   if (SourceMgr)
2755     FID = SourceMgr->getMainFileID();
2756   
2757   if (Loc.isInvalid() || FID.isInvalid())
2758     return false;
2759   
2760   return SourceMgr->isInFileID(Loc, FID);
2761 }
2762
2763 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2764   FileID FID;
2765   if (SourceMgr)
2766     FID = SourceMgr->getPreambleFileID();
2767   
2768   if (FID.isInvalid())
2769     return SourceLocation();
2770
2771   return SourceMgr->getLocForEndOfFile(FID);
2772 }
2773
2774 SourceLocation ASTUnit::getStartOfMainFileID() {
2775   FileID FID;
2776   if (SourceMgr)
2777     FID = SourceMgr->getMainFileID();
2778   
2779   if (FID.isInvalid())
2780     return SourceLocation();
2781   
2782   return SourceMgr->getLocForStartOfFile(FID);
2783 }
2784
2785 llvm::iterator_range<PreprocessingRecord::iterator>
2786 ASTUnit::getLocalPreprocessingEntities() const {
2787   if (isMainFileAST()) {
2788     serialization::ModuleFile &
2789       Mod = Reader->getModuleManager().getPrimaryModule();
2790     return Reader->getModulePreprocessedEntities(Mod);
2791   }
2792
2793   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2794     return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2795
2796   return llvm::make_range(PreprocessingRecord::iterator(),
2797                           PreprocessingRecord::iterator());
2798 }
2799
2800 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2801   if (isMainFileAST()) {
2802     serialization::ModuleFile &
2803       Mod = Reader->getModuleManager().getPrimaryModule();
2804     for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2805       if (!Fn(context, D))
2806         return false;
2807     }
2808
2809     return true;
2810   }
2811
2812   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2813                                 TLEnd = top_level_end();
2814          TL != TLEnd; ++TL) {
2815     if (!Fn(context, *TL))
2816       return false;
2817   }
2818
2819   return true;
2820 }
2821
2822 const FileEntry *ASTUnit::getPCHFile() {
2823   if (!Reader)
2824     return nullptr;
2825
2826   serialization::ModuleFile *Mod = nullptr;
2827   Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2828     switch (M.Kind) {
2829     case serialization::MK_ImplicitModule:
2830     case serialization::MK_ExplicitModule:
2831     case serialization::MK_PrebuiltModule:
2832       return true; // skip dependencies.
2833     case serialization::MK_PCH:
2834       Mod = &M;
2835       return true; // found it.
2836     case serialization::MK_Preamble:
2837       return false; // look in dependencies.
2838     case serialization::MK_MainFile:
2839       return false; // look in dependencies.
2840     }
2841
2842     return true;
2843   });
2844   if (Mod)
2845     return Mod->File;
2846
2847   return nullptr;
2848 }
2849
2850 bool ASTUnit::isModuleFile() {
2851   return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2852 }
2853
2854 void ASTUnit::PreambleData::countLines() const {
2855   NumLines = 0;
2856   if (empty())
2857     return;
2858
2859   NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2860
2861   if (Buffer.back() != '\n')
2862     ++NumLines;
2863 }
2864
2865 #ifndef NDEBUG
2866 ASTUnit::ConcurrencyState::ConcurrencyState() {
2867   Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2868 }
2869
2870 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2871   delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2872 }
2873
2874 void ASTUnit::ConcurrencyState::start() {
2875   bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2876   assert(acquired && "Concurrent access to ASTUnit!");
2877 }
2878
2879 void ASTUnit::ConcurrencyState::finish() {
2880   static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2881 }
2882
2883 #else // NDEBUG
2884
2885 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2886 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2887 void ASTUnit::ConcurrencyState::start() {}
2888 void ASTUnit::ConcurrencyState::finish() {}
2889
2890 #endif // NDEBUG