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