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