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