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   std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1279   uint64_t MainFileID;
1280   if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1281     // Check whether there is a file-file remapping of the main file
1282     for (PreprocessorOptions::remapped_file_iterator
1283           M = PreprocessorOpts.remapped_file_begin(),
1284           E = PreprocessorOpts.remapped_file_end();
1285          M != E;
1286          ++M) {
1287       std::string MPath(M->first);
1288       uint64_t MID;
1289       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1290         if (MainFileID == MID) {
1291           // We found a remapping. Try to load the resulting, remapped source.
1292           if (CreatedBuffer) {
1293             delete Buffer;
1294             CreatedBuffer = false;
1295           }
1296 
1297           Buffer = getBufferForFile(M->second);
1298           if (!Buffer)
1299             return std::make_pair((llvm::MemoryBuffer*)0,
1300                                   std::make_pair(0, true));
1301           CreatedBuffer = true;
1302         }
1303       }
1304     }
1305 
1306     // Check whether there is a file-buffer remapping. It supercedes the
1307     // file-file remapping.
1308     for (PreprocessorOptions::remapped_file_buffer_iterator
1309            M = PreprocessorOpts.remapped_file_buffer_begin(),
1310            E = PreprocessorOpts.remapped_file_buffer_end();
1311          M != E;
1312          ++M) {
1313       std::string MPath(M->first);
1314       uint64_t MID;
1315       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1316         if (MainFileID == MID) {
1317           // We found a remapping.
1318           if (CreatedBuffer) {
1319             delete Buffer;
1320             CreatedBuffer = false;
1321           }
1322 
1323           Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
1324         }
1325       }
1326     }
1327   }
1328 
1329   // If the main source file was not remapped, load it now.
1330   if (!Buffer) {
1331     Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1332     if (!Buffer)
1333       return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
1334 
1335     CreatedBuffer = true;
1336   }
1337 
1338   return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1339                                                        *Invocation.getLangOpts(),
1340                                                        MaxLines));
1341 }
1342 
1343 static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
1344                                                       unsigned NewSize,
1345                                                       StringRef NewName) {
1346   llvm::MemoryBuffer *Result
1347     = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1348   memcpy(const_cast<char*>(Result->getBufferStart()),
1349          Old->getBufferStart(), Old->getBufferSize());
1350   memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
1351          ' ', NewSize - Old->getBufferSize() - 1);
1352   const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
1353 
1354   return Result;
1355 }
1356 
1357 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1358 /// the source file.
1359 ///
1360 /// This routine will compute the preamble of the main source file. If a
1361 /// non-trivial preamble is found, it will precompile that preamble into a
1362 /// precompiled header so that the precompiled preamble can be used to reduce
1363 /// reparsing time. If a precompiled preamble has already been constructed,
1364 /// this routine will determine if it is still valid and, if so, avoid
1365 /// rebuilding the precompiled preamble.
1366 ///
1367 /// \param AllowRebuild When true (the default), this routine is
1368 /// allowed to rebuild the precompiled preamble if it is found to be
1369 /// out-of-date.
1370 ///
1371 /// \param MaxLines When non-zero, the maximum number of lines that
1372 /// can occur within the preamble.
1373 ///
1374 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1375 /// buffer that should be used in place of the main file when doing so.
1376 /// Otherwise, returns a NULL pointer.
1377 llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
1378                               const CompilerInvocation &PreambleInvocationIn,
1379                                                            bool AllowRebuild,
1380                                                            unsigned MaxLines) {
1381 
1382   IntrusiveRefCntPtr<CompilerInvocation>
1383     PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1384   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1385   PreprocessorOptions &PreprocessorOpts
1386     = PreambleInvocation->getPreprocessorOpts();
1387 
1388   bool CreatedPreambleBuffer = false;
1389   std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
1390     = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
1391 
1392   // If ComputePreamble() Take ownership of the preamble buffer.
1393   OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1394   if (CreatedPreambleBuffer)
1395     OwnedPreambleBuffer.reset(NewPreamble.first);
1396 
1397   if (!NewPreamble.second.first) {
1398     // We couldn't find a preamble in the main source. Clear out the current
1399     // preamble, if we have one. It's obviously no good any more.
1400     Preamble.clear();
1401     erasePreambleFile(this);
1402 
1403     // The next time we actually see a preamble, precompile it.
1404     PreambleRebuildCounter = 1;
1405     return 0;
1406   }
1407 
1408   if (!Preamble.empty()) {
1409     // We've previously computed a preamble. Check whether we have the same
1410     // preamble now that we did before, and that there's enough space in
1411     // the main-file buffer within the precompiled preamble to fit the
1412     // new main file.
1413     if (Preamble.size() == NewPreamble.second.first &&
1414         PreambleEndsAtStartOfLine == NewPreamble.second.second &&
1415         NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
1416         memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
1417                NewPreamble.second.first) == 0) {
1418       // The preamble has not changed. We may be able to re-use the precompiled
1419       // preamble.
1420 
1421       // Check that none of the files used by the preamble have changed.
1422       bool AnyFileChanged = false;
1423 
1424       // First, make a record of those files that have been overridden via
1425       // remapping or unsaved_files.
1426       llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1427       for (PreprocessorOptions::remapped_file_iterator
1428                 R = PreprocessorOpts.remapped_file_begin(),
1429              REnd = PreprocessorOpts.remapped_file_end();
1430            !AnyFileChanged && R != REnd;
1431            ++R) {
1432         struct stat StatBuf;
1433         if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
1434           // If we can't stat the file we're remapping to, assume that something
1435           // horrible happened.
1436           AnyFileChanged = true;
1437           break;
1438         }
1439 
1440         OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1441                                                    StatBuf.st_mtime);
1442       }
1443       for (PreprocessorOptions::remapped_file_buffer_iterator
1444                 R = PreprocessorOpts.remapped_file_buffer_begin(),
1445              REnd = PreprocessorOpts.remapped_file_buffer_end();
1446            !AnyFileChanged && R != REnd;
1447            ++R) {
1448         // FIXME: Should we actually compare the contents of file->buffer
1449         // remappings?
1450         OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1451                                                    0);
1452       }
1453 
1454       // Check whether anything has changed.
1455       for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1456              F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1457            !AnyFileChanged && F != FEnd;
1458            ++F) {
1459         llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1460           = OverriddenFiles.find(F->first());
1461         if (Overridden != OverriddenFiles.end()) {
1462           // This file was remapped; check whether the newly-mapped file
1463           // matches up with the previous mapping.
1464           if (Overridden->second != F->second)
1465             AnyFileChanged = true;
1466           continue;
1467         }
1468 
1469         // The file was not remapped; check whether it has changed on disk.
1470         struct stat StatBuf;
1471         if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
1472           // If we can't stat the file, assume that something horrible happened.
1473           AnyFileChanged = true;
1474         } else if (StatBuf.st_size != F->second.first ||
1475                    StatBuf.st_mtime != F->second.second)
1476           AnyFileChanged = true;
1477       }
1478 
1479       if (!AnyFileChanged) {
1480         // Okay! We can re-use the precompiled preamble.
1481 
1482         // Set the state of the diagnostic object to mimic its state
1483         // after parsing the preamble.
1484         getDiagnostics().Reset();
1485         ProcessWarningOptions(getDiagnostics(),
1486                               PreambleInvocation->getDiagnosticOpts());
1487         getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1488 
1489         // Create a version of the main file buffer that is padded to
1490         // buffer size we reserved when creating the preamble.
1491         return CreatePaddedMainFileBuffer(NewPreamble.first,
1492                                           PreambleReservedSize,
1493                                           FrontendOpts.Inputs[0].getFile());
1494       }
1495     }
1496 
1497     // If we aren't allowed to rebuild the precompiled preamble, just
1498     // return now.
1499     if (!AllowRebuild)
1500       return 0;
1501 
1502     // We can't reuse the previously-computed preamble. Build a new one.
1503     Preamble.clear();
1504     PreambleDiagnostics.clear();
1505     erasePreambleFile(this);
1506     PreambleRebuildCounter = 1;
1507   } else if (!AllowRebuild) {
1508     // We aren't allowed to rebuild the precompiled preamble; just
1509     // return now.
1510     return 0;
1511   }
1512 
1513   // If the preamble rebuild counter > 1, it's because we previously
1514   // failed to build a preamble and we're not yet ready to try
1515   // again. Decrement the counter and return a failure.
1516   if (PreambleRebuildCounter > 1) {
1517     --PreambleRebuildCounter;
1518     return 0;
1519   }
1520 
1521   // Create a temporary file for the precompiled preamble. In rare
1522   // circumstances, this can fail.
1523   std::string PreamblePCHPath = GetPreamblePCHPath();
1524   if (PreamblePCHPath.empty()) {
1525     // Try again next time.
1526     PreambleRebuildCounter = 1;
1527     return 0;
1528   }
1529 
1530   // We did not previously compute a preamble, or it can't be reused anyway.
1531   SimpleTimer PreambleTimer(WantTiming);
1532   PreambleTimer.setOutput("Precompiling preamble");
1533 
1534   // Create a new buffer that stores the preamble. The buffer also contains
1535   // extra space for the original contents of the file (which will be present
1536   // when we actually parse the file) along with more room in case the file
1537   // grows.
1538   PreambleReservedSize = NewPreamble.first->getBufferSize();
1539   if (PreambleReservedSize < 4096)
1540     PreambleReservedSize = 8191;
1541   else
1542     PreambleReservedSize *= 2;
1543 
1544   // Save the preamble text for later; we'll need to compare against it for
1545   // subsequent reparses.
1546   StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
1547   Preamble.assign(FileMgr->getFile(MainFilename),
1548                   NewPreamble.first->getBufferStart(),
1549                   NewPreamble.first->getBufferStart()
1550                                                   + NewPreamble.second.first);
1551   PreambleEndsAtStartOfLine = NewPreamble.second.second;
1552 
1553   delete PreambleBuffer;
1554   PreambleBuffer
1555     = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
1556                                                 FrontendOpts.Inputs[0].getFile());
1557   memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
1558          NewPreamble.first->getBufferStart(), Preamble.size());
1559   memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
1560          ' ', PreambleReservedSize - Preamble.size() - 1);
1561   const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
1562 
1563   // Remap the main source file to the preamble buffer.
1564   llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
1565   PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1566 
1567   // Tell the compiler invocation to generate a temporary precompiled header.
1568   FrontendOpts.ProgramAction = frontend::GeneratePCH;
1569   // FIXME: Generate the precompiled header into memory?
1570   FrontendOpts.OutputFile = PreamblePCHPath;
1571   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1572   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1573 
1574   // Create the compiler instance to use for building the precompiled preamble.
1575   OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1576 
1577   // Recover resources if we crash before exiting this method.
1578   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1579     CICleanup(Clang.get());
1580 
1581   Clang->setInvocation(&*PreambleInvocation);
1582   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1583 
1584   // Set up diagnostics, capturing all of the diagnostics produced.
1585   Clang->setDiagnostics(&getDiagnostics());
1586 
1587   // Create the target instance.
1588   Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1589                                                 &Clang->getTargetOpts()));
1590   if (!Clang->hasTarget()) {
1591     llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1592     Preamble.clear();
1593     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1594     PreprocessorOpts.eraseRemappedFile(
1595                                PreprocessorOpts.remapped_file_buffer_end() - 1);
1596     return 0;
1597   }
1598 
1599   // Inform the target of the language options.
1600   //
1601   // FIXME: We shouldn't need to do this, the target should be immutable once
1602   // created. This complexity should be lifted elsewhere.
1603   Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1604 
1605   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1606          "Invocation must have exactly one source file!");
1607   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1608          "FIXME: AST inputs not yet supported here!");
1609   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1610          "IR inputs not support here!");
1611 
1612   // Clear out old caches and data.
1613   getDiagnostics().Reset();
1614   ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1615   checkAndRemoveNonDriverDiags(StoredDiagnostics);
1616   TopLevelDecls.clear();
1617   TopLevelDeclsInPreamble.clear();
1618 
1619   // Create a file manager object to provide access to and cache the filesystem.
1620   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
1621 
1622   // Create the source manager.
1623   Clang->setSourceManager(new SourceManager(getDiagnostics(),
1624                                             Clang->getFileManager()));
1625 
1626   OwningPtr<PrecompilePreambleAction> Act;
1627   Act.reset(new PrecompilePreambleAction(*this));
1628   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1629     llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1630     Preamble.clear();
1631     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1632     PreprocessorOpts.eraseRemappedFile(
1633                                PreprocessorOpts.remapped_file_buffer_end() - 1);
1634     return 0;
1635   }
1636 
1637   Act->Execute();
1638   Act->EndSourceFile();
1639 
1640   if (!Act->hasEmittedPreamblePCH()) {
1641     // The preamble PCH failed (e.g. there was a module loading fatal error),
1642     // so no precompiled header was generated. Forget that we even tried.
1643     // FIXME: Should we leave a note for ourselves to try again?
1644     llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1645     Preamble.clear();
1646     TopLevelDeclsInPreamble.clear();
1647     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1648     PreprocessorOpts.eraseRemappedFile(
1649                                PreprocessorOpts.remapped_file_buffer_end() - 1);
1650     return 0;
1651   }
1652 
1653   // Transfer any diagnostics generated when parsing the preamble into the set
1654   // of preamble diagnostics.
1655   PreambleDiagnostics.clear();
1656   PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1657                             stored_diag_afterDriver_begin(), stored_diag_end());
1658   checkAndRemoveNonDriverDiags(StoredDiagnostics);
1659 
1660   // Keep track of the preamble we precompiled.
1661   setPreambleFile(this, FrontendOpts.OutputFile);
1662   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1663 
1664   // Keep track of all of the files that the source manager knows about,
1665   // so we can verify whether they have changed or not.
1666   FilesInPreamble.clear();
1667   SourceManager &SourceMgr = Clang->getSourceManager();
1668   const llvm::MemoryBuffer *MainFileBuffer
1669     = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1670   for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1671                                      FEnd = SourceMgr.fileinfo_end();
1672        F != FEnd;
1673        ++F) {
1674     const FileEntry *File = F->second->OrigEntry;
1675     if (!File || F->second->getRawBuffer() == MainFileBuffer)
1676       continue;
1677 
1678     FilesInPreamble[File->getName()]
1679       = std::make_pair(F->second->getSize(), File->getModificationTime());
1680   }
1681 
1682   PreambleRebuildCounter = 1;
1683   PreprocessorOpts.eraseRemappedFile(
1684                                PreprocessorOpts.remapped_file_buffer_end() - 1);
1685 
1686   // If the hash of top-level entities differs from the hash of the top-level
1687   // entities the last time we rebuilt the preamble, clear out the completion
1688   // cache.
1689   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1690     CompletionCacheTopLevelHashValue = 0;
1691     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1692   }
1693 
1694   return CreatePaddedMainFileBuffer(NewPreamble.first,
1695                                     PreambleReservedSize,
1696                                     FrontendOpts.Inputs[0].getFile());
1697 }
1698 
1699 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1700   std::vector<Decl *> Resolved;
1701   Resolved.reserve(TopLevelDeclsInPreamble.size());
1702   ExternalASTSource &Source = *getASTContext().getExternalSource();
1703   for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1704     // Resolve the declaration ID to an actual declaration, possibly
1705     // deserializing the declaration in the process.
1706     Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1707     if (D)
1708       Resolved.push_back(D);
1709   }
1710   TopLevelDeclsInPreamble.clear();
1711   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1712 }
1713 
1714 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1715   // Steal the created target, context, and preprocessor.
1716   TheSema.reset(CI.takeSema());
1717   Consumer.reset(CI.takeASTConsumer());
1718   Ctx = &CI.getASTContext();
1719   PP = &CI.getPreprocessor();
1720   CI.setSourceManager(0);
1721   CI.setFileManager(0);
1722   Target = &CI.getTarget();
1723   Reader = CI.getModuleManager();
1724   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1725 }
1726 
1727 StringRef ASTUnit::getMainFileName() const {
1728   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1729     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1730     if (Input.isFile())
1731       return Input.getFile();
1732     else
1733       return Input.getBuffer()->getBufferIdentifier();
1734   }
1735 
1736   if (SourceMgr) {
1737     if (const FileEntry *
1738           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1739       return FE->getName();
1740   }
1741 
1742   return StringRef();
1743 }
1744 
1745 StringRef ASTUnit::getASTFileName() const {
1746   if (!isMainFileAST())
1747     return StringRef();
1748 
1749   serialization::ModuleFile &
1750     Mod = Reader->getModuleManager().getPrimaryModule();
1751   return Mod.FileName;
1752 }
1753 
1754 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1755                          IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1756                          bool CaptureDiagnostics,
1757                          bool UserFilesAreVolatile) {
1758   OwningPtr<ASTUnit> AST;
1759   AST.reset(new ASTUnit(false));
1760   ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1761   AST->Diagnostics = Diags;
1762   AST->Invocation = CI;
1763   AST->FileSystemOpts = CI->getFileSystemOpts();
1764   AST->FileMgr = new FileManager(AST->FileSystemOpts);
1765   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1766   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1767                                      UserFilesAreVolatile);
1768 
1769   return AST.take();
1770 }
1771 
1772 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1773                               IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1774                                              ASTFrontendAction *Action,
1775                                              ASTUnit *Unit,
1776                                              bool Persistent,
1777                                              StringRef ResourceFilesPath,
1778                                              bool OnlyLocalDecls,
1779                                              bool CaptureDiagnostics,
1780                                              bool PrecompilePreamble,
1781                                              bool CacheCodeCompletionResults,
1782                                     bool IncludeBriefCommentsInCodeCompletion,
1783                                              bool UserFilesAreVolatile,
1784                                              OwningPtr<ASTUnit> *ErrAST) {
1785   assert(CI && "A CompilerInvocation is required");
1786 
1787   OwningPtr<ASTUnit> OwnAST;
1788   ASTUnit *AST = Unit;
1789   if (!AST) {
1790     // Create the AST unit.
1791     OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1792     AST = OwnAST.get();
1793   }
1794 
1795   if (!ResourceFilesPath.empty()) {
1796     // Override the resources path.
1797     CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1798   }
1799   AST->OnlyLocalDecls = OnlyLocalDecls;
1800   AST->CaptureDiagnostics = CaptureDiagnostics;
1801   if (PrecompilePreamble)
1802     AST->PreambleRebuildCounter = 2;
1803   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1804   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1805   AST->IncludeBriefCommentsInCodeCompletion
1806     = IncludeBriefCommentsInCodeCompletion;
1807 
1808   // Recover resources if we crash before exiting this method.
1809   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1810     ASTUnitCleanup(OwnAST.get());
1811   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1812     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1813     DiagCleanup(Diags.getPtr());
1814 
1815   // We'll manage file buffers ourselves.
1816   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1817   CI->getFrontendOpts().DisableFree = false;
1818   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1819 
1820   // Create the compiler instance to use for building the AST.
1821   OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1822 
1823   // Recover resources if we crash before exiting this method.
1824   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1825     CICleanup(Clang.get());
1826 
1827   Clang->setInvocation(CI);
1828   AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1829 
1830   // Set up diagnostics, capturing any diagnostics that would
1831   // otherwise be dropped.
1832   Clang->setDiagnostics(&AST->getDiagnostics());
1833 
1834   // Create the target instance.
1835   Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1836                                                 &Clang->getTargetOpts()));
1837   if (!Clang->hasTarget())
1838     return 0;
1839 
1840   // Inform the target of the language options.
1841   //
1842   // FIXME: We shouldn't need to do this, the target should be immutable once
1843   // created. This complexity should be lifted elsewhere.
1844   Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1845 
1846   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1847          "Invocation must have exactly one source file!");
1848   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1849          "FIXME: AST inputs not yet supported here!");
1850   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1851          "IR inputs not supported here!");
1852 
1853   // Configure the various subsystems.
1854   AST->TheSema.reset();
1855   AST->Ctx = 0;
1856   AST->PP = 0;
1857   AST->Reader = 0;
1858 
1859   // Create a file manager object to provide access to and cache the filesystem.
1860   Clang->setFileManager(&AST->getFileManager());
1861 
1862   // Create the source manager.
1863   Clang->setSourceManager(&AST->getSourceManager());
1864 
1865   ASTFrontendAction *Act = Action;
1866 
1867   OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1868   if (!Act) {
1869     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1870     Act = TrackerAct.get();
1871   }
1872 
1873   // Recover resources if we crash before exiting this method.
1874   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1875     ActCleanup(TrackerAct.get());
1876 
1877   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1878     AST->transferASTDataFromCompilerInstance(*Clang);
1879     if (OwnAST && ErrAST)
1880       ErrAST->swap(OwnAST);
1881 
1882     return 0;
1883   }
1884 
1885   if (Persistent && !TrackerAct) {
1886     Clang->getPreprocessor().addPPCallbacks(
1887      new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1888     std::vector<ASTConsumer*> Consumers;
1889     if (Clang->hasASTConsumer())
1890       Consumers.push_back(Clang->takeASTConsumer());
1891     Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1892                                            AST->getCurrentTopLevelHashValue()));
1893     Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1894   }
1895   if (!Act->Execute()) {
1896     AST->transferASTDataFromCompilerInstance(*Clang);
1897     if (OwnAST && ErrAST)
1898       ErrAST->swap(OwnAST);
1899 
1900     return 0;
1901   }
1902 
1903   // Steal the created target, context, and preprocessor.
1904   AST->transferASTDataFromCompilerInstance(*Clang);
1905 
1906   Act->EndSourceFile();
1907 
1908   if (OwnAST)
1909     return OwnAST.take();
1910   else
1911     return AST;
1912 }
1913 
1914 bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1915   if (!Invocation)
1916     return true;
1917 
1918   // We'll manage file buffers ourselves.
1919   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1920   Invocation->getFrontendOpts().DisableFree = false;
1921   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1922 
1923   llvm::MemoryBuffer *OverrideMainBuffer = 0;
1924   if (PrecompilePreamble) {
1925     PreambleRebuildCounter = 2;
1926     OverrideMainBuffer
1927       = getMainBufferWithPrecompiledPreamble(*Invocation);
1928   }
1929 
1930   SimpleTimer ParsingTimer(WantTiming);
1931   ParsingTimer.setOutput("Parsing " + getMainFileName());
1932 
1933   // Recover resources if we crash before exiting this method.
1934   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1935     MemBufferCleanup(OverrideMainBuffer);
1936 
1937   return Parse(OverrideMainBuffer);
1938 }
1939 
1940 ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1941                               IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1942                                              bool OnlyLocalDecls,
1943                                              bool CaptureDiagnostics,
1944                                              bool PrecompilePreamble,
1945                                              TranslationUnitKind TUKind,
1946                                              bool CacheCodeCompletionResults,
1947                                     bool IncludeBriefCommentsInCodeCompletion,
1948                                              bool UserFilesAreVolatile) {
1949   // Create the AST unit.
1950   OwningPtr<ASTUnit> AST;
1951   AST.reset(new ASTUnit(false));
1952   ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1953   AST->Diagnostics = Diags;
1954   AST->OnlyLocalDecls = OnlyLocalDecls;
1955   AST->CaptureDiagnostics = CaptureDiagnostics;
1956   AST->TUKind = TUKind;
1957   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1958   AST->IncludeBriefCommentsInCodeCompletion
1959     = IncludeBriefCommentsInCodeCompletion;
1960   AST->Invocation = CI;
1961   AST->FileSystemOpts = CI->getFileSystemOpts();
1962   AST->FileMgr = new FileManager(AST->FileSystemOpts);
1963   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1964 
1965   // Recover resources if we crash before exiting this method.
1966   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1967     ASTUnitCleanup(AST.get());
1968   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1969     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1970     DiagCleanup(Diags.getPtr());
1971 
1972   return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
1973 }
1974 
1975 ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1976                                       const char **ArgEnd,
1977                                     IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1978                                       StringRef ResourceFilesPath,
1979                                       bool OnlyLocalDecls,
1980                                       bool CaptureDiagnostics,
1981                                       RemappedFile *RemappedFiles,
1982                                       unsigned NumRemappedFiles,
1983                                       bool RemappedFilesKeepOriginalName,
1984                                       bool PrecompilePreamble,
1985                                       TranslationUnitKind TUKind,
1986                                       bool CacheCodeCompletionResults,
1987                                       bool IncludeBriefCommentsInCodeCompletion,
1988                                       bool AllowPCHWithCompilerErrors,
1989                                       bool SkipFunctionBodies,
1990                                       bool UserFilesAreVolatile,
1991                                       bool ForSerialization,
1992                                       OwningPtr<ASTUnit> *ErrAST) {
1993   if (!Diags.getPtr()) {
1994     // No diagnostics engine was provided, so create our own diagnostics object
1995     // with the default options.
1996     Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
1997   }
1998 
1999   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
2000 
2001   IntrusiveRefCntPtr<CompilerInvocation> CI;
2002 
2003   {
2004 
2005     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
2006                                       StoredDiagnostics);
2007 
2008     CI = clang::createInvocationFromCommandLine(
2009                                            llvm::makeArrayRef(ArgBegin, ArgEnd),
2010                                            Diags);
2011     if (!CI)
2012       return 0;
2013   }
2014 
2015   // Override any files that need remapping
2016   for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2017     FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2018     if (const llvm::MemoryBuffer *
2019             memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2020       CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2021     } else {
2022       const char *fname = fileOrBuf.get<const char *>();
2023       CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2024     }
2025   }
2026   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2027   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2028   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
2029 
2030   // Override the resources path.
2031   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
2032 
2033   CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2034 
2035   // Create the AST unit.
2036   OwningPtr<ASTUnit> AST;
2037   AST.reset(new ASTUnit(false));
2038   ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
2039   AST->Diagnostics = Diags;
2040   Diags = 0; // Zero out now to ease cleanup during crash recovery.
2041   AST->FileSystemOpts = CI->getFileSystemOpts();
2042   AST->FileMgr = new FileManager(AST->FileSystemOpts);
2043   AST->OnlyLocalDecls = OnlyLocalDecls;
2044   AST->CaptureDiagnostics = CaptureDiagnostics;
2045   AST->TUKind = TUKind;
2046   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2047   AST->IncludeBriefCommentsInCodeCompletion
2048     = IncludeBriefCommentsInCodeCompletion;
2049   AST->UserFilesAreVolatile = UserFilesAreVolatile;
2050   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2051   AST->StoredDiagnostics.swap(StoredDiagnostics);
2052   AST->Invocation = CI;
2053   if (ForSerialization)
2054     AST->WriterData.reset(new ASTWriterData());
2055   CI = 0; // Zero out now to ease cleanup during crash recovery.
2056 
2057   // Recover resources if we crash before exiting this method.
2058   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2059     ASTUnitCleanup(AST.get());
2060 
2061   if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2062     // Some error occurred, if caller wants to examine diagnostics, pass it the
2063     // ASTUnit.
2064     if (ErrAST) {
2065       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2066       ErrAST->swap(AST);
2067     }
2068     return 0;
2069   }
2070 
2071   return AST.take();
2072 }
2073 
2074 bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
2075   if (!Invocation)
2076     return true;
2077 
2078   clearFileLevelDecls();
2079 
2080   SimpleTimer ParsingTimer(WantTiming);
2081   ParsingTimer.setOutput("Reparsing " + getMainFileName());
2082 
2083   // Remap files.
2084   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2085   for (PreprocessorOptions::remapped_file_buffer_iterator
2086          R = PPOpts.remapped_file_buffer_begin(),
2087          REnd = PPOpts.remapped_file_buffer_end();
2088        R != REnd;
2089        ++R) {
2090     delete R->second;
2091   }
2092   Invocation->getPreprocessorOpts().clearRemappedFiles();
2093   for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2094     FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2095     if (const llvm::MemoryBuffer *
2096             memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2097       Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2098                                                         memBuf);
2099     } else {
2100       const char *fname = fileOrBuf.get<const char *>();
2101       Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2102                                                         fname);
2103     }
2104   }
2105 
2106   // If we have a preamble file lying around, or if we might try to
2107   // build a precompiled preamble, do so now.
2108   llvm::MemoryBuffer *OverrideMainBuffer = 0;
2109   if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2110     OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
2111 
2112   // Clear out the diagnostics state.
2113   getDiagnostics().Reset();
2114   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2115   if (OverrideMainBuffer)
2116     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2117 
2118   // Parse the sources
2119   bool Result = Parse(OverrideMainBuffer);
2120 
2121   // If we're caching global code-completion results, and the top-level
2122   // declarations have changed, clear out the code-completion cache.
2123   if (!Result && ShouldCacheCodeCompletionResults &&
2124       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2125     CacheCodeCompletionResults();
2126 
2127   // We now need to clear out the completion info related to this translation
2128   // unit; it'll be recreated if necessary.
2129   CCTUInfo.reset();
2130 
2131   return Result;
2132 }
2133 
2134 //----------------------------------------------------------------------------//
2135 // Code completion
2136 //----------------------------------------------------------------------------//
2137 
2138 namespace {
2139   /// \brief Code completion consumer that combines the cached code-completion
2140   /// results from an ASTUnit with the code-completion results provided to it,
2141   /// then passes the result on to
2142   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2143     uint64_t NormalContexts;
2144     ASTUnit &AST;
2145     CodeCompleteConsumer &Next;
2146 
2147   public:
2148     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2149                                   const CodeCompleteOptions &CodeCompleteOpts)
2150       : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2151         AST(AST), Next(Next)
2152     {
2153       // Compute the set of contexts in which we will look when we don't have
2154       // any information about the specific context.
2155       NormalContexts
2156         = (1LL << CodeCompletionContext::CCC_TopLevel)
2157         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2158         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2159         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2160         | (1LL << CodeCompletionContext::CCC_Statement)
2161         | (1LL << CodeCompletionContext::CCC_Expression)
2162         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2163         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2164         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2165         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2166         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2167         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2168         | (1LL << CodeCompletionContext::CCC_Recovery);
2169 
2170       if (AST.getASTContext().getLangOpts().CPlusPlus)
2171         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2172                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
2173                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2174     }
2175 
2176     virtual void ProcessCodeCompleteResults(Sema &S,
2177                                             CodeCompletionContext Context,
2178                                             CodeCompletionResult *Results,
2179                                             unsigned NumResults);
2180 
2181     virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2182                                            OverloadCandidate *Candidates,
2183                                            unsigned NumCandidates) {
2184       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2185     }
2186 
2187     virtual CodeCompletionAllocator &getAllocator() {
2188       return Next.getAllocator();
2189     }
2190 
2191     virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2192       return Next.getCodeCompletionTUInfo();
2193     }
2194   };
2195 }
2196 
2197 /// \brief Helper function that computes which global names are hidden by the
2198 /// local code-completion results.
2199 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2200                                  CodeCompletionResult *Results,
2201                                  unsigned NumResults,
2202                                  ASTContext &Ctx,
2203                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2204   bool OnlyTagNames = false;
2205   switch (Context.getKind()) {
2206   case CodeCompletionContext::CCC_Recovery:
2207   case CodeCompletionContext::CCC_TopLevel:
2208   case CodeCompletionContext::CCC_ObjCInterface:
2209   case CodeCompletionContext::CCC_ObjCImplementation:
2210   case CodeCompletionContext::CCC_ObjCIvarList:
2211   case CodeCompletionContext::CCC_ClassStructUnion:
2212   case CodeCompletionContext::CCC_Statement:
2213   case CodeCompletionContext::CCC_Expression:
2214   case CodeCompletionContext::CCC_ObjCMessageReceiver:
2215   case CodeCompletionContext::CCC_DotMemberAccess:
2216   case CodeCompletionContext::CCC_ArrowMemberAccess:
2217   case CodeCompletionContext::CCC_ObjCPropertyAccess:
2218   case CodeCompletionContext::CCC_Namespace:
2219   case CodeCompletionContext::CCC_Type:
2220   case CodeCompletionContext::CCC_Name:
2221   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2222   case CodeCompletionContext::CCC_ParenthesizedExpression:
2223   case CodeCompletionContext::CCC_ObjCInterfaceName:
2224     break;
2225 
2226   case CodeCompletionContext::CCC_EnumTag:
2227   case CodeCompletionContext::CCC_UnionTag:
2228   case CodeCompletionContext::CCC_ClassOrStructTag:
2229     OnlyTagNames = true;
2230     break;
2231 
2232   case CodeCompletionContext::CCC_ObjCProtocolName:
2233   case CodeCompletionContext::CCC_MacroName:
2234   case CodeCompletionContext::CCC_MacroNameUse:
2235   case CodeCompletionContext::CCC_PreprocessorExpression:
2236   case CodeCompletionContext::CCC_PreprocessorDirective:
2237   case CodeCompletionContext::CCC_NaturalLanguage:
2238   case CodeCompletionContext::CCC_SelectorName:
2239   case CodeCompletionContext::CCC_TypeQualifiers:
2240   case CodeCompletionContext::CCC_Other:
2241   case CodeCompletionContext::CCC_OtherWithMacros:
2242   case CodeCompletionContext::CCC_ObjCInstanceMessage:
2243   case CodeCompletionContext::CCC_ObjCClassMessage:
2244   case CodeCompletionContext::CCC_ObjCCategoryName:
2245     // We're looking for nothing, or we're looking for names that cannot
2246     // be hidden.
2247     return;
2248   }
2249 
2250   typedef CodeCompletionResult Result;
2251   for (unsigned I = 0; I != NumResults; ++I) {
2252     if (Results[I].Kind != Result::RK_Declaration)
2253       continue;
2254 
2255     unsigned IDNS
2256       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2257 
2258     bool Hiding = false;
2259     if (OnlyTagNames)
2260       Hiding = (IDNS & Decl::IDNS_Tag);
2261     else {
2262       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2263                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2264                              Decl::IDNS_NonMemberOperator);
2265       if (Ctx.getLangOpts().CPlusPlus)
2266         HiddenIDNS |= Decl::IDNS_Tag;
2267       Hiding = (IDNS & HiddenIDNS);
2268     }
2269 
2270     if (!Hiding)
2271       continue;
2272 
2273     DeclarationName Name = Results[I].Declaration->getDeclName();
2274     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2275       HiddenNames.insert(Identifier->getName());
2276     else
2277       HiddenNames.insert(Name.getAsString());
2278   }
2279 }
2280 
2281 
2282 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2283                                             CodeCompletionContext Context,
2284                                             CodeCompletionResult *Results,
2285                                             unsigned NumResults) {
2286   // Merge the results we were given with the results we cached.
2287   bool AddedResult = false;
2288   uint64_t InContexts =
2289       Context.getKind() == CodeCompletionContext::CCC_Recovery
2290         ? NormalContexts : (1LL << Context.getKind());
2291   // Contains the set of names that are hidden by "local" completion results.
2292   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2293   typedef CodeCompletionResult Result;
2294   SmallVector<Result, 8> AllResults;
2295   for (ASTUnit::cached_completion_iterator
2296             C = AST.cached_completion_begin(),
2297          CEnd = AST.cached_completion_end();
2298        C != CEnd; ++C) {
2299     // If the context we are in matches any of the contexts we are
2300     // interested in, we'll add this result.
2301     if ((C->ShowInContexts & InContexts) == 0)
2302       continue;
2303 
2304     // If we haven't added any results previously, do so now.
2305     if (!AddedResult) {
2306       CalculateHiddenNames(Context, Results, NumResults, S.Context,
2307                            HiddenNames);
2308       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2309       AddedResult = true;
2310     }
2311 
2312     // Determine whether this global completion result is hidden by a local
2313     // completion result. If so, skip it.
2314     if (C->Kind != CXCursor_MacroDefinition &&
2315         HiddenNames.count(C->Completion->getTypedText()))
2316       continue;
2317 
2318     // Adjust priority based on similar type classes.
2319     unsigned Priority = C->Priority;
2320     CodeCompletionString *Completion = C->Completion;
2321     if (!Context.getPreferredType().isNull()) {
2322       if (C->Kind == CXCursor_MacroDefinition) {
2323         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2324                                          S.getLangOpts(),
2325                                Context.getPreferredType()->isAnyPointerType());
2326       } else if (C->Type) {
2327         CanQualType Expected
2328           = S.Context.getCanonicalType(
2329                                Context.getPreferredType().getUnqualifiedType());
2330         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2331         if (ExpectedSTC == C->TypeClass) {
2332           // We know this type is similar; check for an exact match.
2333           llvm::StringMap<unsigned> &CachedCompletionTypes
2334             = AST.getCachedCompletionTypes();
2335           llvm::StringMap<unsigned>::iterator Pos
2336             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2337           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2338             Priority /= CCF_ExactTypeMatch;
2339           else
2340             Priority /= CCF_SimilarTypeMatch;
2341         }
2342       }
2343     }
2344 
2345     // Adjust the completion string, if required.
2346     if (C->Kind == CXCursor_MacroDefinition &&
2347         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2348       // Create a new code-completion string that just contains the
2349       // macro name, without its arguments.
2350       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2351                                     CCP_CodePattern, C->Availability);
2352       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2353       Priority = CCP_CodePattern;
2354       Completion = Builder.TakeString();
2355     }
2356 
2357     AllResults.push_back(Result(Completion, Priority, C->Kind,
2358                                 C->Availability));
2359   }
2360 
2361   // If we did not add any cached completion results, just forward the
2362   // results we were given to the next consumer.
2363   if (!AddedResult) {
2364     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2365     return;
2366   }
2367 
2368   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2369                                   AllResults.size());
2370 }
2371 
2372 
2373 
2374 void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2375                            RemappedFile *RemappedFiles,
2376                            unsigned NumRemappedFiles,
2377                            bool IncludeMacros,
2378                            bool IncludeCodePatterns,
2379                            bool IncludeBriefComments,
2380                            CodeCompleteConsumer &Consumer,
2381                            DiagnosticsEngine &Diag, LangOptions &LangOpts,
2382                            SourceManager &SourceMgr, FileManager &FileMgr,
2383                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2384              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2385   if (!Invocation)
2386     return;
2387 
2388   SimpleTimer CompletionTimer(WantTiming);
2389   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2390                             Twine(Line) + ":" + Twine(Column));
2391 
2392   IntrusiveRefCntPtr<CompilerInvocation>
2393     CCInvocation(new CompilerInvocation(*Invocation));
2394 
2395   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2396   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2397   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2398 
2399   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2400                                    CachedCompletionResults.empty();
2401   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2402   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2403   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2404 
2405   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2406 
2407   FrontendOpts.CodeCompletionAt.FileName = File;
2408   FrontendOpts.CodeCompletionAt.Line = Line;
2409   FrontendOpts.CodeCompletionAt.Column = Column;
2410 
2411   // Set the language options appropriately.
2412   LangOpts = *CCInvocation->getLangOpts();
2413 
2414   OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2415 
2416   // Recover resources if we crash before exiting this method.
2417   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2418     CICleanup(Clang.get());
2419 
2420   Clang->setInvocation(&*CCInvocation);
2421   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2422 
2423   // Set up diagnostics, capturing any diagnostics produced.
2424   Clang->setDiagnostics(&Diag);
2425   ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2426   CaptureDroppedDiagnostics Capture(true,
2427                                     Clang->getDiagnostics(),
2428                                     StoredDiagnostics);
2429 
2430   // Create the target instance.
2431   Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2432                                                 &Clang->getTargetOpts()));
2433   if (!Clang->hasTarget()) {
2434     Clang->setInvocation(0);
2435     return;
2436   }
2437 
2438   // Inform the target of the language options.
2439   //
2440   // FIXME: We shouldn't need to do this, the target should be immutable once
2441   // created. This complexity should be lifted elsewhere.
2442   Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
2443 
2444   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2445          "Invocation must have exactly one source file!");
2446   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2447          "FIXME: AST inputs not yet supported here!");
2448   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2449          "IR inputs not support here!");
2450 
2451 
2452   // Use the source and file managers that we were given.
2453   Clang->setFileManager(&FileMgr);
2454   Clang->setSourceManager(&SourceMgr);
2455 
2456   // Remap files.
2457   PreprocessorOpts.clearRemappedFiles();
2458   PreprocessorOpts.RetainRemappedFileBuffers = true;
2459   for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2460     FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2461     if (const llvm::MemoryBuffer *
2462             memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2463       PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2464       OwnedBuffers.push_back(memBuf);
2465     } else {
2466       const char *fname = fileOrBuf.get<const char *>();
2467       PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2468     }
2469   }
2470 
2471   // Use the code completion consumer we were given, but adding any cached
2472   // code-completion results.
2473   AugmentedCodeCompleteConsumer *AugmentedConsumer
2474     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2475   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2476 
2477   // If we have a precompiled preamble, try to use it. We only allow
2478   // the use of the precompiled preamble if we're if the completion
2479   // point is within the main file, after the end of the precompiled
2480   // preamble.
2481   llvm::MemoryBuffer *OverrideMainBuffer = 0;
2482   if (!getPreambleFile(this).empty()) {
2483     using llvm::sys::FileStatus;
2484     std::string CompleteFilePath(File);
2485     uint64_t CompleteFileID;
2486 
2487     if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2488       std::string MainPath(OriginalSourceFile);
2489       uint64_t MainID;
2490       if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2491         if (CompleteFileID == MainID && Line > 1)
2492           OverrideMainBuffer
2493             = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
2494                                                    Line - 1);
2495       }
2496     }
2497   }
2498 
2499   // If the main file has been overridden due to the use of a preamble,
2500   // make that override happen and introduce the preamble.
2501   if (OverrideMainBuffer) {
2502     PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2503     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2504     PreprocessorOpts.PrecompiledPreambleBytes.second
2505                                                     = PreambleEndsAtStartOfLine;
2506     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2507     PreprocessorOpts.DisablePCHValidation = true;
2508 
2509     OwnedBuffers.push_back(OverrideMainBuffer);
2510   } else {
2511     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2512     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2513   }
2514 
2515   // Disable the preprocessing record if modules are not enabled.
2516   if (!Clang->getLangOpts().Modules)
2517     PreprocessorOpts.DetailedRecord = false;
2518 
2519   OwningPtr<SyntaxOnlyAction> Act;
2520   Act.reset(new SyntaxOnlyAction);
2521   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2522     Act->Execute();
2523     Act->EndSourceFile();
2524   }
2525 }
2526 
2527 bool ASTUnit::Save(StringRef File) {
2528   if (HadModuleLoaderFatalFailure)
2529     return true;
2530 
2531   // Write to a temporary file and later rename it to the actual file, to avoid
2532   // possible race conditions.
2533   SmallString<128> TempPath;
2534   TempPath = File;
2535   TempPath += "-%%%%%%%%";
2536   int fd;
2537   if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2538                                  /*makeAbsolute=*/false))
2539     return true;
2540 
2541   // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2542   // unconditionally create a stat cache when we parse the file?
2543   llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2544 
2545   serialize(Out);
2546   Out.close();
2547   if (Out.has_error()) {
2548     Out.clear_error();
2549     return true;
2550   }
2551 
2552   if (llvm::sys::fs::rename(TempPath.str(), File)) {
2553     bool exists;
2554     llvm::sys::fs::remove(TempPath.str(), exists);
2555     return true;
2556   }
2557 
2558   return false;
2559 }
2560 
2561 static bool serializeUnit(ASTWriter &Writer,
2562                           SmallVectorImpl<char> &Buffer,
2563                           Sema &S,
2564                           bool hasErrors,
2565                           raw_ostream &OS) {
2566   Writer.WriteAST(S, std::string(), 0, "", hasErrors);
2567 
2568   // Write the generated bitstream to "Out".
2569   if (!Buffer.empty())
2570     OS.write(Buffer.data(), Buffer.size());
2571 
2572   return false;
2573 }
2574 
2575 bool ASTUnit::serialize(raw_ostream &OS) {
2576   bool hasErrors = getDiagnostics().hasErrorOccurred();
2577 
2578   if (WriterData)
2579     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2580                          getSema(), hasErrors, OS);
2581 
2582   SmallString<128> Buffer;
2583   llvm::BitstreamWriter Stream(Buffer);
2584   ASTWriter Writer(Stream);
2585   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2586 }
2587 
2588 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2589 
2590 static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2591   unsigned Raw = L.getRawEncoding();
2592   const unsigned MacroBit = 1U << 31;
2593   L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2594       ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2595 }
2596 
2597 void ASTUnit::TranslateStoredDiagnostics(
2598                           ASTReader *MMan,
2599                           StringRef ModName,
2600                           SourceManager &SrcMgr,
2601                           const SmallVectorImpl<StoredDiagnostic> &Diags,
2602                           SmallVectorImpl<StoredDiagnostic> &Out) {
2603   // The stored diagnostic has the old source manager in it; update
2604   // the locations to refer into the new source manager. We also need to remap
2605   // all the locations to the new view. This includes the diag location, any
2606   // associated source ranges, and the source ranges of associated fix-its.
2607   // FIXME: There should be a cleaner way to do this.
2608 
2609   SmallVector<StoredDiagnostic, 4> Result;
2610   Result.reserve(Diags.size());
2611   assert(MMan && "Don't have a module manager");
2612   serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
2613   assert(Mod && "Don't have preamble module");
2614   SLocRemap &Remap = Mod->SLocRemap;
2615   for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2616     // Rebuild the StoredDiagnostic.
2617     const StoredDiagnostic &SD = Diags[I];
2618     SourceLocation L = SD.getLocation();
2619     TranslateSLoc(L, Remap);
2620     FullSourceLoc Loc(L, SrcMgr);
2621 
2622     SmallVector<CharSourceRange, 4> Ranges;
2623     Ranges.reserve(SD.range_size());
2624     for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2625                                           E = SD.range_end();
2626          I != E; ++I) {
2627       SourceLocation BL = I->getBegin();
2628       TranslateSLoc(BL, Remap);
2629       SourceLocation EL = I->getEnd();
2630       TranslateSLoc(EL, Remap);
2631       Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2632     }
2633 
2634     SmallVector<FixItHint, 2> FixIts;
2635     FixIts.reserve(SD.fixit_size());
2636     for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2637                                           E = SD.fixit_end();
2638          I != E; ++I) {
2639       FixIts.push_back(FixItHint());
2640       FixItHint &FH = FixIts.back();
2641       FH.CodeToInsert = I->CodeToInsert;
2642       SourceLocation BL = I->RemoveRange.getBegin();
2643       TranslateSLoc(BL, Remap);
2644       SourceLocation EL = I->RemoveRange.getEnd();
2645       TranslateSLoc(EL, Remap);
2646       FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2647                                        I->RemoveRange.isTokenRange());
2648     }
2649 
2650     Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2651                                       SD.getMessage(), Loc, Ranges, FixIts));
2652   }
2653   Result.swap(Out);
2654 }
2655 
2656 static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2657                                std::pair<unsigned, Decl *> R) {
2658   return L.first < R.first;
2659 }
2660 
2661 void ASTUnit::addFileLevelDecl(Decl *D) {
2662   assert(D);
2663 
2664   // We only care about local declarations.
2665   if (D->isFromASTFile())
2666     return;
2667 
2668   SourceManager &SM = *SourceMgr;
2669   SourceLocation Loc = D->getLocation();
2670   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2671     return;
2672 
2673   // We only keep track of the file-level declarations of each file.
2674   if (!D->getLexicalDeclContext()->isFileContext())
2675     return;
2676 
2677   SourceLocation FileLoc = SM.getFileLoc(Loc);
2678   assert(SM.isLocalSourceLocation(FileLoc));
2679   FileID FID;
2680   unsigned Offset;
2681   llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2682   if (FID.isInvalid())
2683     return;
2684 
2685   LocDeclsTy *&Decls = FileDecls[FID];
2686   if (!Decls)
2687     Decls = new LocDeclsTy();
2688 
2689   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2690 
2691   if (Decls->empty() || Decls->back().first <= Offset) {
2692     Decls->push_back(LocDecl);
2693     return;
2694   }
2695 
2696   LocDeclsTy::iterator
2697     I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2698 
2699   Decls->insert(I, LocDecl);
2700 }
2701 
2702 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2703                                   SmallVectorImpl<Decl *> &Decls) {
2704   if (File.isInvalid())
2705     return;
2706 
2707   if (SourceMgr->isLoadedFileID(File)) {
2708     assert(Ctx->getExternalSource() && "No external source!");
2709     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2710                                                          Decls);
2711   }
2712 
2713   FileDeclsTy::iterator I = FileDecls.find(File);
2714   if (I == FileDecls.end())
2715     return;
2716 
2717   LocDeclsTy &LocDecls = *I->second;
2718   if (LocDecls.empty())
2719     return;
2720 
2721   LocDeclsTy::iterator
2722     BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2723                                std::make_pair(Offset, (Decl*)0), compLocDecl);
2724   if (BeginIt != LocDecls.begin())
2725     --BeginIt;
2726 
2727   // If we are pointing at a top-level decl inside an objc container, we need
2728   // to backtrack until we find it otherwise we will fail to report that the
2729   // region overlaps with an objc container.
2730   while (BeginIt != LocDecls.begin() &&
2731          BeginIt->second->isTopLevelDeclInObjCContainer())
2732     --BeginIt;
2733 
2734   LocDeclsTy::iterator
2735     EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2736                              std::make_pair(Offset+Length, (Decl*)0),
2737                              compLocDecl);
2738   if (EndIt != LocDecls.end())
2739     ++EndIt;
2740 
2741   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2742     Decls.push_back(DIt->second);
2743 }
2744 
2745 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2746                                     unsigned Line, unsigned Col) const {
2747   const SourceManager &SM = getSourceManager();
2748   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2749   return SM.getMacroArgExpandedLocation(Loc);
2750 }
2751 
2752 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2753                                     unsigned Offset) const {
2754   const SourceManager &SM = getSourceManager();
2755   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2756   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2757 }
2758 
2759 /// \brief If \arg Loc is a loaded location from the preamble, returns
2760 /// the corresponding local location of the main file, otherwise it returns
2761 /// \arg Loc.
2762 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2763   FileID PreambleID;
2764   if (SourceMgr)
2765     PreambleID = SourceMgr->getPreambleFileID();
2766 
2767   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2768     return Loc;
2769 
2770   unsigned Offs;
2771   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2772     SourceLocation FileLoc
2773         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2774     return FileLoc.getLocWithOffset(Offs);
2775   }
2776 
2777   return Loc;
2778 }
2779 
2780 /// \brief If \arg Loc is a local location of the main file but inside the
2781 /// preamble chunk, returns the corresponding loaded location from the
2782 /// preamble, otherwise it returns \arg Loc.
2783 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2784   FileID PreambleID;
2785   if (SourceMgr)
2786     PreambleID = SourceMgr->getPreambleFileID();
2787 
2788   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2789     return Loc;
2790 
2791   unsigned Offs;
2792   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2793       Offs < Preamble.size()) {
2794     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2795     return FileLoc.getLocWithOffset(Offs);
2796   }
2797 
2798   return Loc;
2799 }
2800 
2801 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2802   FileID FID;
2803   if (SourceMgr)
2804     FID = SourceMgr->getPreambleFileID();
2805 
2806   if (Loc.isInvalid() || FID.isInvalid())
2807     return false;
2808 
2809   return SourceMgr->isInFileID(Loc, FID);
2810 }
2811 
2812 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2813   FileID FID;
2814   if (SourceMgr)
2815     FID = SourceMgr->getMainFileID();
2816 
2817   if (Loc.isInvalid() || FID.isInvalid())
2818     return false;
2819 
2820   return SourceMgr->isInFileID(Loc, FID);
2821 }
2822 
2823 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2824   FileID FID;
2825   if (SourceMgr)
2826     FID = SourceMgr->getPreambleFileID();
2827 
2828   if (FID.isInvalid())
2829     return SourceLocation();
2830 
2831   return SourceMgr->getLocForEndOfFile(FID);
2832 }
2833 
2834 SourceLocation ASTUnit::getStartOfMainFileID() {
2835   FileID FID;
2836   if (SourceMgr)
2837     FID = SourceMgr->getMainFileID();
2838 
2839   if (FID.isInvalid())
2840     return SourceLocation();
2841 
2842   return SourceMgr->getLocForStartOfFile(FID);
2843 }
2844 
2845 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2846 ASTUnit::getLocalPreprocessingEntities() const {
2847   if (isMainFileAST()) {
2848     serialization::ModuleFile &
2849       Mod = Reader->getModuleManager().getPrimaryModule();
2850     return Reader->getModulePreprocessedEntities(Mod);
2851   }
2852 
2853   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2854     return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2855 
2856   return std::make_pair(PreprocessingRecord::iterator(),
2857                         PreprocessingRecord::iterator());
2858 }
2859 
2860 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2861   if (isMainFileAST()) {
2862     serialization::ModuleFile &
2863       Mod = Reader->getModuleManager().getPrimaryModule();
2864     ASTReader::ModuleDeclIterator MDI, MDE;
2865     llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2866     for (; MDI != MDE; ++MDI) {
2867       if (!Fn(context, *MDI))
2868         return false;
2869     }
2870 
2871     return true;
2872   }
2873 
2874   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2875                                 TLEnd = top_level_end();
2876          TL != TLEnd; ++TL) {
2877     if (!Fn(context, *TL))
2878       return false;
2879   }
2880 
2881   return true;
2882 }
2883 
2884 namespace {
2885 struct PCHLocatorInfo {
2886   serialization::ModuleFile *Mod;
2887   PCHLocatorInfo() : Mod(0) {}
2888 };
2889 }
2890 
2891 static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2892   PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2893   switch (M.Kind) {
2894   case serialization::MK_Module:
2895     return true; // skip dependencies.
2896   case serialization::MK_PCH:
2897     Info.Mod = &M;
2898     return true; // found it.
2899   case serialization::MK_Preamble:
2900     return false; // look in dependencies.
2901   case serialization::MK_MainFile:
2902     return false; // look in dependencies.
2903   }
2904 
2905   return true;
2906 }
2907 
2908 const FileEntry *ASTUnit::getPCHFile() {
2909   if (!Reader)
2910     return 0;
2911 
2912   PCHLocatorInfo Info;
2913   Reader->getModuleManager().visit(PCHLocator, &Info);
2914   if (Info.Mod)
2915     return Info.Mod->File;
2916 
2917   return 0;
2918 }
2919 
2920 bool ASTUnit::isModuleFile() {
2921   return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2922 }
2923 
2924 void ASTUnit::PreambleData::countLines() const {
2925   NumLines = 0;
2926   if (empty())
2927     return;
2928 
2929   for (std::vector<char>::const_iterator
2930          I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2931     if (*I == '\n')
2932       ++NumLines;
2933   }
2934   if (Buffer.back() != '\n')
2935     ++NumLines;
2936 }
2937 
2938 #ifndef NDEBUG
2939 ASTUnit::ConcurrencyState::ConcurrencyState() {
2940   Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2941 }
2942 
2943 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2944   delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2945 }
2946 
2947 void ASTUnit::ConcurrencyState::start() {
2948   bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2949   assert(acquired && "Concurrent access to ASTUnit!");
2950 }
2951 
2952 void ASTUnit::ConcurrencyState::finish() {
2953   static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2954 }
2955 
2956 #else // NDEBUG
2957 
2958 ASTUnit::ConcurrencyState::ConcurrencyState() {}
2959 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2960 void ASTUnit::ConcurrencyState::start() {}
2961 void ASTUnit::ConcurrencyState::finish() {}
2962 
2963 #endif
2964