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