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