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