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