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