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