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, ArrayRef<RemappedFile> RemappedFiles,
762     CaptureDiagsKind CaptureDiagnostics, bool AllowASTWithCompilerErrors,
763     bool UserFilesAreVolatile) {
764   std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
765 
766   // Recover resources if we crash before exiting this method.
767   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
768     ASTUnitCleanup(AST.get());
769   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
770     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
771     DiagCleanup(Diags.get());
772 
773   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
774 
775   AST->LangOpts = std::make_shared<LangOptions>();
776   AST->OnlyLocalDecls = OnlyLocalDecls;
777   AST->CaptureDiagnostics = CaptureDiagnostics;
778   AST->Diagnostics = Diags;
779   IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
780       llvm::vfs::getRealFileSystem();
781   AST->FileMgr = new FileManager(FileSystemOpts, VFS);
782   AST->UserFilesAreVolatile = UserFilesAreVolatile;
783   AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
784                                      AST->getFileManager(),
785                                      UserFilesAreVolatile);
786   AST->ModuleCache = new InMemoryModuleCache;
787   AST->HSOpts = std::make_shared<HeaderSearchOptions>();
788   AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormat());
789   AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
790                                          AST->getSourceManager(),
791                                          AST->getDiagnostics(),
792                                          AST->getLangOpts(),
793                                          /*Target=*/nullptr));
794   AST->PPOpts = std::make_shared<PreprocessorOptions>();
795 
796   for (const auto &RemappedFile : RemappedFiles)
797     AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
798 
799   // Gather Info for preprocessor construction later on.
800 
801   HeaderSearch &HeaderInfo = *AST->HeaderInfo;
802   unsigned Counter;
803 
804   AST->PP = std::make_shared<Preprocessor>(
805       AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
806       AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
807       /*IILookup=*/nullptr,
808       /*OwnsHeaderSearch=*/false);
809   Preprocessor &PP = *AST->PP;
810 
811   if (ToLoad >= LoadASTOnly)
812     AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
813                               PP.getIdentifierTable(), PP.getSelectorTable(),
814                               PP.getBuiltinInfo());
815 
816   bool disableValid = false;
817   if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
818     disableValid = true;
819   AST->Reader = new ASTReader(
820       PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
821       /*isysroot=*/"",
822       /*DisableValidation=*/disableValid, AllowASTWithCompilerErrors);
823 
824   AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
825       *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
826       AST->TargetOpts, AST->Target, Counter));
827 
828   // Attach the AST reader to the AST context as an external AST
829   // source, so that declarations will be deserialized from the
830   // AST file as needed.
831   // We need the external source to be set up before we read the AST, because
832   // eagerly-deserialized declarations may use it.
833   if (AST->Ctx)
834     AST->Ctx->setExternalSource(AST->Reader);
835 
836   switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
837                           SourceLocation(), ASTReader::ARR_None)) {
838   case ASTReader::Success:
839     break;
840 
841   case ASTReader::Failure:
842   case ASTReader::Missing:
843   case ASTReader::OutOfDate:
844   case ASTReader::VersionMismatch:
845   case ASTReader::ConfigurationMismatch:
846   case ASTReader::HadErrors:
847     AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
848     return nullptr;
849   }
850 
851   AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
852 
853   PP.setCounterValue(Counter);
854 
855   // Create an AST consumer, even though it isn't used.
856   if (ToLoad >= LoadASTOnly)
857     AST->Consumer.reset(new ASTConsumer);
858 
859   // Create a semantic analysis object and tell the AST reader about it.
860   if (ToLoad >= LoadEverything) {
861     AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
862     AST->TheSema->Initialize();
863     AST->Reader->InitializeSema(*AST->TheSema);
864   }
865 
866   // Tell the diagnostic client that we have started a source file.
867   AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
868 
869   return AST;
870 }
871 
872 /// Add the given macro to the hash of all top-level entities.
873 static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
874   Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
875 }
876 
877 namespace {
878 
879 /// Preprocessor callback class that updates a hash value with the names
880 /// of all macros that have been defined by the translation unit.
881 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
882   unsigned &Hash;
883 
884 public:
885   explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
886 
887   void MacroDefined(const Token &MacroNameTok,
888                     const MacroDirective *MD) override {
889     AddDefinedMacroToHash(MacroNameTok, Hash);
890   }
891 };
892 
893 } // namespace
894 
895 /// Add the given declaration to the hash of all top-level entities.
896 static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
897   if (!D)
898     return;
899 
900   DeclContext *DC = D->getDeclContext();
901   if (!DC)
902     return;
903 
904   if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
905     return;
906 
907   if (const auto *ND = dyn_cast<NamedDecl>(D)) {
908     if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
909       // For an unscoped enum include the enumerators in the hash since they
910       // enter the top-level namespace.
911       if (!EnumD->isScoped()) {
912         for (const auto *EI : EnumD->enumerators()) {
913           if (EI->getIdentifier())
914             Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
915         }
916       }
917     }
918 
919     if (ND->getIdentifier())
920       Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
921     else if (DeclarationName Name = ND->getDeclName()) {
922       std::string NameStr = Name.getAsString();
923       Hash = llvm::djbHash(NameStr, Hash);
924     }
925     return;
926   }
927 
928   if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
929     if (const Module *Mod = ImportD->getImportedModule()) {
930       std::string ModName = Mod->getFullModuleName();
931       Hash = llvm::djbHash(ModName, Hash);
932     }
933     return;
934   }
935 }
936 
937 namespace {
938 
939 class TopLevelDeclTrackerConsumer : public ASTConsumer {
940   ASTUnit &Unit;
941   unsigned &Hash;
942 
943 public:
944   TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
945       : Unit(_Unit), Hash(Hash) {
946     Hash = 0;
947   }
948 
949   void handleTopLevelDecl(Decl *D) {
950     if (!D)
951       return;
952 
953     // FIXME: Currently ObjC method declarations are incorrectly being
954     // reported as top-level declarations, even though their DeclContext
955     // is the containing ObjC @interface/@implementation.  This is a
956     // fundamental problem in the parser right now.
957     if (isa<ObjCMethodDecl>(D))
958       return;
959 
960     AddTopLevelDeclarationToHash(D, Hash);
961     Unit.addTopLevelDecl(D);
962 
963     handleFileLevelDecl(D);
964   }
965 
966   void handleFileLevelDecl(Decl *D) {
967     Unit.addFileLevelDecl(D);
968     if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
969       for (auto *I : NSD->decls())
970         handleFileLevelDecl(I);
971     }
972   }
973 
974   bool HandleTopLevelDecl(DeclGroupRef D) override {
975     for (auto *TopLevelDecl : D)
976       handleTopLevelDecl(TopLevelDecl);
977     return true;
978   }
979 
980   // We're not interested in "interesting" decls.
981   void HandleInterestingDecl(DeclGroupRef) override {}
982 
983   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
984     for (auto *TopLevelDecl : D)
985       handleTopLevelDecl(TopLevelDecl);
986   }
987 
988   ASTMutationListener *GetASTMutationListener() override {
989     return Unit.getASTMutationListener();
990   }
991 
992   ASTDeserializationListener *GetASTDeserializationListener() override {
993     return Unit.getDeserializationListener();
994   }
995 };
996 
997 class TopLevelDeclTrackerAction : public ASTFrontendAction {
998 public:
999   ASTUnit &Unit;
1000 
1001   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
1002                                                  StringRef InFile) override {
1003     CI.getPreprocessor().addPPCallbacks(
1004         std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1005                                            Unit.getCurrentTopLevelHashValue()));
1006     return std::make_unique<TopLevelDeclTrackerConsumer>(
1007         Unit, Unit.getCurrentTopLevelHashValue());
1008   }
1009 
1010 public:
1011   TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1012 
1013   bool hasCodeCompletionSupport() const override { return false; }
1014 
1015   TranslationUnitKind getTranslationUnitKind() override {
1016     return Unit.getTranslationUnitKind();
1017   }
1018 };
1019 
1020 class ASTUnitPreambleCallbacks : public PreambleCallbacks {
1021 public:
1022   unsigned getHash() const { return Hash; }
1023 
1024   std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
1025 
1026   std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1027     return std::move(TopLevelDeclIDs);
1028   }
1029 
1030   void AfterPCHEmitted(ASTWriter &Writer) override {
1031     TopLevelDeclIDs.reserve(TopLevelDecls.size());
1032     for (const auto *D : TopLevelDecls) {
1033       // Invalid top-level decls may not have been serialized.
1034       if (D->isInvalidDecl())
1035         continue;
1036       TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1037     }
1038   }
1039 
1040   void HandleTopLevelDecl(DeclGroupRef DG) override {
1041     for (auto *D : DG) {
1042       // FIXME: Currently ObjC method declarations are incorrectly being
1043       // reported as top-level declarations, even though their DeclContext
1044       // is the containing ObjC @interface/@implementation.  This is a
1045       // fundamental problem in the parser right now.
1046       if (isa<ObjCMethodDecl>(D))
1047         continue;
1048       AddTopLevelDeclarationToHash(D, Hash);
1049       TopLevelDecls.push_back(D);
1050     }
1051   }
1052 
1053   std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1054     return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1055   }
1056 
1057 private:
1058   unsigned Hash = 0;
1059   std::vector<Decl *> TopLevelDecls;
1060   std::vector<serialization::DeclID> TopLevelDeclIDs;
1061   llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
1062 };
1063 
1064 } // namespace
1065 
1066 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1067   return StoredDiag.getLocation().isValid();
1068 }
1069 
1070 static void
1071 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1072   // Get rid of stored diagnostics except the ones from the driver which do not
1073   // have a source location.
1074   StoredDiags.erase(
1075       std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1076       StoredDiags.end());
1077 }
1078 
1079 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1080                                                               StoredDiagnostics,
1081                                   SourceManager &SM) {
1082   // The stored diagnostic has the old source manager in it; update
1083   // the locations to refer into the new source manager. Since we've
1084   // been careful to make sure that the source manager's state
1085   // before and after are identical, so that we can reuse the source
1086   // location itself.
1087   for (auto &SD : StoredDiagnostics) {
1088     if (SD.getLocation().isValid()) {
1089       FullSourceLoc Loc(SD.getLocation(), SM);
1090       SD.setLocation(Loc);
1091     }
1092   }
1093 }
1094 
1095 /// Parse the source file into a translation unit using the given compiler
1096 /// invocation, replacing the current translation unit.
1097 ///
1098 /// \returns True if a failure occurred that causes the ASTUnit not to
1099 /// contain any translation-unit information, false otherwise.
1100 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1101                     std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1102                     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1103   if (!Invocation)
1104     return true;
1105 
1106   if (VFS && FileMgr)
1107     assert(VFS == &FileMgr->getVirtualFileSystem() &&
1108            "VFS passed to Parse and VFS in FileMgr are different");
1109 
1110   auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1111   if (OverrideMainBuffer) {
1112     assert(Preamble &&
1113            "No preamble was built, but OverrideMainBuffer is not null");
1114     Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1115     // VFS may have changed...
1116   }
1117 
1118   // Create the compiler instance to use for building the AST.
1119   std::unique_ptr<CompilerInstance> Clang(
1120       new CompilerInstance(std::move(PCHContainerOps)));
1121 
1122   // Clean up on error, disengage it if the function returns successfully.
1123   auto CleanOnError = llvm::make_scope_exit([&]() {
1124     // Remove the overridden buffer we used for the preamble.
1125     SavedMainFileBuffer = nullptr;
1126 
1127     // Keep the ownership of the data in the ASTUnit because the client may
1128     // want to see the diagnostics.
1129     transferASTDataFromCompilerInstance(*Clang);
1130     FailedParseDiagnostics.swap(StoredDiagnostics);
1131     StoredDiagnostics.clear();
1132     NumStoredDiagnosticsFromDriver = 0;
1133   });
1134 
1135   // Ensure that Clang has a FileManager with the right VFS, which may have
1136   // changed above in AddImplicitPreamble.  If VFS is nullptr, rely on
1137   // createFileManager to create one.
1138   if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
1139     Clang->setFileManager(&*FileMgr);
1140   else
1141     FileMgr = Clang->createFileManager(std::move(VFS));
1142 
1143   // Recover resources if we crash before exiting this method.
1144   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1145     CICleanup(Clang.get());
1146 
1147   Clang->setInvocation(CCInvocation);
1148   OriginalSourceFile =
1149       std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1150 
1151   // Set up diagnostics, capturing any diagnostics that would
1152   // otherwise be dropped.
1153   Clang->setDiagnostics(&getDiagnostics());
1154 
1155   // Create the target instance.
1156   Clang->setTarget(TargetInfo::CreateTargetInfo(
1157       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1158   if (!Clang->hasTarget())
1159     return true;
1160 
1161   // Inform the target of the language options.
1162   //
1163   // FIXME: We shouldn't need to do this, the target should be immutable once
1164   // created. This complexity should be lifted elsewhere.
1165   Clang->getTarget().adjust(Clang->getLangOpts());
1166 
1167   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1168          "Invocation must have exactly one source file!");
1169   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1170              InputKind::Source &&
1171          "FIXME: AST inputs not yet supported here!");
1172   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1173              Language::LLVM_IR &&
1174          "IR inputs not support here!");
1175 
1176   // Configure the various subsystems.
1177   LangOpts = Clang->getInvocation().LangOpts;
1178   FileSystemOpts = Clang->getFileSystemOpts();
1179 
1180   ResetForParse();
1181 
1182   SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1183                                 UserFilesAreVolatile);
1184   if (!OverrideMainBuffer) {
1185     checkAndRemoveNonDriverDiags(StoredDiagnostics);
1186     TopLevelDeclsInPreamble.clear();
1187   }
1188 
1189   // Create a file manager object to provide access to and cache the filesystem.
1190   Clang->setFileManager(&getFileManager());
1191 
1192   // Create the source manager.
1193   Clang->setSourceManager(&getSourceManager());
1194 
1195   // If the main file has been overridden due to the use of a preamble,
1196   // make that override happen and introduce the preamble.
1197   if (OverrideMainBuffer) {
1198     // The stored diagnostic has the old source manager in it; update
1199     // the locations to refer into the new source manager. Since we've
1200     // been careful to make sure that the source manager's state
1201     // before and after are identical, so that we can reuse the source
1202     // location itself.
1203     checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1204 
1205     // Keep track of the override buffer;
1206     SavedMainFileBuffer = std::move(OverrideMainBuffer);
1207   }
1208 
1209   std::unique_ptr<TopLevelDeclTrackerAction> Act(
1210       new TopLevelDeclTrackerAction(*this));
1211 
1212   // Recover resources if we crash before exiting this method.
1213   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1214     ActCleanup(Act.get());
1215 
1216   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1217     return true;
1218 
1219   if (SavedMainFileBuffer)
1220     TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1221                                PreambleDiagnostics, StoredDiagnostics);
1222   else
1223     PreambleSrcLocCache.clear();
1224 
1225   if (llvm::Error Err = Act->Execute()) {
1226     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1227     return true;
1228   }
1229 
1230   transferASTDataFromCompilerInstance(*Clang);
1231 
1232   Act->EndSourceFile();
1233 
1234   FailedParseDiagnostics.clear();
1235 
1236   CleanOnError.release();
1237 
1238   return false;
1239 }
1240 
1241 static std::pair<unsigned, unsigned>
1242 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1243                     const LangOptions &LangOpts) {
1244   CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1245   unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1246   unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1247   return std::make_pair(Offset, EndOffset);
1248 }
1249 
1250 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1251                                                     const LangOptions &LangOpts,
1252                                                     const FixItHint &InFix) {
1253   ASTUnit::StandaloneFixIt OutFix;
1254   OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1255   OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1256                                                LangOpts);
1257   OutFix.CodeToInsert = InFix.CodeToInsert;
1258   OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1259   return OutFix;
1260 }
1261 
1262 static ASTUnit::StandaloneDiagnostic
1263 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1264                          const StoredDiagnostic &InDiag) {
1265   ASTUnit::StandaloneDiagnostic OutDiag;
1266   OutDiag.ID = InDiag.getID();
1267   OutDiag.Level = InDiag.getLevel();
1268   OutDiag.Message = std::string(InDiag.getMessage());
1269   OutDiag.LocOffset = 0;
1270   if (InDiag.getLocation().isInvalid())
1271     return OutDiag;
1272   const SourceManager &SM = InDiag.getLocation().getManager();
1273   SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1274   OutDiag.Filename = std::string(SM.getFilename(FileLoc));
1275   if (OutDiag.Filename.empty())
1276     return OutDiag;
1277   OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1278   for (const auto &Range : InDiag.getRanges())
1279     OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1280   for (const auto &FixIt : InDiag.getFixIts())
1281     OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1282 
1283   return OutDiag;
1284 }
1285 
1286 /// Attempt to build or re-use a precompiled preamble when (re-)parsing
1287 /// the source file.
1288 ///
1289 /// This routine will compute the preamble of the main source file. If a
1290 /// non-trivial preamble is found, it will precompile that preamble into a
1291 /// precompiled header so that the precompiled preamble can be used to reduce
1292 /// reparsing time. If a precompiled preamble has already been constructed,
1293 /// this routine will determine if it is still valid and, if so, avoid
1294 /// rebuilding the precompiled preamble.
1295 ///
1296 /// \param AllowRebuild When true (the default), this routine is
1297 /// allowed to rebuild the precompiled preamble if it is found to be
1298 /// out-of-date.
1299 ///
1300 /// \param MaxLines When non-zero, the maximum number of lines that
1301 /// can occur within the preamble.
1302 ///
1303 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1304 /// buffer that should be used in place of the main file when doing so.
1305 /// Otherwise, returns a NULL pointer.
1306 std::unique_ptr<llvm::MemoryBuffer>
1307 ASTUnit::getMainBufferWithPrecompiledPreamble(
1308     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1309     CompilerInvocation &PreambleInvocationIn,
1310     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
1311     unsigned MaxLines) {
1312   auto MainFilePath =
1313       PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1314   std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1315       getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1316                                         MainFilePath, UserFilesAreVolatile);
1317   if (!MainFileBuffer)
1318     return nullptr;
1319 
1320   PreambleBounds Bounds = ComputePreambleBounds(
1321       *PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
1322   if (!Bounds.Size)
1323     return nullptr;
1324 
1325   if (Preamble) {
1326     if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1327                            VFS.get())) {
1328       // Okay! We can re-use the precompiled preamble.
1329 
1330       // Set the state of the diagnostic object to mimic its state
1331       // after parsing the preamble.
1332       getDiagnostics().Reset();
1333       ProcessWarningOptions(getDiagnostics(),
1334                             PreambleInvocationIn.getDiagnosticOpts());
1335       getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1336 
1337       PreambleRebuildCountdown = 1;
1338       return MainFileBuffer;
1339     } else {
1340       Preamble.reset();
1341       PreambleDiagnostics.clear();
1342       TopLevelDeclsInPreamble.clear();
1343       PreambleSrcLocCache.clear();
1344       PreambleRebuildCountdown = 1;
1345     }
1346   }
1347 
1348   // If the preamble rebuild counter > 1, it's because we previously
1349   // failed to build a preamble and we're not yet ready to try
1350   // again. Decrement the counter and return a failure.
1351   if (PreambleRebuildCountdown > 1) {
1352     --PreambleRebuildCountdown;
1353     return nullptr;
1354   }
1355 
1356   assert(!Preamble && "No Preamble should be stored at that point");
1357   // If we aren't allowed to rebuild the precompiled preamble, just
1358   // return now.
1359   if (!AllowRebuild)
1360     return nullptr;
1361 
1362   ++PreambleCounter;
1363 
1364   SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1365   SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1366   ASTUnitPreambleCallbacks Callbacks;
1367   {
1368     llvm::Optional<CaptureDroppedDiagnostics> Capture;
1369     if (CaptureDiagnostics != CaptureDiagsKind::None)
1370       Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1371                       &NewPreambleDiagsStandalone);
1372 
1373     // We did not previously compute a preamble, or it can't be reused anyway.
1374     SimpleTimer PreambleTimer(WantTiming);
1375     PreambleTimer.setOutput("Precompiling preamble");
1376 
1377     const bool PreviousSkipFunctionBodies =
1378         PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1379     if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1380       PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1381 
1382     llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1383         PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1384         PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
1385 
1386     PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1387         PreviousSkipFunctionBodies;
1388 
1389     if (NewPreamble) {
1390       Preamble = std::move(*NewPreamble);
1391       PreambleRebuildCountdown = 1;
1392     } else {
1393       switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1394       case BuildPreambleError::CouldntCreateTempFile:
1395         // Try again next time.
1396         PreambleRebuildCountdown = 1;
1397         return nullptr;
1398       case BuildPreambleError::CouldntCreateTargetInfo:
1399       case BuildPreambleError::BeginSourceFileFailed:
1400       case BuildPreambleError::CouldntEmitPCH:
1401       case BuildPreambleError::BadInputs:
1402         // These erros are more likely to repeat, retry after some period.
1403         PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
1404         return nullptr;
1405       }
1406       llvm_unreachable("unexpected BuildPreambleError");
1407     }
1408   }
1409 
1410   assert(Preamble && "Preamble wasn't built");
1411 
1412   TopLevelDecls.clear();
1413   TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1414   PreambleTopLevelHashValue = Callbacks.getHash();
1415 
1416   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1417 
1418   checkAndRemoveNonDriverDiags(NewPreambleDiags);
1419   StoredDiagnostics = std::move(NewPreambleDiags);
1420   PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1421 
1422   // If the hash of top-level entities differs from the hash of the top-level
1423   // entities the last time we rebuilt the preamble, clear out the completion
1424   // cache.
1425   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1426     CompletionCacheTopLevelHashValue = 0;
1427     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1428   }
1429 
1430   return MainFileBuffer;
1431 }
1432 
1433 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1434   assert(Preamble && "Should only be called when preamble was built");
1435 
1436   std::vector<Decl *> Resolved;
1437   Resolved.reserve(TopLevelDeclsInPreamble.size());
1438   ExternalASTSource &Source = *getASTContext().getExternalSource();
1439   for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1440     // Resolve the declaration ID to an actual declaration, possibly
1441     // deserializing the declaration in the process.
1442     if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1443       Resolved.push_back(D);
1444   }
1445   TopLevelDeclsInPreamble.clear();
1446   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1447 }
1448 
1449 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1450   // Steal the created target, context, and preprocessor if they have been
1451   // created.
1452   assert(CI.hasInvocation() && "missing invocation");
1453   LangOpts = CI.getInvocation().LangOpts;
1454   TheSema = CI.takeSema();
1455   Consumer = CI.takeASTConsumer();
1456   if (CI.hasASTContext())
1457     Ctx = &CI.getASTContext();
1458   if (CI.hasPreprocessor())
1459     PP = CI.getPreprocessorPtr();
1460   CI.setSourceManager(nullptr);
1461   CI.setFileManager(nullptr);
1462   if (CI.hasTarget())
1463     Target = &CI.getTarget();
1464   Reader = CI.getASTReader();
1465   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1466 }
1467 
1468 StringRef ASTUnit::getMainFileName() const {
1469   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1470     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1471     if (Input.isFile())
1472       return Input.getFile();
1473     else
1474       return Input.getBuffer().getBufferIdentifier();
1475   }
1476 
1477   if (SourceMgr) {
1478     if (const FileEntry *
1479           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1480       return FE->getName();
1481   }
1482 
1483   return {};
1484 }
1485 
1486 StringRef ASTUnit::getASTFileName() const {
1487   if (!isMainFileAST())
1488     return {};
1489 
1490   serialization::ModuleFile &
1491     Mod = Reader->getModuleManager().getPrimaryModule();
1492   return Mod.FileName;
1493 }
1494 
1495 std::unique_ptr<ASTUnit>
1496 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1497                 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1498                 CaptureDiagsKind CaptureDiagnostics,
1499                 bool UserFilesAreVolatile) {
1500   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1501   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1502   IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1503       createVFSFromCompilerInvocation(*CI, *Diags);
1504   AST->Diagnostics = Diags;
1505   AST->FileSystemOpts = CI->getFileSystemOpts();
1506   AST->Invocation = std::move(CI);
1507   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1508   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1509   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1510                                      UserFilesAreVolatile);
1511   AST->ModuleCache = new InMemoryModuleCache;
1512 
1513   return AST;
1514 }
1515 
1516 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1517     std::shared_ptr<CompilerInvocation> CI,
1518     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1519     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1520     ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1521     bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1522     unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1523     bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1524   assert(CI && "A CompilerInvocation is required");
1525 
1526   std::unique_ptr<ASTUnit> OwnAST;
1527   ASTUnit *AST = Unit;
1528   if (!AST) {
1529     // Create the AST unit.
1530     OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1531     AST = OwnAST.get();
1532     if (!AST)
1533       return nullptr;
1534   }
1535 
1536   if (!ResourceFilesPath.empty()) {
1537     // Override the resources path.
1538     CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1539   }
1540   AST->OnlyLocalDecls = OnlyLocalDecls;
1541   AST->CaptureDiagnostics = CaptureDiagnostics;
1542   if (PrecompilePreambleAfterNParses > 0)
1543     AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1544   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1545   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1546   AST->IncludeBriefCommentsInCodeCompletion = false;
1547 
1548   // Recover resources if we crash before exiting this method.
1549   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1550     ASTUnitCleanup(OwnAST.get());
1551   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1552     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1553     DiagCleanup(Diags.get());
1554 
1555   // We'll manage file buffers ourselves.
1556   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1557   CI->getFrontendOpts().DisableFree = false;
1558   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1559 
1560   // Create the compiler instance to use for building the AST.
1561   std::unique_ptr<CompilerInstance> Clang(
1562       new CompilerInstance(std::move(PCHContainerOps)));
1563 
1564   // Recover resources if we crash before exiting this method.
1565   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1566     CICleanup(Clang.get());
1567 
1568   Clang->setInvocation(std::move(CI));
1569   AST->OriginalSourceFile =
1570       std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1571 
1572   // Set up diagnostics, capturing any diagnostics that would
1573   // otherwise be dropped.
1574   Clang->setDiagnostics(&AST->getDiagnostics());
1575 
1576   // Create the target instance.
1577   Clang->setTarget(TargetInfo::CreateTargetInfo(
1578       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1579   if (!Clang->hasTarget())
1580     return nullptr;
1581 
1582   // Inform the target of the language options.
1583   //
1584   // FIXME: We shouldn't need to do this, the target should be immutable once
1585   // created. This complexity should be lifted elsewhere.
1586   Clang->getTarget().adjust(Clang->getLangOpts());
1587 
1588   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1589          "Invocation must have exactly one source file!");
1590   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1591              InputKind::Source &&
1592          "FIXME: AST inputs not yet supported here!");
1593   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1594              Language::LLVM_IR &&
1595          "IR inputs not support here!");
1596 
1597   // Configure the various subsystems.
1598   AST->TheSema.reset();
1599   AST->Ctx = nullptr;
1600   AST->PP = nullptr;
1601   AST->Reader = nullptr;
1602 
1603   // Create a file manager object to provide access to and cache the filesystem.
1604   Clang->setFileManager(&AST->getFileManager());
1605 
1606   // Create the source manager.
1607   Clang->setSourceManager(&AST->getSourceManager());
1608 
1609   FrontendAction *Act = Action;
1610 
1611   std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1612   if (!Act) {
1613     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1614     Act = TrackerAct.get();
1615   }
1616 
1617   // Recover resources if we crash before exiting this method.
1618   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1619     ActCleanup(TrackerAct.get());
1620 
1621   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1622     AST->transferASTDataFromCompilerInstance(*Clang);
1623     if (OwnAST && ErrAST)
1624       ErrAST->swap(OwnAST);
1625 
1626     return nullptr;
1627   }
1628 
1629   if (Persistent && !TrackerAct) {
1630     Clang->getPreprocessor().addPPCallbacks(
1631         std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1632                                            AST->getCurrentTopLevelHashValue()));
1633     std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1634     if (Clang->hasASTConsumer())
1635       Consumers.push_back(Clang->takeASTConsumer());
1636     Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1637         *AST, AST->getCurrentTopLevelHashValue()));
1638     Clang->setASTConsumer(
1639         std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1640   }
1641   if (llvm::Error Err = Act->Execute()) {
1642     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1643     AST->transferASTDataFromCompilerInstance(*Clang);
1644     if (OwnAST && ErrAST)
1645       ErrAST->swap(OwnAST);
1646 
1647     return nullptr;
1648   }
1649 
1650   // Steal the created target, context, and preprocessor.
1651   AST->transferASTDataFromCompilerInstance(*Clang);
1652 
1653   Act->EndSourceFile();
1654 
1655   if (OwnAST)
1656     return OwnAST.release();
1657   else
1658     return AST;
1659 }
1660 
1661 bool ASTUnit::LoadFromCompilerInvocation(
1662     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1663     unsigned PrecompilePreambleAfterNParses,
1664     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1665   if (!Invocation)
1666     return true;
1667 
1668   assert(VFS && "VFS is null");
1669 
1670   // We'll manage file buffers ourselves.
1671   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1672   Invocation->getFrontendOpts().DisableFree = false;
1673   getDiagnostics().Reset();
1674   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1675 
1676   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1677   if (PrecompilePreambleAfterNParses > 0) {
1678     PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1679     OverrideMainBuffer =
1680         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1681     getDiagnostics().Reset();
1682     ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1683   }
1684 
1685   SimpleTimer ParsingTimer(WantTiming);
1686   ParsingTimer.setOutput("Parsing " + getMainFileName());
1687 
1688   // Recover resources if we crash before exiting this method.
1689   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1690     MemBufferCleanup(OverrideMainBuffer.get());
1691 
1692   return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1693 }
1694 
1695 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1696     std::shared_ptr<CompilerInvocation> CI,
1697     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1698     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1699     bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1700     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1701     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1702     bool UserFilesAreVolatile) {
1703   // Create the AST unit.
1704   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1705   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1706   AST->Diagnostics = Diags;
1707   AST->OnlyLocalDecls = OnlyLocalDecls;
1708   AST->CaptureDiagnostics = CaptureDiagnostics;
1709   AST->TUKind = TUKind;
1710   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1711   AST->IncludeBriefCommentsInCodeCompletion
1712     = IncludeBriefCommentsInCodeCompletion;
1713   AST->Invocation = std::move(CI);
1714   AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1715   AST->FileMgr = FileMgr;
1716   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1717 
1718   // Recover resources if we crash before exiting this method.
1719   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1720     ASTUnitCleanup(AST.get());
1721   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1722     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1723     DiagCleanup(Diags.get());
1724 
1725   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1726                                       PrecompilePreambleAfterNParses,
1727                                       &AST->FileMgr->getVirtualFileSystem()))
1728     return nullptr;
1729   return AST;
1730 }
1731 
1732 ASTUnit *ASTUnit::LoadFromCommandLine(
1733     const char **ArgBegin, const char **ArgEnd,
1734     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1735     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1736     bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1737     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1738     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1739     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1740     bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
1741     bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1742     bool RetainExcludedConditionalBlocks,
1743     llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1744     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1745   assert(Diags.get() && "no DiagnosticsEngine was provided");
1746 
1747   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1748 
1749   std::shared_ptr<CompilerInvocation> CI;
1750 
1751   {
1752     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1753                                       &StoredDiagnostics, nullptr);
1754 
1755     CI = createInvocationFromCommandLine(
1756         llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1757     if (!CI)
1758       return nullptr;
1759   }
1760 
1761   // Override any files that need remapping
1762   for (const auto &RemappedFile : RemappedFiles) {
1763     CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1764                                               RemappedFile.second);
1765   }
1766   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1767   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1768   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1769   PPOpts.SingleFileParseMode = SingleFileParse;
1770   PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
1771 
1772   // Override the resources path.
1773   CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1774 
1775   CI->getFrontendOpts().SkipFunctionBodies =
1776       SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
1777 
1778   if (ModuleFormat)
1779     CI->getHeaderSearchOpts().ModuleFormat =
1780         std::string(ModuleFormat.getValue());
1781 
1782   // Create the AST unit.
1783   std::unique_ptr<ASTUnit> AST;
1784   AST.reset(new ASTUnit(false));
1785   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1786   AST->StoredDiagnostics.swap(StoredDiagnostics);
1787   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1788   AST->Diagnostics = Diags;
1789   AST->FileSystemOpts = CI->getFileSystemOpts();
1790   if (!VFS)
1791     VFS = llvm::vfs::getRealFileSystem();
1792   VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1793   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1794   AST->ModuleCache = new InMemoryModuleCache;
1795   AST->OnlyLocalDecls = OnlyLocalDecls;
1796   AST->CaptureDiagnostics = CaptureDiagnostics;
1797   AST->TUKind = TUKind;
1798   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1799   AST->IncludeBriefCommentsInCodeCompletion
1800     = IncludeBriefCommentsInCodeCompletion;
1801   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1802   AST->Invocation = CI;
1803   AST->SkipFunctionBodies = SkipFunctionBodies;
1804   if (ForSerialization)
1805     AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
1806   // Zero out now to ease cleanup during crash recovery.
1807   CI = nullptr;
1808   Diags = nullptr;
1809 
1810   // Recover resources if we crash before exiting this method.
1811   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1812     ASTUnitCleanup(AST.get());
1813 
1814   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1815                                       PrecompilePreambleAfterNParses,
1816                                       VFS)) {
1817     // Some error occurred, if caller wants to examine diagnostics, pass it the
1818     // ASTUnit.
1819     if (ErrAST) {
1820       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1821       ErrAST->swap(AST);
1822     }
1823     return nullptr;
1824   }
1825 
1826   return AST.release();
1827 }
1828 
1829 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1830                       ArrayRef<RemappedFile> RemappedFiles,
1831                       IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1832   if (!Invocation)
1833     return true;
1834 
1835   if (!VFS) {
1836     assert(FileMgr && "FileMgr is null on Reparse call");
1837     VFS = &FileMgr->getVirtualFileSystem();
1838   }
1839 
1840   clearFileLevelDecls();
1841 
1842   SimpleTimer ParsingTimer(WantTiming);
1843   ParsingTimer.setOutput("Reparsing " + getMainFileName());
1844 
1845   // Remap files.
1846   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1847   for (const auto &RB : PPOpts.RemappedFileBuffers)
1848     delete RB.second;
1849 
1850   Invocation->getPreprocessorOpts().clearRemappedFiles();
1851   for (const auto &RemappedFile : RemappedFiles) {
1852     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1853                                                       RemappedFile.second);
1854   }
1855 
1856   // If we have a preamble file lying around, or if we might try to
1857   // build a precompiled preamble, do so now.
1858   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1859   if (Preamble || PreambleRebuildCountdown > 0)
1860     OverrideMainBuffer =
1861         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1862 
1863   // Clear out the diagnostics state.
1864   FileMgr.reset();
1865   getDiagnostics().Reset();
1866   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1867   if (OverrideMainBuffer)
1868     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1869 
1870   // Parse the sources
1871   bool Result =
1872       Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1873 
1874   // If we're caching global code-completion results, and the top-level
1875   // declarations have changed, clear out the code-completion cache.
1876   if (!Result && ShouldCacheCodeCompletionResults &&
1877       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1878     CacheCodeCompletionResults();
1879 
1880   // We now need to clear out the completion info related to this translation
1881   // unit; it'll be recreated if necessary.
1882   CCTUInfo.reset();
1883 
1884   return Result;
1885 }
1886 
1887 void ASTUnit::ResetForParse() {
1888   SavedMainFileBuffer.reset();
1889 
1890   SourceMgr.reset();
1891   TheSema.reset();
1892   Ctx.reset();
1893   PP.reset();
1894   Reader.reset();
1895 
1896   TopLevelDecls.clear();
1897   clearFileLevelDecls();
1898 }
1899 
1900 //----------------------------------------------------------------------------//
1901 // Code completion
1902 //----------------------------------------------------------------------------//
1903 
1904 namespace {
1905 
1906   /// Code completion consumer that combines the cached code-completion
1907   /// results from an ASTUnit with the code-completion results provided to it,
1908   /// then passes the result on to
1909   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1910     uint64_t NormalContexts;
1911     ASTUnit &AST;
1912     CodeCompleteConsumer &Next;
1913 
1914   public:
1915     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1916                                   const CodeCompleteOptions &CodeCompleteOpts)
1917         : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
1918       // Compute the set of contexts in which we will look when we don't have
1919       // any information about the specific context.
1920       NormalContexts
1921         = (1LL << CodeCompletionContext::CCC_TopLevel)
1922         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1923         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1924         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1925         | (1LL << CodeCompletionContext::CCC_Statement)
1926         | (1LL << CodeCompletionContext::CCC_Expression)
1927         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1928         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1929         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1930         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1931         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1932         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1933         | (1LL << CodeCompletionContext::CCC_Recovery);
1934 
1935       if (AST.getASTContext().getLangOpts().CPlusPlus)
1936         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1937                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
1938                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1939     }
1940 
1941     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1942                                     CodeCompletionResult *Results,
1943                                     unsigned NumResults) override;
1944 
1945     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1946                                    OverloadCandidate *Candidates,
1947                                    unsigned NumCandidates,
1948                                    SourceLocation OpenParLoc) override {
1949       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1950                                      OpenParLoc);
1951     }
1952 
1953     CodeCompletionAllocator &getAllocator() override {
1954       return Next.getAllocator();
1955     }
1956 
1957     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1958       return Next.getCodeCompletionTUInfo();
1959     }
1960   };
1961 
1962 } // namespace
1963 
1964 /// Helper function that computes which global names are hidden by the
1965 /// local code-completion results.
1966 static void CalculateHiddenNames(const CodeCompletionContext &Context,
1967                                  CodeCompletionResult *Results,
1968                                  unsigned NumResults,
1969                                  ASTContext &Ctx,
1970                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1971   bool OnlyTagNames = false;
1972   switch (Context.getKind()) {
1973   case CodeCompletionContext::CCC_Recovery:
1974   case CodeCompletionContext::CCC_TopLevel:
1975   case CodeCompletionContext::CCC_ObjCInterface:
1976   case CodeCompletionContext::CCC_ObjCImplementation:
1977   case CodeCompletionContext::CCC_ObjCIvarList:
1978   case CodeCompletionContext::CCC_ClassStructUnion:
1979   case CodeCompletionContext::CCC_Statement:
1980   case CodeCompletionContext::CCC_Expression:
1981   case CodeCompletionContext::CCC_ObjCMessageReceiver:
1982   case CodeCompletionContext::CCC_DotMemberAccess:
1983   case CodeCompletionContext::CCC_ArrowMemberAccess:
1984   case CodeCompletionContext::CCC_ObjCPropertyAccess:
1985   case CodeCompletionContext::CCC_Namespace:
1986   case CodeCompletionContext::CCC_Type:
1987   case CodeCompletionContext::CCC_Symbol:
1988   case CodeCompletionContext::CCC_SymbolOrNewName:
1989   case CodeCompletionContext::CCC_ParenthesizedExpression:
1990   case CodeCompletionContext::CCC_ObjCInterfaceName:
1991     break;
1992 
1993   case CodeCompletionContext::CCC_EnumTag:
1994   case CodeCompletionContext::CCC_UnionTag:
1995   case CodeCompletionContext::CCC_ClassOrStructTag:
1996     OnlyTagNames = true;
1997     break;
1998 
1999   case CodeCompletionContext::CCC_ObjCProtocolName:
2000   case CodeCompletionContext::CCC_MacroName:
2001   case CodeCompletionContext::CCC_MacroNameUse:
2002   case CodeCompletionContext::CCC_PreprocessorExpression:
2003   case CodeCompletionContext::CCC_PreprocessorDirective:
2004   case CodeCompletionContext::CCC_NaturalLanguage:
2005   case CodeCompletionContext::CCC_SelectorName:
2006   case CodeCompletionContext::CCC_TypeQualifiers:
2007   case CodeCompletionContext::CCC_Other:
2008   case CodeCompletionContext::CCC_OtherWithMacros:
2009   case CodeCompletionContext::CCC_ObjCInstanceMessage:
2010   case CodeCompletionContext::CCC_ObjCClassMessage:
2011   case CodeCompletionContext::CCC_ObjCCategoryName:
2012   case CodeCompletionContext::CCC_IncludedFile:
2013   case CodeCompletionContext::CCC_NewName:
2014     // We're looking for nothing, or we're looking for names that cannot
2015     // be hidden.
2016     return;
2017   }
2018 
2019   using Result = CodeCompletionResult;
2020   for (unsigned I = 0; I != NumResults; ++I) {
2021     if (Results[I].Kind != Result::RK_Declaration)
2022       continue;
2023 
2024     unsigned IDNS
2025       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2026 
2027     bool Hiding = false;
2028     if (OnlyTagNames)
2029       Hiding = (IDNS & Decl::IDNS_Tag);
2030     else {
2031       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2032                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2033                              Decl::IDNS_NonMemberOperator);
2034       if (Ctx.getLangOpts().CPlusPlus)
2035         HiddenIDNS |= Decl::IDNS_Tag;
2036       Hiding = (IDNS & HiddenIDNS);
2037     }
2038 
2039     if (!Hiding)
2040       continue;
2041 
2042     DeclarationName Name = Results[I].Declaration->getDeclName();
2043     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2044       HiddenNames.insert(Identifier->getName());
2045     else
2046       HiddenNames.insert(Name.getAsString());
2047   }
2048 }
2049 
2050 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2051                                             CodeCompletionContext Context,
2052                                             CodeCompletionResult *Results,
2053                                             unsigned NumResults) {
2054   // Merge the results we were given with the results we cached.
2055   bool AddedResult = false;
2056   uint64_t InContexts =
2057       Context.getKind() == CodeCompletionContext::CCC_Recovery
2058         ? NormalContexts : (1LL << Context.getKind());
2059   // Contains the set of names that are hidden by "local" completion results.
2060   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2061   using Result = CodeCompletionResult;
2062   SmallVector<Result, 8> AllResults;
2063   for (ASTUnit::cached_completion_iterator
2064             C = AST.cached_completion_begin(),
2065          CEnd = AST.cached_completion_end();
2066        C != CEnd; ++C) {
2067     // If the context we are in matches any of the contexts we are
2068     // interested in, we'll add this result.
2069     if ((C->ShowInContexts & InContexts) == 0)
2070       continue;
2071 
2072     // If we haven't added any results previously, do so now.
2073     if (!AddedResult) {
2074       CalculateHiddenNames(Context, Results, NumResults, S.Context,
2075                            HiddenNames);
2076       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2077       AddedResult = true;
2078     }
2079 
2080     // Determine whether this global completion result is hidden by a local
2081     // completion result. If so, skip it.
2082     if (C->Kind != CXCursor_MacroDefinition &&
2083         HiddenNames.count(C->Completion->getTypedText()))
2084       continue;
2085 
2086     // Adjust priority based on similar type classes.
2087     unsigned Priority = C->Priority;
2088     CodeCompletionString *Completion = C->Completion;
2089     if (!Context.getPreferredType().isNull()) {
2090       if (C->Kind == CXCursor_MacroDefinition) {
2091         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2092                                          S.getLangOpts(),
2093                                Context.getPreferredType()->isAnyPointerType());
2094       } else if (C->Type) {
2095         CanQualType Expected
2096           = S.Context.getCanonicalType(
2097                                Context.getPreferredType().getUnqualifiedType());
2098         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2099         if (ExpectedSTC == C->TypeClass) {
2100           // We know this type is similar; check for an exact match.
2101           llvm::StringMap<unsigned> &CachedCompletionTypes
2102             = AST.getCachedCompletionTypes();
2103           llvm::StringMap<unsigned>::iterator Pos
2104             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2105           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2106             Priority /= CCF_ExactTypeMatch;
2107           else
2108             Priority /= CCF_SimilarTypeMatch;
2109         }
2110       }
2111     }
2112 
2113     // Adjust the completion string, if required.
2114     if (C->Kind == CXCursor_MacroDefinition &&
2115         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2116       // Create a new code-completion string that just contains the
2117       // macro name, without its arguments.
2118       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2119                                     CCP_CodePattern, C->Availability);
2120       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2121       Priority = CCP_CodePattern;
2122       Completion = Builder.TakeString();
2123     }
2124 
2125     AllResults.push_back(Result(Completion, Priority, C->Kind,
2126                                 C->Availability));
2127   }
2128 
2129   // If we did not add any cached completion results, just forward the
2130   // results we were given to the next consumer.
2131   if (!AddedResult) {
2132     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2133     return;
2134   }
2135 
2136   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2137                                   AllResults.size());
2138 }
2139 
2140 void ASTUnit::CodeComplete(
2141     StringRef File, unsigned Line, unsigned Column,
2142     ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2143     bool IncludeCodePatterns, bool IncludeBriefComments,
2144     CodeCompleteConsumer &Consumer,
2145     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2146     DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2147     FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2148     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2149   if (!Invocation)
2150     return;
2151 
2152   SimpleTimer CompletionTimer(WantTiming);
2153   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2154                             Twine(Line) + ":" + Twine(Column));
2155 
2156   auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2157 
2158   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2159   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2160   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2161 
2162   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2163                                    CachedCompletionResults.empty();
2164   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2165   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2166   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2167   CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
2168   CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
2169 
2170   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2171 
2172   FrontendOpts.CodeCompletionAt.FileName = std::string(File);
2173   FrontendOpts.CodeCompletionAt.Line = Line;
2174   FrontendOpts.CodeCompletionAt.Column = Column;
2175 
2176   // Set the language options appropriately.
2177   LangOpts = *CCInvocation->getLangOpts();
2178 
2179   // Spell-checking and warnings are wasteful during code-completion.
2180   LangOpts.SpellChecking = false;
2181   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2182 
2183   std::unique_ptr<CompilerInstance> Clang(
2184       new CompilerInstance(PCHContainerOps));
2185 
2186   // Recover resources if we crash before exiting this method.
2187   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2188     CICleanup(Clang.get());
2189 
2190   auto &Inv = *CCInvocation;
2191   Clang->setInvocation(std::move(CCInvocation));
2192   OriginalSourceFile =
2193       std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2194 
2195   // Set up diagnostics, capturing any diagnostics produced.
2196   Clang->setDiagnostics(&Diag);
2197   CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
2198                                     Clang->getDiagnostics(),
2199                                     &StoredDiagnostics, nullptr);
2200   ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2201 
2202   // Create the target instance.
2203   Clang->setTarget(TargetInfo::CreateTargetInfo(
2204       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2205   if (!Clang->hasTarget()) {
2206     Clang->setInvocation(nullptr);
2207     return;
2208   }
2209 
2210   // Inform the target of the language options.
2211   //
2212   // FIXME: We shouldn't need to do this, the target should be immutable once
2213   // created. This complexity should be lifted elsewhere.
2214   Clang->getTarget().adjust(Clang->getLangOpts());
2215 
2216   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2217          "Invocation must have exactly one source file!");
2218   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2219              InputKind::Source &&
2220          "FIXME: AST inputs not yet supported here!");
2221   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2222              Language::LLVM_IR &&
2223          "IR inputs not support here!");
2224 
2225   // Use the source and file managers that we were given.
2226   Clang->setFileManager(&FileMgr);
2227   Clang->setSourceManager(&SourceMgr);
2228 
2229   // Remap files.
2230   PreprocessorOpts.clearRemappedFiles();
2231   PreprocessorOpts.RetainRemappedFileBuffers = true;
2232   for (const auto &RemappedFile : RemappedFiles) {
2233     PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2234     OwnedBuffers.push_back(RemappedFile.second);
2235   }
2236 
2237   // Use the code completion consumer we were given, but adding any cached
2238   // code-completion results.
2239   AugmentedCodeCompleteConsumer *AugmentedConsumer
2240     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2241   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2242 
2243   // If we have a precompiled preamble, try to use it. We only allow
2244   // the use of the precompiled preamble if we're if the completion
2245   // point is within the main file, after the end of the precompiled
2246   // preamble.
2247   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2248   if (Preamble) {
2249     std::string CompleteFilePath(File);
2250 
2251     auto &VFS = FileMgr.getVirtualFileSystem();
2252     auto CompleteFileStatus = VFS.status(CompleteFilePath);
2253     if (CompleteFileStatus) {
2254       llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2255 
2256       std::string MainPath(OriginalSourceFile);
2257       auto MainStatus = VFS.status(MainPath);
2258       if (MainStatus) {
2259         llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2260         if (CompleteFileID == MainID && Line > 1)
2261           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2262               PCHContainerOps, Inv, &VFS, false, Line - 1);
2263       }
2264     }
2265   }
2266 
2267   // If the main file has been overridden due to the use of a preamble,
2268   // make that override happen and introduce the preamble.
2269   if (OverrideMainBuffer) {
2270     assert(Preamble &&
2271            "No preamble was built, but OverrideMainBuffer is not null");
2272 
2273     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
2274         &FileMgr.getVirtualFileSystem();
2275     Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2276                                   OverrideMainBuffer.get());
2277     // FIXME: there is no way to update VFS if it was changed by
2278     // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2279     // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2280     // PCH files are always readable.
2281     OwnedBuffers.push_back(OverrideMainBuffer.release());
2282   } else {
2283     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2284     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2285   }
2286 
2287   // Disable the preprocessing record if modules are not enabled.
2288   if (!Clang->getLangOpts().Modules)
2289     PreprocessorOpts.DetailedRecord = false;
2290 
2291   std::unique_ptr<SyntaxOnlyAction> Act;
2292   Act.reset(new SyntaxOnlyAction);
2293   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2294     if (llvm::Error Err = Act->Execute()) {
2295       consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2296     }
2297     Act->EndSourceFile();
2298   }
2299 }
2300 
2301 bool ASTUnit::Save(StringRef File) {
2302   if (HadModuleLoaderFatalFailure)
2303     return true;
2304 
2305   // Write to a temporary file and later rename it to the actual file, to avoid
2306   // possible race conditions.
2307   SmallString<128> TempPath;
2308   TempPath = File;
2309   TempPath += "-%%%%%%%%";
2310   // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2311   // unconditionally create a stat cache when we parse the file?
2312 
2313   if (llvm::Error Err = llvm::writeFileAtomically(
2314           TempPath, File, [this](llvm::raw_ostream &Out) {
2315             return serialize(Out) ? llvm::make_error<llvm::StringError>(
2316                                         "ASTUnit serialization failed",
2317                                         llvm::inconvertibleErrorCode())
2318                                   : llvm::Error::success();
2319           })) {
2320     consumeError(std::move(Err));
2321     return true;
2322   }
2323   return false;
2324 }
2325 
2326 static bool serializeUnit(ASTWriter &Writer,
2327                           SmallVectorImpl<char> &Buffer,
2328                           Sema &S,
2329                           bool hasErrors,
2330                           raw_ostream &OS) {
2331   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2332 
2333   // Write the generated bitstream to "Out".
2334   if (!Buffer.empty())
2335     OS.write(Buffer.data(), Buffer.size());
2336 
2337   return false;
2338 }
2339 
2340 bool ASTUnit::serialize(raw_ostream &OS) {
2341   // For serialization we are lenient if the errors were only warn-as-error kind.
2342   bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2343 
2344   if (WriterData)
2345     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2346                          getSema(), hasErrors, OS);
2347 
2348   SmallString<128> Buffer;
2349   llvm::BitstreamWriter Stream(Buffer);
2350   InMemoryModuleCache ModuleCache;
2351   ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2352   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2353 }
2354 
2355 using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
2356 
2357 void ASTUnit::TranslateStoredDiagnostics(
2358                           FileManager &FileMgr,
2359                           SourceManager &SrcMgr,
2360                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2361                           SmallVectorImpl<StoredDiagnostic> &Out) {
2362   // Map the standalone diagnostic into the new source manager. We also need to
2363   // remap all the locations to the new view. This includes the diag location,
2364   // any associated source ranges, and the source ranges of associated fix-its.
2365   // FIXME: There should be a cleaner way to do this.
2366   SmallVector<StoredDiagnostic, 4> Result;
2367   Result.reserve(Diags.size());
2368 
2369   for (const auto &SD : Diags) {
2370     // Rebuild the StoredDiagnostic.
2371     if (SD.Filename.empty())
2372       continue;
2373     auto FE = FileMgr.getFile(SD.Filename);
2374     if (!FE)
2375       continue;
2376     SourceLocation FileLoc;
2377     auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2378     if (ItFileID == PreambleSrcLocCache.end()) {
2379       FileID FID = SrcMgr.translateFile(*FE);
2380       FileLoc = SrcMgr.getLocForStartOfFile(FID);
2381       PreambleSrcLocCache[SD.Filename] = FileLoc;
2382     } else {
2383       FileLoc = ItFileID->getValue();
2384     }
2385 
2386     if (FileLoc.isInvalid())
2387       continue;
2388     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2389     FullSourceLoc Loc(L, SrcMgr);
2390 
2391     SmallVector<CharSourceRange, 4> Ranges;
2392     Ranges.reserve(SD.Ranges.size());
2393     for (const auto &Range : SD.Ranges) {
2394       SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2395       SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2396       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2397     }
2398 
2399     SmallVector<FixItHint, 2> FixIts;
2400     FixIts.reserve(SD.FixIts.size());
2401     for (const auto &FixIt : SD.FixIts) {
2402       FixIts.push_back(FixItHint());
2403       FixItHint &FH = FixIts.back();
2404       FH.CodeToInsert = FixIt.CodeToInsert;
2405       SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2406       SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2407       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2408     }
2409 
2410     Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2411                                       SD.Message, Loc, Ranges, FixIts));
2412   }
2413   Result.swap(Out);
2414 }
2415 
2416 void ASTUnit::addFileLevelDecl(Decl *D) {
2417   assert(D);
2418 
2419   // We only care about local declarations.
2420   if (D->isFromASTFile())
2421     return;
2422 
2423   SourceManager &SM = *SourceMgr;
2424   SourceLocation Loc = D->getLocation();
2425   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2426     return;
2427 
2428   // We only keep track of the file-level declarations of each file.
2429   if (!D->getLexicalDeclContext()->isFileContext())
2430     return;
2431 
2432   SourceLocation FileLoc = SM.getFileLoc(Loc);
2433   assert(SM.isLocalSourceLocation(FileLoc));
2434   FileID FID;
2435   unsigned Offset;
2436   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2437   if (FID.isInvalid())
2438     return;
2439 
2440   std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2441   if (!Decls)
2442     Decls = std::make_unique<LocDeclsTy>();
2443 
2444   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2445 
2446   if (Decls->empty() || Decls->back().first <= Offset) {
2447     Decls->push_back(LocDecl);
2448     return;
2449   }
2450 
2451   LocDeclsTy::iterator I =
2452       llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2453 
2454   Decls->insert(I, LocDecl);
2455 }
2456 
2457 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2458                                   SmallVectorImpl<Decl *> &Decls) {
2459   if (File.isInvalid())
2460     return;
2461 
2462   if (SourceMgr->isLoadedFileID(File)) {
2463     assert(Ctx->getExternalSource() && "No external source!");
2464     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2465                                                          Decls);
2466   }
2467 
2468   FileDeclsTy::iterator I = FileDecls.find(File);
2469   if (I == FileDecls.end())
2470     return;
2471 
2472   LocDeclsTy &LocDecls = *I->second;
2473   if (LocDecls.empty())
2474     return;
2475 
2476   LocDeclsTy::iterator BeginIt =
2477       llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2478         return LD.first < Offset;
2479       });
2480   if (BeginIt != LocDecls.begin())
2481     --BeginIt;
2482 
2483   // If we are pointing at a top-level decl inside an objc container, we need
2484   // to backtrack until we find it otherwise we will fail to report that the
2485   // region overlaps with an objc container.
2486   while (BeginIt != LocDecls.begin() &&
2487          BeginIt->second->isTopLevelDeclInObjCContainer())
2488     --BeginIt;
2489 
2490   LocDeclsTy::iterator EndIt = llvm::upper_bound(
2491       LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2492       llvm::less_first());
2493   if (EndIt != LocDecls.end())
2494     ++EndIt;
2495 
2496   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2497     Decls.push_back(DIt->second);
2498 }
2499 
2500 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2501                                     unsigned Line, unsigned Col) const {
2502   const SourceManager &SM = getSourceManager();
2503   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2504   return SM.getMacroArgExpandedLocation(Loc);
2505 }
2506 
2507 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2508                                     unsigned Offset) const {
2509   const SourceManager &SM = getSourceManager();
2510   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2511   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2512 }
2513 
2514 /// If \arg Loc is a loaded location from the preamble, returns
2515 /// the corresponding local location of the main file, otherwise it returns
2516 /// \arg Loc.
2517 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
2518   FileID PreambleID;
2519   if (SourceMgr)
2520     PreambleID = SourceMgr->getPreambleFileID();
2521 
2522   if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2523     return Loc;
2524 
2525   unsigned Offs;
2526   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2527     SourceLocation FileLoc
2528         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2529     return FileLoc.getLocWithOffset(Offs);
2530   }
2531 
2532   return Loc;
2533 }
2534 
2535 /// If \arg Loc is a local location of the main file but inside the
2536 /// preamble chunk, returns the corresponding loaded location from the
2537 /// preamble, otherwise it returns \arg Loc.
2538 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
2539   FileID PreambleID;
2540   if (SourceMgr)
2541     PreambleID = SourceMgr->getPreambleFileID();
2542 
2543   if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2544     return Loc;
2545 
2546   unsigned Offs;
2547   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2548       Offs < Preamble->getBounds().Size) {
2549     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2550     return FileLoc.getLocWithOffset(Offs);
2551   }
2552 
2553   return Loc;
2554 }
2555 
2556 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
2557   FileID FID;
2558   if (SourceMgr)
2559     FID = SourceMgr->getPreambleFileID();
2560 
2561   if (Loc.isInvalid() || FID.isInvalid())
2562     return false;
2563 
2564   return SourceMgr->isInFileID(Loc, FID);
2565 }
2566 
2567 bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
2568   FileID FID;
2569   if (SourceMgr)
2570     FID = SourceMgr->getMainFileID();
2571 
2572   if (Loc.isInvalid() || FID.isInvalid())
2573     return false;
2574 
2575   return SourceMgr->isInFileID(Loc, FID);
2576 }
2577 
2578 SourceLocation ASTUnit::getEndOfPreambleFileID() const {
2579   FileID FID;
2580   if (SourceMgr)
2581     FID = SourceMgr->getPreambleFileID();
2582 
2583   if (FID.isInvalid())
2584     return {};
2585 
2586   return SourceMgr->getLocForEndOfFile(FID);
2587 }
2588 
2589 SourceLocation ASTUnit::getStartOfMainFileID() const {
2590   FileID FID;
2591   if (SourceMgr)
2592     FID = SourceMgr->getMainFileID();
2593 
2594   if (FID.isInvalid())
2595     return {};
2596 
2597   return SourceMgr->getLocForStartOfFile(FID);
2598 }
2599 
2600 llvm::iterator_range<PreprocessingRecord::iterator>
2601 ASTUnit::getLocalPreprocessingEntities() const {
2602   if (isMainFileAST()) {
2603     serialization::ModuleFile &
2604       Mod = Reader->getModuleManager().getPrimaryModule();
2605     return Reader->getModulePreprocessedEntities(Mod);
2606   }
2607 
2608   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2609     return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2610 
2611   return llvm::make_range(PreprocessingRecord::iterator(),
2612                           PreprocessingRecord::iterator());
2613 }
2614 
2615 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2616   if (isMainFileAST()) {
2617     serialization::ModuleFile &
2618       Mod = Reader->getModuleManager().getPrimaryModule();
2619     for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2620       if (!Fn(context, D))
2621         return false;
2622     }
2623 
2624     return true;
2625   }
2626 
2627   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2628                                 TLEnd = top_level_end();
2629          TL != TLEnd; ++TL) {
2630     if (!Fn(context, *TL))
2631       return false;
2632   }
2633 
2634   return true;
2635 }
2636 
2637 const FileEntry *ASTUnit::getPCHFile() {
2638   if (!Reader)
2639     return nullptr;
2640 
2641   serialization::ModuleFile *Mod = nullptr;
2642   Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2643     switch (M.Kind) {
2644     case serialization::MK_ImplicitModule:
2645     case serialization::MK_ExplicitModule:
2646     case serialization::MK_PrebuiltModule:
2647       return true; // skip dependencies.
2648     case serialization::MK_PCH:
2649       Mod = &M;
2650       return true; // found it.
2651     case serialization::MK_Preamble:
2652       return false; // look in dependencies.
2653     case serialization::MK_MainFile:
2654       return false; // look in dependencies.
2655     }
2656 
2657     return true;
2658   });
2659   if (Mod)
2660     return Mod->File;
2661 
2662   return nullptr;
2663 }
2664 
2665 bool ASTUnit::isModuleFile() const {
2666   return isMainFileAST() && getLangOpts().isCompilingModule();
2667 }
2668 
2669 InputKind ASTUnit::getInputKind() const {
2670   auto &LangOpts = getLangOpts();
2671 
2672   Language Lang;
2673   if (LangOpts.OpenCL)
2674     Lang = Language::OpenCL;
2675   else if (LangOpts.CUDA)
2676     Lang = Language::CUDA;
2677   else if (LangOpts.RenderScript)
2678     Lang = Language::RenderScript;
2679   else if (LangOpts.CPlusPlus)
2680     Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
2681   else
2682     Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
2683 
2684   InputKind::Format Fmt = InputKind::Source;
2685   if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2686     Fmt = InputKind::ModuleMap;
2687 
2688   // We don't know if input was preprocessed. Assume not.
2689   bool PP = false;
2690 
2691   return InputKind(Lang, Fmt, PP);
2692 }
2693 
2694 #ifndef NDEBUG
2695 ASTUnit::ConcurrencyState::ConcurrencyState() {
2696   Mutex = new std::recursive_mutex;
2697 }
2698 
2699 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2700   delete static_cast<std::recursive_mutex *>(Mutex);
2701 }
2702 
2703 void ASTUnit::ConcurrencyState::start() {
2704   bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
2705   assert(acquired && "Concurrent access to ASTUnit!");
2706 }
2707 
2708 void ASTUnit::ConcurrencyState::finish() {
2709   static_cast<std::recursive_mutex *>(Mutex)->unlock();
2710 }
2711 
2712 #else // NDEBUG
2713 
2714 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2715 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2716 void ASTUnit::ConcurrencyState::start() {}
2717 void ASTUnit::ConcurrencyState::finish() {}
2718 
2719 #endif // NDEBUG
2720