clang API Documentation

ASTUnit.cpp
Go to the documentation of this file.
00001 //===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // ASTUnit Implementation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Frontend/ASTUnit.h"
00015 #include "clang/AST/ASTConsumer.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/DeclVisitor.h"
00018 #include "clang/AST/StmtVisitor.h"
00019 #include "clang/AST/TypeOrdering.h"
00020 #include "clang/Basic/Diagnostic.h"
00021 #include "clang/Basic/TargetInfo.h"
00022 #include "clang/Basic/TargetOptions.h"
00023 #include "clang/Basic/VirtualFileSystem.h"
00024 #include "clang/Frontend/CompilerInstance.h"
00025 #include "clang/Frontend/FrontendActions.h"
00026 #include "clang/Frontend/FrontendDiagnostic.h"
00027 #include "clang/Frontend/FrontendOptions.h"
00028 #include "clang/Frontend/MultiplexConsumer.h"
00029 #include "clang/Frontend/Utils.h"
00030 #include "clang/Lex/HeaderSearch.h"
00031 #include "clang/Lex/Preprocessor.h"
00032 #include "clang/Lex/PreprocessorOptions.h"
00033 #include "clang/Sema/Sema.h"
00034 #include "clang/Serialization/ASTReader.h"
00035 #include "clang/Serialization/ASTWriter.h"
00036 #include "llvm/ADT/ArrayRef.h"
00037 #include "llvm/ADT/StringExtras.h"
00038 #include "llvm/ADT/StringSet.h"
00039 #include "llvm/Support/CrashRecoveryContext.h"
00040 #include "llvm/Support/Host.h"
00041 #include "llvm/Support/MemoryBuffer.h"
00042 #include "llvm/Support/Mutex.h"
00043 #include "llvm/Support/MutexGuard.h"
00044 #include "llvm/Support/Path.h"
00045 #include "llvm/Support/Timer.h"
00046 #include "llvm/Support/raw_ostream.h"
00047 #include <atomic>
00048 #include <cstdio>
00049 #include <cstdlib>
00050 using namespace clang;
00051 
00052 using llvm::TimeRecord;
00053 
00054 namespace {
00055   class SimpleTimer {
00056     bool WantTiming;
00057     TimeRecord Start;
00058     std::string Output;
00059 
00060   public:
00061     explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
00062       if (WantTiming)
00063         Start = TimeRecord::getCurrentTime();
00064     }
00065 
00066     void setOutput(const Twine &Output) {
00067       if (WantTiming)
00068         this->Output = Output.str();
00069     }
00070 
00071     ~SimpleTimer() {
00072       if (WantTiming) {
00073         TimeRecord Elapsed = TimeRecord::getCurrentTime();
00074         Elapsed -= Start;
00075         llvm::errs() << Output << ':';
00076         Elapsed.print(Elapsed, llvm::errs());
00077         llvm::errs() << '\n';
00078       }
00079     }
00080   };
00081   
00082   struct OnDiskData {
00083     /// \brief The file in which the precompiled preamble is stored.
00084     std::string PreambleFile;
00085 
00086     /// \brief Temporary files that should be removed when the ASTUnit is
00087     /// destroyed.
00088     SmallVector<std::string, 4> TemporaryFiles;
00089 
00090     /// \brief Erase temporary files.
00091     void CleanTemporaryFiles();
00092 
00093     /// \brief Erase the preamble file.
00094     void CleanPreambleFile();
00095 
00096     /// \brief Erase temporary files and the preamble file.
00097     void Cleanup();
00098   };
00099 }
00100 
00101 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
00102   static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
00103   return M;
00104 }
00105 
00106 static void cleanupOnDiskMapAtExit();
00107 
00108 typedef llvm::DenseMap<const ASTUnit *,
00109                        std::unique_ptr<OnDiskData>> OnDiskDataMap;
00110 static OnDiskDataMap &getOnDiskDataMap() {
00111   static OnDiskDataMap M;
00112   static bool hasRegisteredAtExit = false;
00113   if (!hasRegisteredAtExit) {
00114     hasRegisteredAtExit = true;
00115     atexit(cleanupOnDiskMapAtExit);
00116   }
00117   return M;
00118 }
00119 
00120 static void cleanupOnDiskMapAtExit() {
00121   // Use the mutex because there can be an alive thread destroying an ASTUnit.
00122   llvm::MutexGuard Guard(getOnDiskMutex());
00123   OnDiskDataMap &M = getOnDiskDataMap();
00124   for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00125     // We don't worry about freeing the memory associated with OnDiskDataMap.
00126     // All we care about is erasing stale files.
00127     I->second->Cleanup();
00128   }
00129 }
00130 
00131 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
00132   // We require the mutex since we are modifying the structure of the
00133   // DenseMap.
00134   llvm::MutexGuard Guard(getOnDiskMutex());
00135   OnDiskDataMap &M = getOnDiskDataMap();
00136   auto &D = M[AU];
00137   if (!D)
00138     D = llvm::make_unique<OnDiskData>();
00139   return *D;
00140 }
00141 
00142 static void erasePreambleFile(const ASTUnit *AU) {
00143   getOnDiskData(AU).CleanPreambleFile();
00144 }
00145 
00146 static void removeOnDiskEntry(const ASTUnit *AU) {
00147   // We require the mutex since we are modifying the structure of the
00148   // DenseMap.
00149   llvm::MutexGuard Guard(getOnDiskMutex());
00150   OnDiskDataMap &M = getOnDiskDataMap();
00151   OnDiskDataMap::iterator I = M.find(AU);
00152   if (I != M.end()) {
00153     I->second->Cleanup();
00154     M.erase(AU);
00155   }
00156 }
00157 
00158 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
00159   getOnDiskData(AU).PreambleFile = preambleFile;
00160 }
00161 
00162 static const std::string &getPreambleFile(const ASTUnit *AU) {
00163   return getOnDiskData(AU).PreambleFile;  
00164 }
00165 
00166 void OnDiskData::CleanTemporaryFiles() {
00167   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
00168     llvm::sys::fs::remove(TemporaryFiles[I]);
00169   TemporaryFiles.clear();
00170 }
00171 
00172 void OnDiskData::CleanPreambleFile() {
00173   if (!PreambleFile.empty()) {
00174     llvm::sys::fs::remove(PreambleFile);
00175     PreambleFile.clear();
00176   }
00177 }
00178 
00179 void OnDiskData::Cleanup() {
00180   CleanTemporaryFiles();
00181   CleanPreambleFile();
00182 }
00183 
00184 struct ASTUnit::ASTWriterData {
00185   SmallString<128> Buffer;
00186   llvm::BitstreamWriter Stream;
00187   ASTWriter Writer;
00188 
00189   ASTWriterData() : Stream(Buffer), Writer(Stream) { }
00190 };
00191 
00192 void ASTUnit::clearFileLevelDecls() {
00193   llvm::DeleteContainerSeconds(FileDecls);
00194 }
00195 
00196 void ASTUnit::CleanTemporaryFiles() {
00197   getOnDiskData(this).CleanTemporaryFiles();
00198 }
00199 
00200 void ASTUnit::addTemporaryFile(StringRef TempFile) {
00201   getOnDiskData(this).TemporaryFiles.push_back(TempFile);
00202 }
00203 
00204 /// \brief After failing to build a precompiled preamble (due to
00205 /// errors in the source that occurs in the preamble), the number of
00206 /// reparses during which we'll skip even trying to precompile the
00207 /// preamble.
00208 const unsigned DefaultPreambleRebuildInterval = 5;
00209 
00210 /// \brief Tracks the number of ASTUnit objects that are currently active.
00211 ///
00212 /// Used for debugging purposes only.
00213 static std::atomic<unsigned> ActiveASTUnitObjects;
00214 
00215 ASTUnit::ASTUnit(bool _MainFileIsAST)
00216   : Reader(nullptr), HadModuleLoaderFatalFailure(false),
00217     OnlyLocalDecls(false), CaptureDiagnostics(false),
00218     MainFileIsAST(_MainFileIsAST), 
00219     TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
00220     OwnsRemappedFileBuffers(true),
00221     NumStoredDiagnosticsFromDriver(0),
00222     PreambleRebuildCounter(0),
00223     NumWarningsInPreamble(0),
00224     ShouldCacheCodeCompletionResults(false),
00225     IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
00226     CompletionCacheTopLevelHashValue(0),
00227     PreambleTopLevelHashValue(0),
00228     CurrentTopLevelHashValue(0),
00229     UnsafeToFree(false) { 
00230   if (getenv("LIBCLANG_OBJTRACKING"))
00231     fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
00232 }
00233 
00234 ASTUnit::~ASTUnit() {
00235   // If we loaded from an AST file, balance out the BeginSourceFile call.
00236   if (MainFileIsAST && getDiagnostics().getClient()) {
00237     getDiagnostics().getClient()->EndSourceFile();
00238   }
00239 
00240   clearFileLevelDecls();
00241 
00242   // Clean up the temporary files and the preamble file.
00243   removeOnDiskEntry(this);
00244 
00245   // Free the buffers associated with remapped files. We are required to
00246   // perform this operation here because we explicitly request that the
00247   // compiler instance *not* free these buffers for each invocation of the
00248   // parser.
00249   if (Invocation.get() && OwnsRemappedFileBuffers) {
00250     PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
00251     for (const auto &RB : PPOpts.RemappedFileBuffers)
00252       delete RB.second;
00253   }
00254 
00255   ClearCachedCompletionResults();  
00256   
00257   if (getenv("LIBCLANG_OBJTRACKING"))
00258     fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
00259 }
00260 
00261 void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
00262 
00263 /// \brief Determine the set of code-completion contexts in which this 
00264 /// declaration should be shown.
00265 static unsigned getDeclShowContexts(const NamedDecl *ND,
00266                                     const LangOptions &LangOpts,
00267                                     bool &IsNestedNameSpecifier) {
00268   IsNestedNameSpecifier = false;
00269   
00270   if (isa<UsingShadowDecl>(ND))
00271     ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
00272   if (!ND)
00273     return 0;
00274   
00275   uint64_t Contexts = 0;
00276   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) || 
00277       isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
00278     // Types can appear in these contexts.
00279     if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
00280       Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
00281                |  (1LL << CodeCompletionContext::CCC_ObjCIvarList)
00282                |  (1LL << CodeCompletionContext::CCC_ClassStructUnion)
00283                |  (1LL << CodeCompletionContext::CCC_Statement)
00284                |  (1LL << CodeCompletionContext::CCC_Type)
00285                |  (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
00286 
00287     // In C++, types can appear in expressions contexts (for functional casts).
00288     if (LangOpts.CPlusPlus)
00289       Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
00290     
00291     // In Objective-C, message sends can send interfaces. In Objective-C++,
00292     // all types are available due to functional casts.
00293     if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
00294       Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
00295     
00296     // In Objective-C, you can only be a subclass of another Objective-C class
00297     if (isa<ObjCInterfaceDecl>(ND))
00298       Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
00299 
00300     // Deal with tag names.
00301     if (isa<EnumDecl>(ND)) {
00302       Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
00303       
00304       // Part of the nested-name-specifier in C++0x.
00305       if (LangOpts.CPlusPlus11)
00306         IsNestedNameSpecifier = true;
00307     } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
00308       if (Record->isUnion())
00309         Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
00310       else
00311         Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
00312       
00313       if (LangOpts.CPlusPlus)
00314         IsNestedNameSpecifier = true;
00315     } else if (isa<ClassTemplateDecl>(ND))
00316       IsNestedNameSpecifier = true;
00317   } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
00318     // Values can appear in these contexts.
00319     Contexts = (1LL << CodeCompletionContext::CCC_Statement)
00320              | (1LL << CodeCompletionContext::CCC_Expression)
00321              | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
00322              | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
00323   } else if (isa<ObjCProtocolDecl>(ND)) {
00324     Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
00325   } else if (isa<ObjCCategoryDecl>(ND)) {
00326     Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
00327   } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
00328     Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
00329    
00330     // Part of the nested-name-specifier.
00331     IsNestedNameSpecifier = true;
00332   }
00333   
00334   return Contexts;
00335 }
00336 
00337 void ASTUnit::CacheCodeCompletionResults() {
00338   if (!TheSema)
00339     return;
00340   
00341   SimpleTimer Timer(WantTiming);
00342   Timer.setOutput("Cache global code completions for " + getMainFileName());
00343 
00344   // Clear out the previous results.
00345   ClearCachedCompletionResults();
00346   
00347   // Gather the set of global code completions.
00348   typedef CodeCompletionResult Result;
00349   SmallVector<Result, 8> Results;
00350   CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
00351   CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
00352   TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
00353                                        CCTUInfo, Results);
00354   
00355   // Translate global code completions into cached completions.
00356   llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
00357   
00358   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
00359     switch (Results[I].Kind) {
00360     case Result::RK_Declaration: {
00361       bool IsNestedNameSpecifier = false;
00362       CachedCodeCompletionResult CachedResult;
00363       CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
00364                                                     *CachedCompletionAllocator,
00365                                                     CCTUInfo,
00366                                           IncludeBriefCommentsInCodeCompletion);
00367       CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
00368                                                         Ctx->getLangOpts(),
00369                                                         IsNestedNameSpecifier);
00370       CachedResult.Priority = Results[I].Priority;
00371       CachedResult.Kind = Results[I].CursorKind;
00372       CachedResult.Availability = Results[I].Availability;
00373 
00374       // Keep track of the type of this completion in an ASTContext-agnostic 
00375       // way.
00376       QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
00377       if (UsageType.isNull()) {
00378         CachedResult.TypeClass = STC_Void;
00379         CachedResult.Type = 0;
00380       } else {
00381         CanQualType CanUsageType
00382           = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
00383         CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
00384 
00385         // Determine whether we have already seen this type. If so, we save
00386         // ourselves the work of formatting the type string by using the 
00387         // temporary, CanQualType-based hash table to find the associated value.
00388         unsigned &TypeValue = CompletionTypes[CanUsageType];
00389         if (TypeValue == 0) {
00390           TypeValue = CompletionTypes.size();
00391           CachedCompletionTypes[QualType(CanUsageType).getAsString()]
00392             = TypeValue;
00393         }
00394         
00395         CachedResult.Type = TypeValue;
00396       }
00397       
00398       CachedCompletionResults.push_back(CachedResult);
00399       
00400       /// Handle nested-name-specifiers in C++.
00401       if (TheSema->Context.getLangOpts().CPlusPlus && 
00402           IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
00403         // The contexts in which a nested-name-specifier can appear in C++.
00404         uint64_t NNSContexts
00405           = (1LL << CodeCompletionContext::CCC_TopLevel)
00406           | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
00407           | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
00408           | (1LL << CodeCompletionContext::CCC_Statement)
00409           | (1LL << CodeCompletionContext::CCC_Expression)
00410           | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
00411           | (1LL << CodeCompletionContext::CCC_EnumTag)
00412           | (1LL << CodeCompletionContext::CCC_UnionTag)
00413           | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
00414           | (1LL << CodeCompletionContext::CCC_Type)
00415           | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
00416           | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
00417 
00418         if (isa<NamespaceDecl>(Results[I].Declaration) ||
00419             isa<NamespaceAliasDecl>(Results[I].Declaration))
00420           NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
00421 
00422         if (unsigned RemainingContexts 
00423                                 = NNSContexts & ~CachedResult.ShowInContexts) {
00424           // If there any contexts where this completion can be a 
00425           // nested-name-specifier but isn't already an option, create a 
00426           // nested-name-specifier completion.
00427           Results[I].StartsNestedNameSpecifier = true;
00428           CachedResult.Completion 
00429             = Results[I].CreateCodeCompletionString(*TheSema,
00430                                                     *CachedCompletionAllocator,
00431                                                     CCTUInfo,
00432                                         IncludeBriefCommentsInCodeCompletion);
00433           CachedResult.ShowInContexts = RemainingContexts;
00434           CachedResult.Priority = CCP_NestedNameSpecifier;
00435           CachedResult.TypeClass = STC_Void;
00436           CachedResult.Type = 0;
00437           CachedCompletionResults.push_back(CachedResult);
00438         }
00439       }
00440       break;
00441     }
00442         
00443     case Result::RK_Keyword:
00444     case Result::RK_Pattern:
00445       // Ignore keywords and patterns; we don't care, since they are so
00446       // easily regenerated.
00447       break;
00448       
00449     case Result::RK_Macro: {
00450       CachedCodeCompletionResult CachedResult;
00451       CachedResult.Completion 
00452         = Results[I].CreateCodeCompletionString(*TheSema,
00453                                                 *CachedCompletionAllocator,
00454                                                 CCTUInfo,
00455                                           IncludeBriefCommentsInCodeCompletion);
00456       CachedResult.ShowInContexts
00457         = (1LL << CodeCompletionContext::CCC_TopLevel)
00458         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
00459         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
00460         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
00461         | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
00462         | (1LL << CodeCompletionContext::CCC_Statement)
00463         | (1LL << CodeCompletionContext::CCC_Expression)
00464         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
00465         | (1LL << CodeCompletionContext::CCC_MacroNameUse)
00466         | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
00467         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
00468         | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
00469       
00470       CachedResult.Priority = Results[I].Priority;
00471       CachedResult.Kind = Results[I].CursorKind;
00472       CachedResult.Availability = Results[I].Availability;
00473       CachedResult.TypeClass = STC_Void;
00474       CachedResult.Type = 0;
00475       CachedCompletionResults.push_back(CachedResult);
00476       break;
00477     }
00478     }
00479   }
00480   
00481   // Save the current top-level hash value.
00482   CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
00483 }
00484 
00485 void ASTUnit::ClearCachedCompletionResults() {
00486   CachedCompletionResults.clear();
00487   CachedCompletionTypes.clear();
00488   CachedCompletionAllocator = nullptr;
00489 }
00490 
00491 namespace {
00492 
00493 /// \brief Gathers information from ASTReader that will be used to initialize
00494 /// a Preprocessor.
00495 class ASTInfoCollector : public ASTReaderListener {
00496   Preprocessor &PP;
00497   ASTContext &Context;
00498   LangOptions &LangOpt;
00499   std::shared_ptr<TargetOptions> &TargetOpts;
00500   IntrusiveRefCntPtr<TargetInfo> &Target;
00501   unsigned &Counter;
00502 
00503   bool InitializedLanguage;
00504 public:
00505   ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
00506                    std::shared_ptr<TargetOptions> &TargetOpts,
00507                    IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
00508       : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
00509         Target(Target), Counter(Counter), InitializedLanguage(false) {}
00510 
00511   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
00512                            bool AllowCompatibleDifferences) override {
00513     if (InitializedLanguage)
00514       return false;
00515     
00516     LangOpt = LangOpts;
00517     InitializedLanguage = true;
00518     
00519     updated();
00520     return false;
00521   }
00522 
00523   bool ReadTargetOptions(const TargetOptions &TargetOpts,
00524                          bool Complain) override {
00525     // If we've already initialized the target, don't do it again.
00526     if (Target)
00527       return false;
00528 
00529     this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
00530     Target =
00531         TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
00532 
00533     updated();
00534     return false;
00535   }
00536 
00537   void ReadCounter(const serialization::ModuleFile &M,
00538                    unsigned Value) override {
00539     Counter = Value;
00540   }
00541 
00542 private:
00543   void updated() {
00544     if (!Target || !InitializedLanguage)
00545       return;
00546 
00547     // Inform the target of the language options.
00548     //
00549     // FIXME: We shouldn't need to do this, the target should be immutable once
00550     // created. This complexity should be lifted elsewhere.
00551     Target->adjust(LangOpt);
00552 
00553     // Initialize the preprocessor.
00554     PP.Initialize(*Target);
00555 
00556     // Initialize the ASTContext
00557     Context.InitBuiltinTypes(*Target);
00558 
00559     // We didn't have access to the comment options when the ASTContext was
00560     // constructed, so register them now.
00561     Context.getCommentCommandTraits().registerCommentOptions(
00562         LangOpt.CommentOpts);
00563   }
00564 };
00565 
00566   /// \brief Diagnostic consumer that saves each diagnostic it is given.
00567 class StoredDiagnosticConsumer : public DiagnosticConsumer {
00568   SmallVectorImpl<StoredDiagnostic> &StoredDiags;
00569   SourceManager *SourceMgr;
00570 
00571 public:
00572   explicit StoredDiagnosticConsumer(
00573                           SmallVectorImpl<StoredDiagnostic> &StoredDiags)
00574     : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
00575 
00576   void BeginSourceFile(const LangOptions &LangOpts,
00577                        const Preprocessor *PP = nullptr) override {
00578     if (PP)
00579       SourceMgr = &PP->getSourceManager();
00580   }
00581 
00582   void HandleDiagnostic(DiagnosticsEngine::Level Level,
00583                         const Diagnostic &Info) override;
00584 };
00585 
00586 /// \brief RAII object that optionally captures diagnostics, if
00587 /// there is no diagnostic client to capture them already.
00588 class CaptureDroppedDiagnostics {
00589   DiagnosticsEngine &Diags;
00590   StoredDiagnosticConsumer Client;
00591   DiagnosticConsumer *PreviousClient;
00592   std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
00593 
00594 public:
00595   CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
00596                           SmallVectorImpl<StoredDiagnostic> &StoredDiags)
00597     : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
00598   {
00599     if (RequestCapture || Diags.getClient() == nullptr) {
00600       OwningPreviousClient = Diags.takeClient();
00601       PreviousClient = Diags.getClient();
00602       Diags.setClient(&Client, false);
00603     }
00604   }
00605 
00606   ~CaptureDroppedDiagnostics() {
00607     if (Diags.getClient() == &Client)
00608       Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
00609   }
00610 };
00611 
00612 } // anonymous namespace
00613 
00614 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
00615                                               const Diagnostic &Info) {
00616   // Default implementation (Warnings/errors count).
00617   DiagnosticConsumer::HandleDiagnostic(Level, Info);
00618 
00619   // Only record the diagnostic if it's part of the source manager we know
00620   // about. This effectively drops diagnostics from modules we're building.
00621   // FIXME: In the long run, ee don't want to drop source managers from modules.
00622   if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
00623     StoredDiags.push_back(StoredDiagnostic(Level, Info));
00624 }
00625 
00626 ASTMutationListener *ASTUnit::getASTMutationListener() {
00627   if (WriterData)
00628     return &WriterData->Writer;
00629   return nullptr;
00630 }
00631 
00632 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
00633   if (WriterData)
00634     return &WriterData->Writer;
00635   return nullptr;
00636 }
00637 
00638 std::unique_ptr<llvm::MemoryBuffer>
00639 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
00640   assert(FileMgr);
00641   auto Buffer = FileMgr->getBufferForFile(Filename);
00642   if (Buffer)
00643     return std::move(*Buffer);
00644   if (ErrorStr)
00645     *ErrorStr = Buffer.getError().message();
00646   return nullptr;
00647 }
00648 
00649 /// \brief Configure the diagnostics object for use with ASTUnit.
00650 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00651                              ASTUnit &AST, bool CaptureDiagnostics) {
00652   assert(Diags.get() && "no DiagnosticsEngine was provided");
00653   if (CaptureDiagnostics)
00654     Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
00655 }
00656 
00657 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
00658     const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00659     const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
00660     ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
00661     bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
00662   std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
00663 
00664   // Recover resources if we crash before exiting this method.
00665   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
00666     ASTUnitCleanup(AST.get());
00667   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
00668     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
00669     DiagCleanup(Diags.get());
00670 
00671   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
00672 
00673   AST->OnlyLocalDecls = OnlyLocalDecls;
00674   AST->CaptureDiagnostics = CaptureDiagnostics;
00675   AST->Diagnostics = Diags;
00676   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
00677   AST->FileMgr = new FileManager(FileSystemOpts, VFS);
00678   AST->UserFilesAreVolatile = UserFilesAreVolatile;
00679   AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
00680                                      AST->getFileManager(),
00681                                      UserFilesAreVolatile);
00682   AST->HSOpts = new HeaderSearchOptions();
00683 
00684   AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
00685                                          AST->getSourceManager(),
00686                                          AST->getDiagnostics(),
00687                                          AST->ASTFileLangOpts,
00688                                          /*Target=*/nullptr));
00689 
00690   PreprocessorOptions *PPOpts = new PreprocessorOptions();
00691 
00692   for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
00693     PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
00694 
00695   // Gather Info for preprocessor construction later on.
00696 
00697   HeaderSearch &HeaderInfo = *AST->HeaderInfo;
00698   unsigned Counter;
00699 
00700   AST->PP =
00701       new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
00702                        AST->getSourceManager(), HeaderInfo, *AST,
00703                        /*IILookup=*/nullptr,
00704                        /*OwnsHeaderSearch=*/false);
00705   Preprocessor &PP = *AST->PP;
00706 
00707   AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
00708                             PP.getIdentifierTable(), PP.getSelectorTable(),
00709                             PP.getBuiltinInfo());
00710   ASTContext &Context = *AST->Ctx;
00711 
00712   bool disableValid = false;
00713   if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
00714     disableValid = true;
00715   AST->Reader = new ASTReader(PP, Context,
00716                              /*isysroot=*/"",
00717                              /*DisableValidation=*/disableValid,
00718                              AllowPCHWithCompilerErrors);
00719 
00720   AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
00721       *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
00722       Counter));
00723 
00724   switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
00725                           SourceLocation(), ASTReader::ARR_None)) {
00726   case ASTReader::Success:
00727     break;
00728 
00729   case ASTReader::Failure:
00730   case ASTReader::Missing:
00731   case ASTReader::OutOfDate:
00732   case ASTReader::VersionMismatch:
00733   case ASTReader::ConfigurationMismatch:
00734   case ASTReader::HadErrors:
00735     AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
00736     return nullptr;
00737   }
00738 
00739   AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
00740 
00741   PP.setCounterValue(Counter);
00742 
00743   // Attach the AST reader to the AST context as an external AST
00744   // source, so that declarations will be deserialized from the
00745   // AST file as needed.
00746   Context.setExternalSource(AST->Reader);
00747 
00748   // Create an AST consumer, even though it isn't used.
00749   AST->Consumer.reset(new ASTConsumer);
00750   
00751   // Create a semantic analysis object and tell the AST reader about it.
00752   AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
00753   AST->TheSema->Initialize();
00754   AST->Reader->InitializeSema(*AST->TheSema);
00755 
00756   // Tell the diagnostic client that we have started a source file.
00757   AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
00758 
00759   return AST;
00760 }
00761 
00762 namespace {
00763 
00764 /// \brief Preprocessor callback class that updates a hash value with the names 
00765 /// of all macros that have been defined by the translation unit.
00766 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
00767   unsigned &Hash;
00768   
00769 public:
00770   explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
00771 
00772   void MacroDefined(const Token &MacroNameTok,
00773                     const MacroDirective *MD) override {
00774     Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
00775   }
00776 };
00777 
00778 /// \brief Add the given declaration to the hash of all top-level entities.
00779 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
00780   if (!D)
00781     return;
00782   
00783   DeclContext *DC = D->getDeclContext();
00784   if (!DC)
00785     return;
00786   
00787   if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
00788     return;
00789 
00790   if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
00791     if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
00792       // For an unscoped enum include the enumerators in the hash since they
00793       // enter the top-level namespace.
00794       if (!EnumD->isScoped()) {
00795         for (const auto *EI : EnumD->enumerators()) {
00796           if (EI->getIdentifier())
00797             Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
00798         }
00799       }
00800     }
00801 
00802     if (ND->getIdentifier())
00803       Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
00804     else if (DeclarationName Name = ND->getDeclName()) {
00805       std::string NameStr = Name.getAsString();
00806       Hash = llvm::HashString(NameStr, Hash);
00807     }
00808     return;
00809   }
00810 
00811   if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
00812     if (Module *Mod = ImportD->getImportedModule()) {
00813       std::string ModName = Mod->getFullModuleName();
00814       Hash = llvm::HashString(ModName, Hash);
00815     }
00816     return;
00817   }
00818 }
00819 
00820 class TopLevelDeclTrackerConsumer : public ASTConsumer {
00821   ASTUnit &Unit;
00822   unsigned &Hash;
00823   
00824 public:
00825   TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
00826     : Unit(_Unit), Hash(Hash) {
00827     Hash = 0;
00828   }
00829 
00830   void handleTopLevelDecl(Decl *D) {
00831     if (!D)
00832       return;
00833 
00834     // FIXME: Currently ObjC method declarations are incorrectly being
00835     // reported as top-level declarations, even though their DeclContext
00836     // is the containing ObjC @interface/@implementation.  This is a
00837     // fundamental problem in the parser right now.
00838     if (isa<ObjCMethodDecl>(D))
00839       return;
00840 
00841     AddTopLevelDeclarationToHash(D, Hash);
00842     Unit.addTopLevelDecl(D);
00843 
00844     handleFileLevelDecl(D);
00845   }
00846 
00847   void handleFileLevelDecl(Decl *D) {
00848     Unit.addFileLevelDecl(D);
00849     if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
00850       for (auto *I : NSD->decls())
00851         handleFileLevelDecl(I);
00852     }
00853   }
00854 
00855   bool HandleTopLevelDecl(DeclGroupRef D) override {
00856     for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
00857       handleTopLevelDecl(*it);
00858     return true;
00859   }
00860 
00861   // We're not interested in "interesting" decls.
00862   void HandleInterestingDecl(DeclGroupRef) override {}
00863 
00864   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
00865     for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
00866       handleTopLevelDecl(*it);
00867   }
00868 
00869   ASTMutationListener *GetASTMutationListener() override {
00870     return Unit.getASTMutationListener();
00871   }
00872 
00873   ASTDeserializationListener *GetASTDeserializationListener() override {
00874     return Unit.getDeserializationListener();
00875   }
00876 };
00877 
00878 class TopLevelDeclTrackerAction : public ASTFrontendAction {
00879 public:
00880   ASTUnit &Unit;
00881 
00882   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
00883                                                  StringRef InFile) override {
00884     CI.getPreprocessor().addPPCallbacks(
00885         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
00886                                            Unit.getCurrentTopLevelHashValue()));
00887     return llvm::make_unique<TopLevelDeclTrackerConsumer>(
00888         Unit, Unit.getCurrentTopLevelHashValue());
00889   }
00890 
00891 public:
00892   TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
00893 
00894   bool hasCodeCompletionSupport() const override { return false; }
00895   TranslationUnitKind getTranslationUnitKind() override {
00896     return Unit.getTranslationUnitKind(); 
00897   }
00898 };
00899 
00900 class PrecompilePreambleAction : public ASTFrontendAction {
00901   ASTUnit &Unit;
00902   bool HasEmittedPreamblePCH;
00903 
00904 public:
00905   explicit PrecompilePreambleAction(ASTUnit &Unit)
00906       : Unit(Unit), HasEmittedPreamblePCH(false) {}
00907 
00908   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
00909                                                  StringRef InFile) override;
00910   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
00911   void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
00912   bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
00913 
00914   bool hasCodeCompletionSupport() const override { return false; }
00915   bool hasASTFileSupport() const override { return false; }
00916   TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
00917 };
00918 
00919 class PrecompilePreambleConsumer : public PCHGenerator {
00920   ASTUnit &Unit;
00921   unsigned &Hash;
00922   std::vector<Decl *> TopLevelDecls;
00923   PrecompilePreambleAction *Action;
00924 
00925 public:
00926   PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
00927                              const Preprocessor &PP, StringRef isysroot,
00928                              raw_ostream *Out)
00929     : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
00930       Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
00931     Hash = 0;
00932   }
00933 
00934   bool HandleTopLevelDecl(DeclGroupRef D) override {
00935     for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
00936       Decl *D = *it;
00937       // FIXME: Currently ObjC method declarations are incorrectly being
00938       // reported as top-level declarations, even though their DeclContext
00939       // is the containing ObjC @interface/@implementation.  This is a
00940       // fundamental problem in the parser right now.
00941       if (isa<ObjCMethodDecl>(D))
00942         continue;
00943       AddTopLevelDeclarationToHash(D, Hash);
00944       TopLevelDecls.push_back(D);
00945     }
00946     return true;
00947   }
00948 
00949   void HandleTranslationUnit(ASTContext &Ctx) override {
00950     PCHGenerator::HandleTranslationUnit(Ctx);
00951     if (hasEmittedPCH()) {
00952       // Translate the top-level declarations we captured during
00953       // parsing into declaration IDs in the precompiled
00954       // preamble. This will allow us to deserialize those top-level
00955       // declarations when requested.
00956       for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
00957         Decl *D = TopLevelDecls[I];
00958         // Invalid top-level decls may not have been serialized.
00959         if (D->isInvalidDecl())
00960           continue;
00961         Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
00962       }
00963 
00964       Action->setHasEmittedPreamblePCH();
00965     }
00966   }
00967 };
00968 
00969 }
00970 
00971 std::unique_ptr<ASTConsumer>
00972 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
00973                                             StringRef InFile) {
00974   std::string Sysroot;
00975   std::string OutputFile;
00976   raw_ostream *OS = nullptr;
00977   if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
00978                                                      OutputFile, OS))
00979     return nullptr;
00980 
00981   if (!CI.getFrontendOpts().RelocatablePCH)
00982     Sysroot.clear();
00983 
00984   CI.getPreprocessor().addPPCallbacks(
00985       llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
00986                                            Unit.getCurrentTopLevelHashValue()));
00987   return llvm::make_unique<PrecompilePreambleConsumer>(
00988       Unit, this, CI.getPreprocessor(), Sysroot, OS);
00989 }
00990 
00991 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
00992   return StoredDiag.getLocation().isValid();
00993 }
00994 
00995 static void
00996 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
00997   // Get rid of stored diagnostics except the ones from the driver which do not
00998   // have a source location.
00999   StoredDiags.erase(
01000       std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
01001       StoredDiags.end());
01002 }
01003 
01004 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
01005                                                               StoredDiagnostics,
01006                                   SourceManager &SM) {
01007   // The stored diagnostic has the old source manager in it; update
01008   // the locations to refer into the new source manager. Since we've
01009   // been careful to make sure that the source manager's state
01010   // before and after are identical, so that we can reuse the source
01011   // location itself.
01012   for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
01013     if (StoredDiagnostics[I].getLocation().isValid()) {
01014       FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
01015       StoredDiagnostics[I].setLocation(Loc);
01016     }
01017   }
01018 }
01019 
01020 /// Parse the source file into a translation unit using the given compiler
01021 /// invocation, replacing the current translation unit.
01022 ///
01023 /// \returns True if a failure occurred that causes the ASTUnit not to
01024 /// contain any translation-unit information, false otherwise.
01025 bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
01026   SavedMainFileBuffer.reset();
01027 
01028   if (!Invocation)
01029     return true;
01030 
01031   // Create the compiler instance to use for building the AST.
01032   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
01033 
01034   // Recover resources if we crash before exiting this method.
01035   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
01036     CICleanup(Clang.get());
01037 
01038   IntrusiveRefCntPtr<CompilerInvocation>
01039     CCInvocation(new CompilerInvocation(*Invocation));
01040 
01041   Clang->setInvocation(CCInvocation.get());
01042   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
01043     
01044   // Set up diagnostics, capturing any diagnostics that would
01045   // otherwise be dropped.
01046   Clang->setDiagnostics(&getDiagnostics());
01047   
01048   // Create the target instance.
01049   Clang->setTarget(TargetInfo::CreateTargetInfo(
01050       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
01051   if (!Clang->hasTarget())
01052     return true;
01053 
01054   // Inform the target of the language options.
01055   //
01056   // FIXME: We shouldn't need to do this, the target should be immutable once
01057   // created. This complexity should be lifted elsewhere.
01058   Clang->getTarget().adjust(Clang->getLangOpts());
01059   
01060   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
01061          "Invocation must have exactly one source file!");
01062   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
01063          "FIXME: AST inputs not yet supported here!");
01064   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
01065          "IR inputs not support here!");
01066 
01067   // Configure the various subsystems.
01068   LangOpts = Clang->getInvocation().LangOpts;
01069   FileSystemOpts = Clang->getFileSystemOpts();
01070   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
01071       createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
01072   if (!VFS)
01073     return true;
01074   FileMgr = new FileManager(FileSystemOpts, VFS);
01075   SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
01076                                 UserFilesAreVolatile);
01077   TheSema.reset();
01078   Ctx = nullptr;
01079   PP = nullptr;
01080   Reader = nullptr;
01081 
01082   // Clear out old caches and data.
01083   TopLevelDecls.clear();
01084   clearFileLevelDecls();
01085   CleanTemporaryFiles();
01086 
01087   if (!OverrideMainBuffer) {
01088     checkAndRemoveNonDriverDiags(StoredDiagnostics);
01089     TopLevelDeclsInPreamble.clear();
01090   }
01091 
01092   // Create a file manager object to provide access to and cache the filesystem.
01093   Clang->setFileManager(&getFileManager());
01094   
01095   // Create the source manager.
01096   Clang->setSourceManager(&getSourceManager());
01097   
01098   // If the main file has been overridden due to the use of a preamble,
01099   // make that override happen and introduce the preamble.
01100   PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
01101   if (OverrideMainBuffer) {
01102     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
01103                                      OverrideMainBuffer.get());
01104     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
01105     PreprocessorOpts.PrecompiledPreambleBytes.second
01106                                                     = PreambleEndsAtStartOfLine;
01107     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
01108     PreprocessorOpts.DisablePCHValidation = true;
01109     
01110     // The stored diagnostic has the old source manager in it; update
01111     // the locations to refer into the new source manager. Since we've
01112     // been careful to make sure that the source manager's state
01113     // before and after are identical, so that we can reuse the source
01114     // location itself.
01115     checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
01116 
01117     // Keep track of the override buffer;
01118     SavedMainFileBuffer = std::move(OverrideMainBuffer);
01119   }
01120 
01121   std::unique_ptr<TopLevelDeclTrackerAction> Act(
01122       new TopLevelDeclTrackerAction(*this));
01123 
01124   // Recover resources if we crash before exiting this method.
01125   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
01126     ActCleanup(Act.get());
01127 
01128   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
01129     goto error;
01130 
01131   if (SavedMainFileBuffer) {
01132     std::string ModName = getPreambleFile(this);
01133     TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
01134                                PreambleDiagnostics, StoredDiagnostics);
01135   }
01136 
01137   if (!Act->Execute())
01138     goto error;
01139 
01140   transferASTDataFromCompilerInstance(*Clang);
01141   
01142   Act->EndSourceFile();
01143 
01144   FailedParseDiagnostics.clear();
01145 
01146   return false;
01147 
01148 error:
01149   // Remove the overridden buffer we used for the preamble.
01150   SavedMainFileBuffer = nullptr;
01151 
01152   // Keep the ownership of the data in the ASTUnit because the client may
01153   // want to see the diagnostics.
01154   transferASTDataFromCompilerInstance(*Clang);
01155   FailedParseDiagnostics.swap(StoredDiagnostics);
01156   StoredDiagnostics.clear();
01157   NumStoredDiagnosticsFromDriver = 0;
01158   return true;
01159 }
01160 
01161 /// \brief Simple function to retrieve a path for a preamble precompiled header.
01162 static std::string GetPreamblePCHPath() {
01163   // FIXME: This is a hack so that we can override the preamble file during
01164   // crash-recovery testing, which is the only case where the preamble files
01165   // are not necessarily cleaned up.
01166   const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
01167   if (TmpFile)
01168     return TmpFile;
01169 
01170   SmallString<128> Path;
01171   llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
01172 
01173   return Path.str();
01174 }
01175 
01176 /// \brief Compute the preamble for the main file, providing the source buffer
01177 /// that corresponds to the main file along with a pair (bytes, start-of-line)
01178 /// that describes the preamble.
01179 ASTUnit::ComputedPreamble
01180 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
01181   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
01182   PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
01183   
01184   // Try to determine if the main file has been remapped, either from the 
01185   // command line (to another file) or directly through the compiler invocation
01186   // (to a memory buffer).
01187   llvm::MemoryBuffer *Buffer = nullptr;
01188   std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
01189   std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
01190   llvm::sys::fs::UniqueID MainFileID;
01191   if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
01192     // Check whether there is a file-file remapping of the main file
01193     for (const auto &RF : PreprocessorOpts.RemappedFiles) {
01194       std::string MPath(RF.first);
01195       llvm::sys::fs::UniqueID MID;
01196       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
01197         if (MainFileID == MID) {
01198           // We found a remapping. Try to load the resulting, remapped source.
01199           BufferOwner = getBufferForFile(RF.second);
01200           if (!BufferOwner)
01201             return ComputedPreamble(nullptr, nullptr, 0, true);
01202         }
01203       }
01204     }
01205     
01206     // Check whether there is a file-buffer remapping. It supercedes the
01207     // file-file remapping.
01208     for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
01209       std::string MPath(RB.first);
01210       llvm::sys::fs::UniqueID MID;
01211       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
01212         if (MainFileID == MID) {
01213           // We found a remapping.
01214           BufferOwner.reset();
01215           Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
01216         }
01217       }
01218     }
01219   }
01220   
01221   // If the main source file was not remapped, load it now.
01222   if (!Buffer && !BufferOwner) {
01223     BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
01224     if (!BufferOwner)
01225       return ComputedPreamble(nullptr, nullptr, 0, true);
01226   }
01227 
01228   if (!Buffer)
01229     Buffer = BufferOwner.get();
01230   auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
01231                                     *Invocation.getLangOpts(), MaxLines);
01232   return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
01233                           Pre.second);
01234 }
01235 
01236 ASTUnit::PreambleFileHash
01237 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
01238   PreambleFileHash Result;
01239   Result.Size = Size;
01240   Result.ModTime = ModTime;
01241   memset(Result.MD5, 0, sizeof(Result.MD5));
01242   return Result;
01243 }
01244 
01245 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
01246     const llvm::MemoryBuffer *Buffer) {
01247   PreambleFileHash Result;
01248   Result.Size = Buffer->getBufferSize();
01249   Result.ModTime = 0;
01250 
01251   llvm::MD5 MD5Ctx;
01252   MD5Ctx.update(Buffer->getBuffer().data());
01253   MD5Ctx.final(Result.MD5);
01254 
01255   return Result;
01256 }
01257 
01258 namespace clang {
01259 bool operator==(const ASTUnit::PreambleFileHash &LHS,
01260                 const ASTUnit::PreambleFileHash &RHS) {
01261   return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
01262          memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
01263 }
01264 } // namespace clang
01265 
01266 static std::pair<unsigned, unsigned>
01267 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
01268                     const LangOptions &LangOpts) {
01269   CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
01270   unsigned Offset = SM.getFileOffset(FileRange.getBegin());
01271   unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
01272   return std::make_pair(Offset, EndOffset);
01273 }
01274 
01275 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
01276                                                     const LangOptions &LangOpts,
01277                                                     const FixItHint &InFix) {
01278   ASTUnit::StandaloneFixIt OutFix;
01279   OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
01280   OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
01281                                                LangOpts);
01282   OutFix.CodeToInsert = InFix.CodeToInsert;
01283   OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
01284   return OutFix;
01285 }
01286 
01287 static ASTUnit::StandaloneDiagnostic
01288 makeStandaloneDiagnostic(const LangOptions &LangOpts,
01289                          const StoredDiagnostic &InDiag) {
01290   ASTUnit::StandaloneDiagnostic OutDiag;
01291   OutDiag.ID = InDiag.getID();
01292   OutDiag.Level = InDiag.getLevel();
01293   OutDiag.Message = InDiag.getMessage();
01294   OutDiag.LocOffset = 0;
01295   if (InDiag.getLocation().isInvalid())
01296     return OutDiag;
01297   const SourceManager &SM = InDiag.getLocation().getManager();
01298   SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
01299   OutDiag.Filename = SM.getFilename(FileLoc);
01300   if (OutDiag.Filename.empty())
01301     return OutDiag;
01302   OutDiag.LocOffset = SM.getFileOffset(FileLoc);
01303   for (StoredDiagnostic::range_iterator
01304          I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
01305     OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
01306   }
01307   for (StoredDiagnostic::fixit_iterator I = InDiag.fixit_begin(),
01308                                         E = InDiag.fixit_end();
01309        I != E; ++I)
01310     OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, *I));
01311 
01312   return OutDiag;
01313 }
01314 
01315 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
01316 /// the source file.
01317 ///
01318 /// This routine will compute the preamble of the main source file. If a
01319 /// non-trivial preamble is found, it will precompile that preamble into a 
01320 /// precompiled header so that the precompiled preamble can be used to reduce
01321 /// reparsing time. If a precompiled preamble has already been constructed,
01322 /// this routine will determine if it is still valid and, if so, avoid 
01323 /// rebuilding the precompiled preamble.
01324 ///
01325 /// \param AllowRebuild When true (the default), this routine is
01326 /// allowed to rebuild the precompiled preamble if it is found to be
01327 /// out-of-date.
01328 ///
01329 /// \param MaxLines When non-zero, the maximum number of lines that
01330 /// can occur within the preamble.
01331 ///
01332 /// \returns If the precompiled preamble can be used, returns a newly-allocated
01333 /// buffer that should be used in place of the main file when doing so.
01334 /// Otherwise, returns a NULL pointer.
01335 std::unique_ptr<llvm::MemoryBuffer>
01336 ASTUnit::getMainBufferWithPrecompiledPreamble(
01337     const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
01338     unsigned MaxLines) {
01339 
01340   IntrusiveRefCntPtr<CompilerInvocation>
01341     PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
01342   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
01343   PreprocessorOptions &PreprocessorOpts
01344     = PreambleInvocation->getPreprocessorOpts();
01345 
01346   ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
01347 
01348   if (!NewPreamble.Size) {
01349     // We couldn't find a preamble in the main source. Clear out the current
01350     // preamble, if we have one. It's obviously no good any more.
01351     Preamble.clear();
01352     erasePreambleFile(this);
01353 
01354     // The next time we actually see a preamble, precompile it.
01355     PreambleRebuildCounter = 1;
01356     return nullptr;
01357   }
01358   
01359   if (!Preamble.empty()) {
01360     // We've previously computed a preamble. Check whether we have the same
01361     // preamble now that we did before, and that there's enough space in
01362     // the main-file buffer within the precompiled preamble to fit the
01363     // new main file.
01364     if (Preamble.size() == NewPreamble.Size &&
01365         PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
01366         memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
01367                NewPreamble.Size) == 0) {
01368       // The preamble has not changed. We may be able to re-use the precompiled
01369       // preamble.
01370 
01371       // Check that none of the files used by the preamble have changed.
01372       bool AnyFileChanged = false;
01373           
01374       // First, make a record of those files that have been overridden via
01375       // remapping or unsaved_files.
01376       llvm::StringMap<PreambleFileHash> OverriddenFiles;
01377       for (const auto &R : PreprocessorOpts.RemappedFiles) {
01378         if (AnyFileChanged)
01379           break;
01380 
01381         vfs::Status Status;
01382         if (FileMgr->getNoncachedStatValue(R.second, Status)) {
01383           // If we can't stat the file we're remapping to, assume that something
01384           // horrible happened.
01385           AnyFileChanged = true;
01386           break;
01387         }
01388 
01389         OverriddenFiles[R.first] = PreambleFileHash::createForFile(
01390             Status.getSize(), Status.getLastModificationTime().toEpochTime());
01391       }
01392 
01393       for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
01394         if (AnyFileChanged)
01395           break;
01396         OverriddenFiles[RB.first] =
01397             PreambleFileHash::createForMemoryBuffer(RB.second);
01398       }
01399        
01400       // Check whether anything has changed.
01401       for (llvm::StringMap<PreambleFileHash>::iterator 
01402              F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
01403            !AnyFileChanged && F != FEnd; 
01404            ++F) {
01405         llvm::StringMap<PreambleFileHash>::iterator Overridden
01406           = OverriddenFiles.find(F->first());
01407         if (Overridden != OverriddenFiles.end()) {
01408           // This file was remapped; check whether the newly-mapped file 
01409           // matches up with the previous mapping.
01410           if (Overridden->second != F->second)
01411             AnyFileChanged = true;
01412           continue;
01413         }
01414         
01415         // The file was not remapped; check whether it has changed on disk.
01416         vfs::Status Status;
01417         if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
01418           // If we can't stat the file, assume that something horrible happened.
01419           AnyFileChanged = true;
01420         } else if (Status.getSize() != uint64_t(F->second.Size) ||
01421                    Status.getLastModificationTime().toEpochTime() !=
01422                        uint64_t(F->second.ModTime))
01423           AnyFileChanged = true;
01424       }
01425           
01426       if (!AnyFileChanged) {
01427         // Okay! We can re-use the precompiled preamble.
01428 
01429         // Set the state of the diagnostic object to mimic its state
01430         // after parsing the preamble.
01431         getDiagnostics().Reset();
01432         ProcessWarningOptions(getDiagnostics(), 
01433                               PreambleInvocation->getDiagnosticOpts());
01434         getDiagnostics().setNumWarnings(NumWarningsInPreamble);
01435 
01436         return llvm::MemoryBuffer::getMemBufferCopy(
01437             NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
01438       }
01439     }
01440 
01441     // If we aren't allowed to rebuild the precompiled preamble, just
01442     // return now.
01443     if (!AllowRebuild)
01444       return nullptr;
01445 
01446     // We can't reuse the previously-computed preamble. Build a new one.
01447     Preamble.clear();
01448     PreambleDiagnostics.clear();
01449     erasePreambleFile(this);
01450     PreambleRebuildCounter = 1;
01451   } else if (!AllowRebuild) {
01452     // We aren't allowed to rebuild the precompiled preamble; just
01453     // return now.
01454     return nullptr;
01455   }
01456 
01457   // If the preamble rebuild counter > 1, it's because we previously
01458   // failed to build a preamble and we're not yet ready to try
01459   // again. Decrement the counter and return a failure.
01460   if (PreambleRebuildCounter > 1) {
01461     --PreambleRebuildCounter;
01462     return nullptr;
01463   }
01464 
01465   // Create a temporary file for the precompiled preamble. In rare 
01466   // circumstances, this can fail.
01467   std::string PreamblePCHPath = GetPreamblePCHPath();
01468   if (PreamblePCHPath.empty()) {
01469     // Try again next time.
01470     PreambleRebuildCounter = 1;
01471     return nullptr;
01472   }
01473   
01474   // We did not previously compute a preamble, or it can't be reused anyway.
01475   SimpleTimer PreambleTimer(WantTiming);
01476   PreambleTimer.setOutput("Precompiling preamble");
01477 
01478   // Save the preamble text for later; we'll need to compare against it for
01479   // subsequent reparses.
01480   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
01481   Preamble.assign(FileMgr->getFile(MainFilename),
01482                   NewPreamble.Buffer->getBufferStart(),
01483                   NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
01484   PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
01485 
01486   PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
01487       NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
01488 
01489   // Remap the main source file to the preamble buffer.
01490   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
01491   PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
01492 
01493   // Tell the compiler invocation to generate a temporary precompiled header.
01494   FrontendOpts.ProgramAction = frontend::GeneratePCH;
01495   // FIXME: Generate the precompiled header into memory?
01496   FrontendOpts.OutputFile = PreamblePCHPath;
01497   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
01498   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
01499   
01500   // Create the compiler instance to use for building the precompiled preamble.
01501   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
01502 
01503   // Recover resources if we crash before exiting this method.
01504   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
01505     CICleanup(Clang.get());
01506 
01507   Clang->setInvocation(&*PreambleInvocation);
01508   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
01509   
01510   // Set up diagnostics, capturing all of the diagnostics produced.
01511   Clang->setDiagnostics(&getDiagnostics());
01512   
01513   // Create the target instance.
01514   Clang->setTarget(TargetInfo::CreateTargetInfo(
01515       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
01516   if (!Clang->hasTarget()) {
01517     llvm::sys::fs::remove(FrontendOpts.OutputFile);
01518     Preamble.clear();
01519     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
01520     PreprocessorOpts.RemappedFileBuffers.pop_back();
01521     return nullptr;
01522   }
01523   
01524   // Inform the target of the language options.
01525   //
01526   // FIXME: We shouldn't need to do this, the target should be immutable once
01527   // created. This complexity should be lifted elsewhere.
01528   Clang->getTarget().adjust(Clang->getLangOpts());
01529   
01530   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
01531          "Invocation must have exactly one source file!");
01532   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
01533          "FIXME: AST inputs not yet supported here!");
01534   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
01535          "IR inputs not support here!");
01536   
01537   // Clear out old caches and data.
01538   getDiagnostics().Reset();
01539   ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
01540   checkAndRemoveNonDriverDiags(StoredDiagnostics);
01541   TopLevelDecls.clear();
01542   TopLevelDeclsInPreamble.clear();
01543   PreambleDiagnostics.clear();
01544 
01545   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
01546       createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
01547   if (!VFS)
01548     return nullptr;
01549 
01550   // Create a file manager object to provide access to and cache the filesystem.
01551   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
01552   
01553   // Create the source manager.
01554   Clang->setSourceManager(new SourceManager(getDiagnostics(),
01555                                             Clang->getFileManager()));
01556 
01557   auto PreambleDepCollector = std::make_shared<DependencyCollector>();
01558   Clang->addDependencyCollector(PreambleDepCollector);
01559 
01560   std::unique_ptr<PrecompilePreambleAction> Act;
01561   Act.reset(new PrecompilePreambleAction(*this));
01562   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
01563     llvm::sys::fs::remove(FrontendOpts.OutputFile);
01564     Preamble.clear();
01565     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
01566     PreprocessorOpts.RemappedFileBuffers.pop_back();
01567     return nullptr;
01568   }
01569   
01570   Act->Execute();
01571 
01572   // Transfer any diagnostics generated when parsing the preamble into the set
01573   // of preamble diagnostics.
01574   for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
01575                             E = stored_diag_end();
01576        I != E; ++I)
01577     PreambleDiagnostics.push_back(
01578         makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
01579 
01580   Act->EndSourceFile();
01581 
01582   checkAndRemoveNonDriverDiags(StoredDiagnostics);
01583 
01584   if (!Act->hasEmittedPreamblePCH()) {
01585     // The preamble PCH failed (e.g. there was a module loading fatal error),
01586     // so no precompiled header was generated. Forget that we even tried.
01587     // FIXME: Should we leave a note for ourselves to try again?
01588     llvm::sys::fs::remove(FrontendOpts.OutputFile);
01589     Preamble.clear();
01590     TopLevelDeclsInPreamble.clear();
01591     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
01592     PreprocessorOpts.RemappedFileBuffers.pop_back();
01593     return nullptr;
01594   }
01595   
01596   // Keep track of the preamble we precompiled.
01597   setPreambleFile(this, FrontendOpts.OutputFile);
01598   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
01599   
01600   // Keep track of all of the files that the source manager knows about,
01601   // so we can verify whether they have changed or not.
01602   FilesInPreamble.clear();
01603   SourceManager &SourceMgr = Clang->getSourceManager();
01604   for (auto &Filename : PreambleDepCollector->getDependencies()) {
01605     const FileEntry *File = Clang->getFileManager().getFile(Filename);
01606     if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
01607       continue;
01608     if (time_t ModTime = File->getModificationTime()) {
01609       FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
01610           File->getSize(), ModTime);
01611     } else {
01612       llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
01613       FilesInPreamble[File->getName()] =
01614           PreambleFileHash::createForMemoryBuffer(Buffer);
01615     }
01616   }
01617 
01618   PreambleRebuildCounter = 1;
01619   PreprocessorOpts.RemappedFileBuffers.pop_back();
01620 
01621   // If the hash of top-level entities differs from the hash of the top-level
01622   // entities the last time we rebuilt the preamble, clear out the completion
01623   // cache.
01624   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
01625     CompletionCacheTopLevelHashValue = 0;
01626     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
01627   }
01628 
01629   return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
01630                                               MainFilename);
01631 }
01632 
01633 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
01634   std::vector<Decl *> Resolved;
01635   Resolved.reserve(TopLevelDeclsInPreamble.size());
01636   ExternalASTSource &Source = *getASTContext().getExternalSource();
01637   for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
01638     // Resolve the declaration ID to an actual declaration, possibly
01639     // deserializing the declaration in the process.
01640     Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
01641     if (D)
01642       Resolved.push_back(D);
01643   }
01644   TopLevelDeclsInPreamble.clear();
01645   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
01646 }
01647 
01648 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
01649   // Steal the created target, context, and preprocessor if they have been
01650   // created.
01651   assert(CI.hasInvocation() && "missing invocation");
01652   LangOpts = CI.getInvocation().LangOpts;
01653   TheSema = CI.takeSema();
01654   Consumer = CI.takeASTConsumer();
01655   if (CI.hasASTContext())
01656     Ctx = &CI.getASTContext();
01657   if (CI.hasPreprocessor())
01658     PP = &CI.getPreprocessor();
01659   CI.setSourceManager(nullptr);
01660   CI.setFileManager(nullptr);
01661   if (CI.hasTarget())
01662     Target = &CI.getTarget();
01663   Reader = CI.getModuleManager();
01664   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
01665 }
01666 
01667 StringRef ASTUnit::getMainFileName() const {
01668   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
01669     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
01670     if (Input.isFile())
01671       return Input.getFile();
01672     else
01673       return Input.getBuffer()->getBufferIdentifier();
01674   }
01675 
01676   if (SourceMgr) {
01677     if (const FileEntry *
01678           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
01679       return FE->getName();
01680   }
01681 
01682   return StringRef();
01683 }
01684 
01685 StringRef ASTUnit::getASTFileName() const {
01686   if (!isMainFileAST())
01687     return StringRef();
01688 
01689   serialization::ModuleFile &
01690     Mod = Reader->getModuleManager().getPrimaryModule();
01691   return Mod.FileName;
01692 }
01693 
01694 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
01695                          IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
01696                          bool CaptureDiagnostics,
01697                          bool UserFilesAreVolatile) {
01698   std::unique_ptr<ASTUnit> AST;
01699   AST.reset(new ASTUnit(false));
01700   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
01701   AST->Diagnostics = Diags;
01702   AST->Invocation = CI;
01703   AST->FileSystemOpts = CI->getFileSystemOpts();
01704   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
01705       createVFSFromCompilerInvocation(*CI, *Diags);
01706   if (!VFS)
01707     return nullptr;
01708   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
01709   AST->UserFilesAreVolatile = UserFilesAreVolatile;
01710   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
01711                                      UserFilesAreVolatile);
01712 
01713   return AST.release();
01714 }
01715 
01716 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
01717     CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
01718     ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
01719     StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
01720     bool PrecompilePreamble, bool CacheCodeCompletionResults,
01721     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
01722     std::unique_ptr<ASTUnit> *ErrAST) {
01723   assert(CI && "A CompilerInvocation is required");
01724 
01725   std::unique_ptr<ASTUnit> OwnAST;
01726   ASTUnit *AST = Unit;
01727   if (!AST) {
01728     // Create the AST unit.
01729     OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
01730     AST = OwnAST.get();
01731     if (!AST)
01732       return nullptr;
01733   }
01734   
01735   if (!ResourceFilesPath.empty()) {
01736     // Override the resources path.
01737     CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
01738   }
01739   AST->OnlyLocalDecls = OnlyLocalDecls;
01740   AST->CaptureDiagnostics = CaptureDiagnostics;
01741   if (PrecompilePreamble)
01742     AST->PreambleRebuildCounter = 2;
01743   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
01744   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
01745   AST->IncludeBriefCommentsInCodeCompletion
01746     = IncludeBriefCommentsInCodeCompletion;
01747 
01748   // Recover resources if we crash before exiting this method.
01749   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
01750     ASTUnitCleanup(OwnAST.get());
01751   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
01752     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
01753     DiagCleanup(Diags.get());
01754 
01755   // We'll manage file buffers ourselves.
01756   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
01757   CI->getFrontendOpts().DisableFree = false;
01758   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
01759 
01760   // Create the compiler instance to use for building the AST.
01761   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
01762 
01763   // Recover resources if we crash before exiting this method.
01764   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
01765     CICleanup(Clang.get());
01766 
01767   Clang->setInvocation(CI);
01768   AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
01769     
01770   // Set up diagnostics, capturing any diagnostics that would
01771   // otherwise be dropped.
01772   Clang->setDiagnostics(&AST->getDiagnostics());
01773   
01774   // Create the target instance.
01775   Clang->setTarget(TargetInfo::CreateTargetInfo(
01776       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
01777   if (!Clang->hasTarget())
01778     return nullptr;
01779 
01780   // Inform the target of the language options.
01781   //
01782   // FIXME: We shouldn't need to do this, the target should be immutable once
01783   // created. This complexity should be lifted elsewhere.
01784   Clang->getTarget().adjust(Clang->getLangOpts());
01785   
01786   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
01787          "Invocation must have exactly one source file!");
01788   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
01789          "FIXME: AST inputs not yet supported here!");
01790   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
01791          "IR inputs not supported here!");
01792 
01793   // Configure the various subsystems.
01794   AST->TheSema.reset();
01795   AST->Ctx = nullptr;
01796   AST->PP = nullptr;
01797   AST->Reader = nullptr;
01798 
01799   // Create a file manager object to provide access to and cache the filesystem.
01800   Clang->setFileManager(&AST->getFileManager());
01801   
01802   // Create the source manager.
01803   Clang->setSourceManager(&AST->getSourceManager());
01804 
01805   ASTFrontendAction *Act = Action;
01806 
01807   std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
01808   if (!Act) {
01809     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
01810     Act = TrackerAct.get();
01811   }
01812 
01813   // Recover resources if we crash before exiting this method.
01814   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
01815     ActCleanup(TrackerAct.get());
01816 
01817   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
01818     AST->transferASTDataFromCompilerInstance(*Clang);
01819     if (OwnAST && ErrAST)
01820       ErrAST->swap(OwnAST);
01821 
01822     return nullptr;
01823   }
01824 
01825   if (Persistent && !TrackerAct) {
01826     Clang->getPreprocessor().addPPCallbacks(
01827         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
01828                                            AST->getCurrentTopLevelHashValue()));
01829     std::vector<std::unique_ptr<ASTConsumer>> Consumers;
01830     if (Clang->hasASTConsumer())
01831       Consumers.push_back(Clang->takeASTConsumer());
01832     Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
01833         *AST, AST->getCurrentTopLevelHashValue()));
01834     Clang->setASTConsumer(
01835         llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
01836   }
01837   if (!Act->Execute()) {
01838     AST->transferASTDataFromCompilerInstance(*Clang);
01839     if (OwnAST && ErrAST)
01840       ErrAST->swap(OwnAST);
01841 
01842     return nullptr;
01843   }
01844 
01845   // Steal the created target, context, and preprocessor.
01846   AST->transferASTDataFromCompilerInstance(*Clang);
01847   
01848   Act->EndSourceFile();
01849 
01850   if (OwnAST)
01851     return OwnAST.release();
01852   else
01853     return AST;
01854 }
01855 
01856 bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
01857   if (!Invocation)
01858     return true;
01859   
01860   // We'll manage file buffers ourselves.
01861   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
01862   Invocation->getFrontendOpts().DisableFree = false;
01863   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
01864 
01865   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
01866   if (PrecompilePreamble) {
01867     PreambleRebuildCounter = 2;
01868     OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
01869   }
01870   
01871   SimpleTimer ParsingTimer(WantTiming);
01872   ParsingTimer.setOutput("Parsing " + getMainFileName());
01873   
01874   // Recover resources if we crash before exiting this method.
01875   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
01876     MemBufferCleanup(OverrideMainBuffer.get());
01877 
01878   return Parse(std::move(OverrideMainBuffer));
01879 }
01880 
01881 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
01882     CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
01883     bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
01884     TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
01885     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
01886   // Create the AST unit.
01887   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
01888   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
01889   AST->Diagnostics = Diags;
01890   AST->OnlyLocalDecls = OnlyLocalDecls;
01891   AST->CaptureDiagnostics = CaptureDiagnostics;
01892   AST->TUKind = TUKind;
01893   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
01894   AST->IncludeBriefCommentsInCodeCompletion
01895     = IncludeBriefCommentsInCodeCompletion;
01896   AST->Invocation = CI;
01897   AST->FileSystemOpts = CI->getFileSystemOpts();
01898   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
01899       createVFSFromCompilerInvocation(*CI, *Diags);
01900   if (!VFS)
01901     return nullptr;
01902   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
01903   AST->UserFilesAreVolatile = UserFilesAreVolatile;
01904   
01905   // Recover resources if we crash before exiting this method.
01906   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
01907     ASTUnitCleanup(AST.get());
01908   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
01909     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
01910     DiagCleanup(Diags.get());
01911 
01912   if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
01913     return nullptr;
01914   return AST;
01915 }
01916 
01917 ASTUnit *ASTUnit::LoadFromCommandLine(
01918     const char **ArgBegin, const char **ArgEnd,
01919     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
01920     bool OnlyLocalDecls, bool CaptureDiagnostics,
01921     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
01922     bool PrecompilePreamble, TranslationUnitKind TUKind,
01923     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
01924     bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
01925     bool UserFilesAreVolatile, bool ForSerialization,
01926     std::unique_ptr<ASTUnit> *ErrAST) {
01927   assert(Diags.get() && "no DiagnosticsEngine was provided");
01928 
01929   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
01930   
01931   IntrusiveRefCntPtr<CompilerInvocation> CI;
01932 
01933   {
01934 
01935     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, 
01936                                       StoredDiagnostics);
01937 
01938     CI = clang::createInvocationFromCommandLine(
01939                                            llvm::makeArrayRef(ArgBegin, ArgEnd),
01940                                            Diags);
01941     if (!CI)
01942       return nullptr;
01943   }
01944 
01945   // Override any files that need remapping
01946   for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
01947     CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
01948                                               RemappedFiles[I].second);
01949   }
01950   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
01951   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
01952   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
01953   
01954   // Override the resources path.
01955   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
01956 
01957   CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
01958 
01959   // Create the AST unit.
01960   std::unique_ptr<ASTUnit> AST;
01961   AST.reset(new ASTUnit(false));
01962   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
01963   AST->Diagnostics = Diags;
01964   AST->FileSystemOpts = CI->getFileSystemOpts();
01965   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
01966       createVFSFromCompilerInvocation(*CI, *Diags);
01967   if (!VFS)
01968     return nullptr;
01969   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
01970   AST->OnlyLocalDecls = OnlyLocalDecls;
01971   AST->CaptureDiagnostics = CaptureDiagnostics;
01972   AST->TUKind = TUKind;
01973   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
01974   AST->IncludeBriefCommentsInCodeCompletion
01975     = IncludeBriefCommentsInCodeCompletion;
01976   AST->UserFilesAreVolatile = UserFilesAreVolatile;
01977   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
01978   AST->StoredDiagnostics.swap(StoredDiagnostics);
01979   AST->Invocation = CI;
01980   if (ForSerialization)
01981     AST->WriterData.reset(new ASTWriterData());
01982   // Zero out now to ease cleanup during crash recovery.
01983   CI = nullptr;
01984   Diags = nullptr;
01985 
01986   // Recover resources if we crash before exiting this method.
01987   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
01988     ASTUnitCleanup(AST.get());
01989 
01990   if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
01991     // Some error occurred, if caller wants to examine diagnostics, pass it the
01992     // ASTUnit.
01993     if (ErrAST) {
01994       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
01995       ErrAST->swap(AST);
01996     }
01997     return nullptr;
01998   }
01999 
02000   return AST.release();
02001 }
02002 
02003 bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
02004   if (!Invocation)
02005     return true;
02006 
02007   clearFileLevelDecls();
02008   
02009   SimpleTimer ParsingTimer(WantTiming);
02010   ParsingTimer.setOutput("Reparsing " + getMainFileName());
02011 
02012   // Remap files.
02013   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
02014   for (const auto &RB : PPOpts.RemappedFileBuffers)
02015     delete RB.second;
02016 
02017   Invocation->getPreprocessorOpts().clearRemappedFiles();
02018   for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
02019     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
02020                                                       RemappedFiles[I].second);
02021   }
02022 
02023   // If we have a preamble file lying around, or if we might try to
02024   // build a precompiled preamble, do so now.
02025   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
02026   if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
02027     OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
02028     
02029   // Clear out the diagnostics state.
02030   getDiagnostics().Reset();
02031   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
02032   if (OverrideMainBuffer)
02033     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
02034 
02035   // Parse the sources
02036   bool Result = Parse(std::move(OverrideMainBuffer));
02037 
02038   // If we're caching global code-completion results, and the top-level 
02039   // declarations have changed, clear out the code-completion cache.
02040   if (!Result && ShouldCacheCodeCompletionResults &&
02041       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
02042     CacheCodeCompletionResults();
02043 
02044   // We now need to clear out the completion info related to this translation
02045   // unit; it'll be recreated if necessary.
02046   CCTUInfo.reset();
02047   
02048   return Result;
02049 }
02050 
02051 //----------------------------------------------------------------------------//
02052 // Code completion
02053 //----------------------------------------------------------------------------//
02054 
02055 namespace {
02056   /// \brief Code completion consumer that combines the cached code-completion
02057   /// results from an ASTUnit with the code-completion results provided to it,
02058   /// then passes the result on to 
02059   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
02060     uint64_t NormalContexts;
02061     ASTUnit &AST;
02062     CodeCompleteConsumer &Next;
02063     
02064   public:
02065     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
02066                                   const CodeCompleteOptions &CodeCompleteOpts)
02067       : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
02068         AST(AST), Next(Next)
02069     { 
02070       // Compute the set of contexts in which we will look when we don't have
02071       // any information about the specific context.
02072       NormalContexts 
02073         = (1LL << CodeCompletionContext::CCC_TopLevel)
02074         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
02075         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
02076         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
02077         | (1LL << CodeCompletionContext::CCC_Statement)
02078         | (1LL << CodeCompletionContext::CCC_Expression)
02079         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
02080         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
02081         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
02082         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
02083         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
02084         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
02085         | (1LL << CodeCompletionContext::CCC_Recovery);
02086 
02087       if (AST.getASTContext().getLangOpts().CPlusPlus)
02088         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
02089                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
02090                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
02091     }
02092 
02093     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
02094                                     CodeCompletionResult *Results,
02095                                     unsigned NumResults) override;
02096 
02097     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
02098                                    OverloadCandidate *Candidates,
02099                                    unsigned NumCandidates) override {
02100       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
02101     }
02102 
02103     CodeCompletionAllocator &getAllocator() override {
02104       return Next.getAllocator();
02105     }
02106 
02107     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
02108       return Next.getCodeCompletionTUInfo();
02109     }
02110   };
02111 }
02112 
02113 /// \brief Helper function that computes which global names are hidden by the
02114 /// local code-completion results.
02115 static void CalculateHiddenNames(const CodeCompletionContext &Context,
02116                                  CodeCompletionResult *Results,
02117                                  unsigned NumResults,
02118                                  ASTContext &Ctx,
02119                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
02120   bool OnlyTagNames = false;
02121   switch (Context.getKind()) {
02122   case CodeCompletionContext::CCC_Recovery:
02123   case CodeCompletionContext::CCC_TopLevel:
02124   case CodeCompletionContext::CCC_ObjCInterface:
02125   case CodeCompletionContext::CCC_ObjCImplementation:
02126   case CodeCompletionContext::CCC_ObjCIvarList:
02127   case CodeCompletionContext::CCC_ClassStructUnion:
02128   case CodeCompletionContext::CCC_Statement:
02129   case CodeCompletionContext::CCC_Expression:
02130   case CodeCompletionContext::CCC_ObjCMessageReceiver:
02131   case CodeCompletionContext::CCC_DotMemberAccess:
02132   case CodeCompletionContext::CCC_ArrowMemberAccess:
02133   case CodeCompletionContext::CCC_ObjCPropertyAccess:
02134   case CodeCompletionContext::CCC_Namespace:
02135   case CodeCompletionContext::CCC_Type:
02136   case CodeCompletionContext::CCC_Name:
02137   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
02138   case CodeCompletionContext::CCC_ParenthesizedExpression:
02139   case CodeCompletionContext::CCC_ObjCInterfaceName:
02140     break;
02141     
02142   case CodeCompletionContext::CCC_EnumTag:
02143   case CodeCompletionContext::CCC_UnionTag:
02144   case CodeCompletionContext::CCC_ClassOrStructTag:
02145     OnlyTagNames = true;
02146     break;
02147     
02148   case CodeCompletionContext::CCC_ObjCProtocolName:
02149   case CodeCompletionContext::CCC_MacroName:
02150   case CodeCompletionContext::CCC_MacroNameUse:
02151   case CodeCompletionContext::CCC_PreprocessorExpression:
02152   case CodeCompletionContext::CCC_PreprocessorDirective:
02153   case CodeCompletionContext::CCC_NaturalLanguage:
02154   case CodeCompletionContext::CCC_SelectorName:
02155   case CodeCompletionContext::CCC_TypeQualifiers:
02156   case CodeCompletionContext::CCC_Other:
02157   case CodeCompletionContext::CCC_OtherWithMacros:
02158   case CodeCompletionContext::CCC_ObjCInstanceMessage:
02159   case CodeCompletionContext::CCC_ObjCClassMessage:
02160   case CodeCompletionContext::CCC_ObjCCategoryName:
02161     // We're looking for nothing, or we're looking for names that cannot
02162     // be hidden.
02163     return;
02164   }
02165   
02166   typedef CodeCompletionResult Result;
02167   for (unsigned I = 0; I != NumResults; ++I) {
02168     if (Results[I].Kind != Result::RK_Declaration)
02169       continue;
02170     
02171     unsigned IDNS
02172       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
02173 
02174     bool Hiding = false;
02175     if (OnlyTagNames)
02176       Hiding = (IDNS & Decl::IDNS_Tag);
02177     else {
02178       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 
02179                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
02180                              Decl::IDNS_NonMemberOperator);
02181       if (Ctx.getLangOpts().CPlusPlus)
02182         HiddenIDNS |= Decl::IDNS_Tag;
02183       Hiding = (IDNS & HiddenIDNS);
02184     }
02185   
02186     if (!Hiding)
02187       continue;
02188     
02189     DeclarationName Name = Results[I].Declaration->getDeclName();
02190     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
02191       HiddenNames.insert(Identifier->getName());
02192     else
02193       HiddenNames.insert(Name.getAsString());
02194   }
02195 }
02196 
02197 
02198 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
02199                                             CodeCompletionContext Context,
02200                                             CodeCompletionResult *Results,
02201                                             unsigned NumResults) { 
02202   // Merge the results we were given with the results we cached.
02203   bool AddedResult = false;
02204   uint64_t InContexts =
02205       Context.getKind() == CodeCompletionContext::CCC_Recovery
02206         ? NormalContexts : (1LL << Context.getKind());
02207   // Contains the set of names that are hidden by "local" completion results.
02208   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
02209   typedef CodeCompletionResult Result;
02210   SmallVector<Result, 8> AllResults;
02211   for (ASTUnit::cached_completion_iterator 
02212             C = AST.cached_completion_begin(),
02213          CEnd = AST.cached_completion_end();
02214        C != CEnd; ++C) {
02215     // If the context we are in matches any of the contexts we are 
02216     // interested in, we'll add this result.
02217     if ((C->ShowInContexts & InContexts) == 0)
02218       continue;
02219     
02220     // If we haven't added any results previously, do so now.
02221     if (!AddedResult) {
02222       CalculateHiddenNames(Context, Results, NumResults, S.Context, 
02223                            HiddenNames);
02224       AllResults.insert(AllResults.end(), Results, Results + NumResults);
02225       AddedResult = true;
02226     }
02227     
02228     // Determine whether this global completion result is hidden by a local
02229     // completion result. If so, skip it.
02230     if (C->Kind != CXCursor_MacroDefinition &&
02231         HiddenNames.count(C->Completion->getTypedText()))
02232       continue;
02233     
02234     // Adjust priority based on similar type classes.
02235     unsigned Priority = C->Priority;
02236     CodeCompletionString *Completion = C->Completion;
02237     if (!Context.getPreferredType().isNull()) {
02238       if (C->Kind == CXCursor_MacroDefinition) {
02239         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
02240                                          S.getLangOpts(),
02241                                Context.getPreferredType()->isAnyPointerType());        
02242       } else if (C->Type) {
02243         CanQualType Expected
02244           = S.Context.getCanonicalType(
02245                                Context.getPreferredType().getUnqualifiedType());
02246         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
02247         if (ExpectedSTC == C->TypeClass) {
02248           // We know this type is similar; check for an exact match.
02249           llvm::StringMap<unsigned> &CachedCompletionTypes
02250             = AST.getCachedCompletionTypes();
02251           llvm::StringMap<unsigned>::iterator Pos
02252             = CachedCompletionTypes.find(QualType(Expected).getAsString());
02253           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
02254             Priority /= CCF_ExactTypeMatch;
02255           else
02256             Priority /= CCF_SimilarTypeMatch;
02257         }
02258       }
02259     }
02260     
02261     // Adjust the completion string, if required.
02262     if (C->Kind == CXCursor_MacroDefinition &&
02263         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
02264       // Create a new code-completion string that just contains the
02265       // macro name, without its arguments.
02266       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
02267                                     CCP_CodePattern, C->Availability);
02268       Builder.AddTypedTextChunk(C->Completion->getTypedText());
02269       Priority = CCP_CodePattern;
02270       Completion = Builder.TakeString();
02271     }
02272     
02273     AllResults.push_back(Result(Completion, Priority, C->Kind,
02274                                 C->Availability));
02275   }
02276   
02277   // If we did not add any cached completion results, just forward the
02278   // results we were given to the next consumer.
02279   if (!AddedResult) {
02280     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
02281     return;
02282   }
02283   
02284   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
02285                                   AllResults.size());
02286 }
02287 
02288 
02289 
02290 void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
02291                            ArrayRef<RemappedFile> RemappedFiles,
02292                            bool IncludeMacros, 
02293                            bool IncludeCodePatterns,
02294                            bool IncludeBriefComments,
02295                            CodeCompleteConsumer &Consumer,
02296                            DiagnosticsEngine &Diag, LangOptions &LangOpts,
02297                            SourceManager &SourceMgr, FileManager &FileMgr,
02298                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
02299              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
02300   if (!Invocation)
02301     return;
02302 
02303   SimpleTimer CompletionTimer(WantTiming);
02304   CompletionTimer.setOutput("Code completion @ " + File + ":" +
02305                             Twine(Line) + ":" + Twine(Column));
02306 
02307   IntrusiveRefCntPtr<CompilerInvocation>
02308     CCInvocation(new CompilerInvocation(*Invocation));
02309 
02310   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
02311   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
02312   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
02313 
02314   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
02315                                    CachedCompletionResults.empty();
02316   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
02317   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
02318   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
02319 
02320   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
02321 
02322   FrontendOpts.CodeCompletionAt.FileName = File;
02323   FrontendOpts.CodeCompletionAt.Line = Line;
02324   FrontendOpts.CodeCompletionAt.Column = Column;
02325 
02326   // Set the language options appropriately.
02327   LangOpts = *CCInvocation->getLangOpts();
02328 
02329   // Spell-checking and warnings are wasteful during code-completion.
02330   LangOpts.SpellChecking = false;
02331   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
02332 
02333   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
02334 
02335   // Recover resources if we crash before exiting this method.
02336   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
02337     CICleanup(Clang.get());
02338 
02339   Clang->setInvocation(&*CCInvocation);
02340   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
02341     
02342   // Set up diagnostics, capturing any diagnostics produced.
02343   Clang->setDiagnostics(&Diag);
02344   CaptureDroppedDiagnostics Capture(true, 
02345                                     Clang->getDiagnostics(), 
02346                                     StoredDiagnostics);
02347   ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
02348   
02349   // Create the target instance.
02350   Clang->setTarget(TargetInfo::CreateTargetInfo(
02351       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
02352   if (!Clang->hasTarget()) {
02353     Clang->setInvocation(nullptr);
02354     return;
02355   }
02356   
02357   // Inform the target of the language options.
02358   //
02359   // FIXME: We shouldn't need to do this, the target should be immutable once
02360   // created. This complexity should be lifted elsewhere.
02361   Clang->getTarget().adjust(Clang->getLangOpts());
02362   
02363   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
02364          "Invocation must have exactly one source file!");
02365   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
02366          "FIXME: AST inputs not yet supported here!");
02367   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
02368          "IR inputs not support here!");
02369 
02370   
02371   // Use the source and file managers that we were given.
02372   Clang->setFileManager(&FileMgr);
02373   Clang->setSourceManager(&SourceMgr);
02374 
02375   // Remap files.
02376   PreprocessorOpts.clearRemappedFiles();
02377   PreprocessorOpts.RetainRemappedFileBuffers = true;
02378   for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
02379     PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
02380                                      RemappedFiles[I].second);
02381     OwnedBuffers.push_back(RemappedFiles[I].second);
02382   }
02383 
02384   // Use the code completion consumer we were given, but adding any cached
02385   // code-completion results.
02386   AugmentedCodeCompleteConsumer *AugmentedConsumer
02387     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
02388   Clang->setCodeCompletionConsumer(AugmentedConsumer);
02389 
02390   // If we have a precompiled preamble, try to use it. We only allow
02391   // the use of the precompiled preamble if we're if the completion
02392   // point is within the main file, after the end of the precompiled
02393   // preamble.
02394   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
02395   if (!getPreambleFile(this).empty()) {
02396     std::string CompleteFilePath(File);
02397     llvm::sys::fs::UniqueID CompleteFileID;
02398 
02399     if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
02400       std::string MainPath(OriginalSourceFile);
02401       llvm::sys::fs::UniqueID MainID;
02402       if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
02403         if (CompleteFileID == MainID && Line > 1)
02404           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
02405               *CCInvocation, false, Line - 1);
02406       }
02407     }
02408   }
02409 
02410   // If the main file has been overridden due to the use of a preamble,
02411   // make that override happen and introduce the preamble.
02412   if (OverrideMainBuffer) {
02413     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
02414                                      OverrideMainBuffer.get());
02415     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
02416     PreprocessorOpts.PrecompiledPreambleBytes.second
02417                                                     = PreambleEndsAtStartOfLine;
02418     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
02419     PreprocessorOpts.DisablePCHValidation = true;
02420 
02421     OwnedBuffers.push_back(OverrideMainBuffer.release());
02422   } else {
02423     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
02424     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
02425   }
02426 
02427   // Disable the preprocessing record if modules are not enabled.
02428   if (!Clang->getLangOpts().Modules)
02429     PreprocessorOpts.DetailedRecord = false;
02430 
02431   std::unique_ptr<SyntaxOnlyAction> Act;
02432   Act.reset(new SyntaxOnlyAction);
02433   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
02434     Act->Execute();
02435     Act->EndSourceFile();
02436   }
02437 }
02438 
02439 bool ASTUnit::Save(StringRef File) {
02440   if (HadModuleLoaderFatalFailure)
02441     return true;
02442 
02443   // Write to a temporary file and later rename it to the actual file, to avoid
02444   // possible race conditions.
02445   SmallString<128> TempPath;
02446   TempPath = File;
02447   TempPath += "-%%%%%%%%";
02448   int fd;
02449   if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
02450     return true;
02451 
02452   // FIXME: Can we somehow regenerate the stat cache here, or do we need to 
02453   // unconditionally create a stat cache when we parse the file?
02454   llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
02455 
02456   serialize(Out);
02457   Out.close();
02458   if (Out.has_error()) {
02459     Out.clear_error();
02460     return true;
02461   }
02462 
02463   if (llvm::sys::fs::rename(TempPath.str(), File)) {
02464     llvm::sys::fs::remove(TempPath.str());
02465     return true;
02466   }
02467 
02468   return false;
02469 }
02470 
02471 static bool serializeUnit(ASTWriter &Writer,
02472                           SmallVectorImpl<char> &Buffer,
02473                           Sema &S,
02474                           bool hasErrors,
02475                           raw_ostream &OS) {
02476   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
02477 
02478   // Write the generated bitstream to "Out".
02479   if (!Buffer.empty())
02480     OS.write(Buffer.data(), Buffer.size());
02481 
02482   return false;
02483 }
02484 
02485 bool ASTUnit::serialize(raw_ostream &OS) {
02486   bool hasErrors = getDiagnostics().hasErrorOccurred();
02487 
02488   if (WriterData)
02489     return serializeUnit(WriterData->Writer, WriterData->Buffer,
02490                          getSema(), hasErrors, OS);
02491 
02492   SmallString<128> Buffer;
02493   llvm::BitstreamWriter Stream(Buffer);
02494   ASTWriter Writer(Stream);
02495   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
02496 }
02497 
02498 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
02499 
02500 void ASTUnit::TranslateStoredDiagnostics(
02501                           FileManager &FileMgr,
02502                           SourceManager &SrcMgr,
02503                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
02504                           SmallVectorImpl<StoredDiagnostic> &Out) {
02505   // Map the standalone diagnostic into the new source manager. We also need to
02506   // remap all the locations to the new view. This includes the diag location,
02507   // any associated source ranges, and the source ranges of associated fix-its.
02508   // FIXME: There should be a cleaner way to do this.
02509 
02510   SmallVector<StoredDiagnostic, 4> Result;
02511   Result.reserve(Diags.size());
02512   for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
02513     // Rebuild the StoredDiagnostic.
02514     const StandaloneDiagnostic &SD = Diags[I];
02515     if (SD.Filename.empty())
02516       continue;
02517     const FileEntry *FE = FileMgr.getFile(SD.Filename);
02518     if (!FE)
02519       continue;
02520     FileID FID = SrcMgr.translateFile(FE);
02521     SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
02522     if (FileLoc.isInvalid())
02523       continue;
02524     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
02525     FullSourceLoc Loc(L, SrcMgr);
02526 
02527     SmallVector<CharSourceRange, 4> Ranges;
02528     Ranges.reserve(SD.Ranges.size());
02529     for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
02530            I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
02531       SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
02532       SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
02533       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
02534     }
02535 
02536     SmallVector<FixItHint, 2> FixIts;
02537     FixIts.reserve(SD.FixIts.size());
02538     for (std::vector<StandaloneFixIt>::const_iterator
02539            I = SD.FixIts.begin(), E = SD.FixIts.end();
02540          I != E; ++I) {
02541       FixIts.push_back(FixItHint());
02542       FixItHint &FH = FixIts.back();
02543       FH.CodeToInsert = I->CodeToInsert;
02544       SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
02545       SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
02546       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
02547     }
02548 
02549     Result.push_back(StoredDiagnostic(SD.Level, SD.ID, 
02550                                       SD.Message, Loc, Ranges, FixIts));
02551   }
02552   Result.swap(Out);
02553 }
02554 
02555 void ASTUnit::addFileLevelDecl(Decl *D) {
02556   assert(D);
02557   
02558   // We only care about local declarations.
02559   if (D->isFromASTFile())
02560     return;
02561 
02562   SourceManager &SM = *SourceMgr;
02563   SourceLocation Loc = D->getLocation();
02564   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
02565     return;
02566 
02567   // We only keep track of the file-level declarations of each file.
02568   if (!D->getLexicalDeclContext()->isFileContext())
02569     return;
02570 
02571   SourceLocation FileLoc = SM.getFileLoc(Loc);
02572   assert(SM.isLocalSourceLocation(FileLoc));
02573   FileID FID;
02574   unsigned Offset;
02575   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
02576   if (FID.isInvalid())
02577     return;
02578 
02579   LocDeclsTy *&Decls = FileDecls[FID];
02580   if (!Decls)
02581     Decls = new LocDeclsTy();
02582 
02583   std::pair<unsigned, Decl *> LocDecl(Offset, D);
02584 
02585   if (Decls->empty() || Decls->back().first <= Offset) {
02586     Decls->push_back(LocDecl);
02587     return;
02588   }
02589 
02590   LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
02591                                             LocDecl, llvm::less_first());
02592 
02593   Decls->insert(I, LocDecl);
02594 }
02595 
02596 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
02597                                   SmallVectorImpl<Decl *> &Decls) {
02598   if (File.isInvalid())
02599     return;
02600 
02601   if (SourceMgr->isLoadedFileID(File)) {
02602     assert(Ctx->getExternalSource() && "No external source!");
02603     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
02604                                                          Decls);
02605   }
02606 
02607   FileDeclsTy::iterator I = FileDecls.find(File);
02608   if (I == FileDecls.end())
02609     return;
02610 
02611   LocDeclsTy &LocDecls = *I->second;
02612   if (LocDecls.empty())
02613     return;
02614 
02615   LocDeclsTy::iterator BeginIt =
02616       std::lower_bound(LocDecls.begin(), LocDecls.end(),
02617                        std::make_pair(Offset, (Decl *)nullptr),
02618                        llvm::less_first());
02619   if (BeginIt != LocDecls.begin())
02620     --BeginIt;
02621 
02622   // If we are pointing at a top-level decl inside an objc container, we need
02623   // to backtrack until we find it otherwise we will fail to report that the
02624   // region overlaps with an objc container.
02625   while (BeginIt != LocDecls.begin() &&
02626          BeginIt->second->isTopLevelDeclInObjCContainer())
02627     --BeginIt;
02628 
02629   LocDeclsTy::iterator EndIt = std::upper_bound(
02630       LocDecls.begin(), LocDecls.end(),
02631       std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
02632   if (EndIt != LocDecls.end())
02633     ++EndIt;
02634   
02635   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
02636     Decls.push_back(DIt->second);
02637 }
02638 
02639 SourceLocation ASTUnit::getLocation(const FileEntry *File,
02640                                     unsigned Line, unsigned Col) const {
02641   const SourceManager &SM = getSourceManager();
02642   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
02643   return SM.getMacroArgExpandedLocation(Loc);
02644 }
02645 
02646 SourceLocation ASTUnit::getLocation(const FileEntry *File,
02647                                     unsigned Offset) const {
02648   const SourceManager &SM = getSourceManager();
02649   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
02650   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
02651 }
02652 
02653 /// \brief If \arg Loc is a loaded location from the preamble, returns
02654 /// the corresponding local location of the main file, otherwise it returns
02655 /// \arg Loc.
02656 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
02657   FileID PreambleID;
02658   if (SourceMgr)
02659     PreambleID = SourceMgr->getPreambleFileID();
02660 
02661   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
02662     return Loc;
02663 
02664   unsigned Offs;
02665   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
02666     SourceLocation FileLoc
02667         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
02668     return FileLoc.getLocWithOffset(Offs);
02669   }
02670 
02671   return Loc;
02672 }
02673 
02674 /// \brief If \arg Loc is a local location of the main file but inside the
02675 /// preamble chunk, returns the corresponding loaded location from the
02676 /// preamble, otherwise it returns \arg Loc.
02677 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
02678   FileID PreambleID;
02679   if (SourceMgr)
02680     PreambleID = SourceMgr->getPreambleFileID();
02681 
02682   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
02683     return Loc;
02684 
02685   unsigned Offs;
02686   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
02687       Offs < Preamble.size()) {
02688     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
02689     return FileLoc.getLocWithOffset(Offs);
02690   }
02691 
02692   return Loc;
02693 }
02694 
02695 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
02696   FileID FID;
02697   if (SourceMgr)
02698     FID = SourceMgr->getPreambleFileID();
02699   
02700   if (Loc.isInvalid() || FID.isInvalid())
02701     return false;
02702   
02703   return SourceMgr->isInFileID(Loc, FID);
02704 }
02705 
02706 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
02707   FileID FID;
02708   if (SourceMgr)
02709     FID = SourceMgr->getMainFileID();
02710   
02711   if (Loc.isInvalid() || FID.isInvalid())
02712     return false;
02713   
02714   return SourceMgr->isInFileID(Loc, FID);
02715 }
02716 
02717 SourceLocation ASTUnit::getEndOfPreambleFileID() {
02718   FileID FID;
02719   if (SourceMgr)
02720     FID = SourceMgr->getPreambleFileID();
02721   
02722   if (FID.isInvalid())
02723     return SourceLocation();
02724 
02725   return SourceMgr->getLocForEndOfFile(FID);
02726 }
02727 
02728 SourceLocation ASTUnit::getStartOfMainFileID() {
02729   FileID FID;
02730   if (SourceMgr)
02731     FID = SourceMgr->getMainFileID();
02732   
02733   if (FID.isInvalid())
02734     return SourceLocation();
02735   
02736   return SourceMgr->getLocForStartOfFile(FID);
02737 }
02738 
02739 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
02740 ASTUnit::getLocalPreprocessingEntities() const {
02741   if (isMainFileAST()) {
02742     serialization::ModuleFile &
02743       Mod = Reader->getModuleManager().getPrimaryModule();
02744     return Reader->getModulePreprocessedEntities(Mod);
02745   }
02746 
02747   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
02748     return std::make_pair(PPRec->local_begin(), PPRec->local_end());
02749 
02750   return std::make_pair(PreprocessingRecord::iterator(),
02751                         PreprocessingRecord::iterator());
02752 }
02753 
02754 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
02755   if (isMainFileAST()) {
02756     serialization::ModuleFile &
02757       Mod = Reader->getModuleManager().getPrimaryModule();
02758     ASTReader::ModuleDeclIterator MDI, MDE;
02759     std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
02760     for (; MDI != MDE; ++MDI) {
02761       if (!Fn(context, *MDI))
02762         return false;
02763     }
02764 
02765     return true;
02766   }
02767 
02768   for (ASTUnit::top_level_iterator TL = top_level_begin(),
02769                                 TLEnd = top_level_end();
02770          TL != TLEnd; ++TL) {
02771     if (!Fn(context, *TL))
02772       return false;
02773   }
02774 
02775   return true;
02776 }
02777 
02778 namespace {
02779 struct PCHLocatorInfo {
02780   serialization::ModuleFile *Mod;
02781   PCHLocatorInfo() : Mod(nullptr) {}
02782 };
02783 }
02784 
02785 static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
02786   PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
02787   switch (M.Kind) {
02788   case serialization::MK_ImplicitModule:
02789   case serialization::MK_ExplicitModule:
02790     return true; // skip dependencies.
02791   case serialization::MK_PCH:
02792     Info.Mod = &M;
02793     return true; // found it.
02794   case serialization::MK_Preamble:
02795     return false; // look in dependencies.
02796   case serialization::MK_MainFile:
02797     return false; // look in dependencies.
02798   }
02799 
02800   return true;
02801 }
02802 
02803 const FileEntry *ASTUnit::getPCHFile() {
02804   if (!Reader)
02805     return nullptr;
02806 
02807   PCHLocatorInfo Info;
02808   Reader->getModuleManager().visit(PCHLocator, &Info);
02809   if (Info.Mod)
02810     return Info.Mod->File;
02811 
02812   return nullptr;
02813 }
02814 
02815 bool ASTUnit::isModuleFile() {
02816   return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
02817 }
02818 
02819 void ASTUnit::PreambleData::countLines() const {
02820   NumLines = 0;
02821   if (empty())
02822     return;
02823 
02824   for (std::vector<char>::const_iterator
02825          I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
02826     if (*I == '\n')
02827       ++NumLines;
02828   }
02829   if (Buffer.back() != '\n')
02830     ++NumLines;
02831 }
02832 
02833 #ifndef NDEBUG
02834 ASTUnit::ConcurrencyState::ConcurrencyState() {
02835   Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
02836 }
02837 
02838 ASTUnit::ConcurrencyState::~ConcurrencyState() {
02839   delete static_cast<llvm::sys::MutexImpl *>(Mutex);
02840 }
02841 
02842 void ASTUnit::ConcurrencyState::start() {
02843   bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
02844   assert(acquired && "Concurrent access to ASTUnit!");
02845 }
02846 
02847 void ASTUnit::ConcurrencyState::finish() {
02848   static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
02849 }
02850 
02851 #else // NDEBUG
02852 
02853 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
02854 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
02855 void ASTUnit::ConcurrencyState::start() {}
02856 void ASTUnit::ConcurrencyState::finish() {}
02857 
02858 #endif