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