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