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