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