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