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