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