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