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