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