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