Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:37

0001 //===- ExternalASTSource.h - Abstract External AST Interface ----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 //  This file defines the ExternalASTSource interface, which enables
0010 //  construction of AST nodes from some external source.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CLANG_AST_EXTERNALASTSOURCE_H
0015 #define LLVM_CLANG_AST_EXTERNALASTSOURCE_H
0016 
0017 #include "clang/AST/CharUnits.h"
0018 #include "clang/AST/DeclBase.h"
0019 #include "clang/Basic/LLVM.h"
0020 #include "llvm/ADT/ArrayRef.h"
0021 #include "llvm/ADT/DenseMap.h"
0022 #include "llvm/ADT/IntrusiveRefCntPtr.h"
0023 #include "llvm/ADT/PointerUnion.h"
0024 #include "llvm/ADT/STLExtras.h"
0025 #include "llvm/ADT/SmallVector.h"
0026 #include "llvm/ADT/iterator.h"
0027 #include "llvm/Support/PointerLikeTypeTraits.h"
0028 #include <algorithm>
0029 #include <cassert>
0030 #include <cstddef>
0031 #include <cstdint>
0032 #include <iterator>
0033 #include <new>
0034 #include <optional>
0035 #include <utility>
0036 
0037 namespace clang {
0038 
0039 class ASTConsumer;
0040 class ASTContext;
0041 class ASTSourceDescriptor;
0042 class CXXBaseSpecifier;
0043 class CXXCtorInitializer;
0044 class CXXRecordDecl;
0045 class DeclarationName;
0046 class FieldDecl;
0047 class IdentifierInfo;
0048 class NamedDecl;
0049 class ObjCInterfaceDecl;
0050 class RecordDecl;
0051 class Selector;
0052 class Stmt;
0053 class TagDecl;
0054 
0055 /// Abstract interface for external sources of AST nodes.
0056 ///
0057 /// External AST sources provide AST nodes constructed from some
0058 /// external source, such as a precompiled header. External AST
0059 /// sources can resolve types and declarations from abstract IDs into
0060 /// actual type and declaration nodes, and read parts of declaration
0061 /// contexts.
0062 class ExternalASTSource : public RefCountedBase<ExternalASTSource> {
0063   friend class ExternalSemaSource;
0064 
0065   /// Generation number for this external AST source. Must be increased
0066   /// whenever we might have added new redeclarations for existing decls.
0067   uint32_t CurrentGeneration = 0;
0068 
0069   /// LLVM-style RTTI.
0070   static char ID;
0071 
0072 public:
0073   ExternalASTSource() = default;
0074   virtual ~ExternalASTSource();
0075 
0076   /// RAII class for safely pairing a StartedDeserializing call
0077   /// with FinishedDeserializing.
0078   class Deserializing {
0079     ExternalASTSource *Source;
0080 
0081   public:
0082     explicit Deserializing(ExternalASTSource *source) : Source(source) {
0083       assert(Source);
0084       Source->StartedDeserializing();
0085     }
0086 
0087     ~Deserializing() {
0088       Source->FinishedDeserializing();
0089     }
0090   };
0091 
0092   /// Get the current generation of this AST source. This number
0093   /// is incremented each time the AST source lazily extends an existing
0094   /// entity.
0095   uint32_t getGeneration() const { return CurrentGeneration; }
0096 
0097   /// Resolve a declaration ID into a declaration, potentially
0098   /// building a new declaration.
0099   ///
0100   /// This method only needs to be implemented if the AST source ever
0101   /// passes back decl sets as VisibleDeclaration objects.
0102   ///
0103   /// The default implementation of this method is a no-op.
0104   virtual Decl *GetExternalDecl(GlobalDeclID ID);
0105 
0106   /// Resolve a selector ID into a selector.
0107   ///
0108   /// This operation only needs to be implemented if the AST source
0109   /// returns non-zero for GetNumKnownSelectors().
0110   ///
0111   /// The default implementation of this method is a no-op.
0112   virtual Selector GetExternalSelector(uint32_t ID);
0113 
0114   /// Returns the number of selectors known to the external AST
0115   /// source.
0116   ///
0117   /// The default implementation of this method is a no-op.
0118   virtual uint32_t GetNumExternalSelectors();
0119 
0120   /// Resolve the offset of a statement in the decl stream into
0121   /// a statement.
0122   ///
0123   /// This operation is meant to be used via a LazyOffsetPtr.  It only
0124   /// needs to be implemented if the AST source uses methods like
0125   /// FunctionDecl::setLazyBody when building decls.
0126   ///
0127   /// The default implementation of this method is a no-op.
0128   virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
0129 
0130   /// Resolve the offset of a set of C++ constructor initializers in
0131   /// the decl stream into an array of initializers.
0132   ///
0133   /// The default implementation of this method is a no-op.
0134   virtual CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset);
0135 
0136   /// Resolve the offset of a set of C++ base specifiers in the decl
0137   /// stream into an array of specifiers.
0138   ///
0139   /// The default implementation of this method is a no-op.
0140   virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
0141 
0142   /// Update an out-of-date identifier.
0143   virtual void updateOutOfDateIdentifier(const IdentifierInfo &II) {}
0144 
0145   /// Find all declarations with the given name in the given context,
0146   /// and add them to the context by calling SetExternalVisibleDeclsForName
0147   /// or SetNoExternalVisibleDeclsForName.
0148   /// \param DC The context for lookup in. \c DC should be a primary context.
0149   /// \param Name The name to look for.
0150   /// \param OriginalDC The original context for lookup.  \c OriginalDC can
0151   /// provide more information than \c DC. e.g., The same namespace can appear
0152   /// in multiple module units. So we need the \c OriginalDC to tell us what
0153   /// the module the lookup come from.
0154   ///
0155   /// \return \c true if any declarations might have been found, \c false if
0156   /// we definitely have no declarations with tbis name.
0157   ///
0158   /// The default implementation of this method is a no-op returning \c false.
0159   virtual bool FindExternalVisibleDeclsByName(const DeclContext *DC,
0160                                               DeclarationName Name,
0161                                               const DeclContext *OriginalDC);
0162 
0163   /// Load all the external specializations for the Decl \param D if \param
0164   /// OnlyPartial is false. Otherwise, load all the external **partial**
0165   /// specializations for the \param D.
0166   ///
0167   /// Return true if any new specializations get loaded. Return false otherwise.
0168   virtual bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial);
0169 
0170   /// Load all the specializations for the Decl \param D with the same template
0171   /// args specified by \param TemplateArgs.
0172   ///
0173   /// Return true if any new specializations get loaded. Return false otherwise.
0174   virtual bool
0175   LoadExternalSpecializations(const Decl *D,
0176                               ArrayRef<TemplateArgument> TemplateArgs);
0177 
0178   /// Ensures that the table of all visible declarations inside this
0179   /// context is up to date.
0180   ///
0181   /// The default implementation of this function is a no-op.
0182   virtual void completeVisibleDeclsMap(const DeclContext *DC);
0183 
0184   /// Retrieve the module that corresponds to the given module ID.
0185   virtual Module *getModule(unsigned ID) { return nullptr; }
0186 
0187   /// Return a descriptor for the corresponding module, if one exists.
0188   virtual std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID);
0189 
0190   enum ExtKind { EK_Always, EK_Never, EK_ReplyHazy };
0191 
0192   virtual ExtKind hasExternalDefinitions(const Decl *D);
0193 
0194   /// Finds all declarations lexically contained within the given
0195   /// DeclContext, after applying an optional filter predicate.
0196   ///
0197   /// \param IsKindWeWant a predicate function that returns true if the passed
0198   /// declaration kind is one we are looking for.
0199   ///
0200   /// The default implementation of this method is a no-op.
0201   virtual void
0202   FindExternalLexicalDecls(const DeclContext *DC,
0203                            llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
0204                            SmallVectorImpl<Decl *> &Result);
0205 
0206   /// Finds all declarations lexically contained within the given
0207   /// DeclContext.
0208   void FindExternalLexicalDecls(const DeclContext *DC,
0209                                 SmallVectorImpl<Decl *> &Result) {
0210     FindExternalLexicalDecls(DC, [](Decl::Kind) { return true; }, Result);
0211   }
0212 
0213   /// Get the decls that are contained in a file in the Offset/Length
0214   /// range. \p Length can be 0 to indicate a point at \p Offset instead of
0215   /// a range.
0216   virtual void FindFileRegionDecls(FileID File, unsigned Offset,
0217                                    unsigned Length,
0218                                    SmallVectorImpl<Decl *> &Decls);
0219 
0220   /// Gives the external AST source an opportunity to complete
0221   /// the redeclaration chain for a declaration. Called each time we
0222   /// need the most recent declaration of a declaration after the
0223   /// generation count is incremented.
0224   virtual void CompleteRedeclChain(const Decl *D);
0225 
0226   /// Gives the external AST source an opportunity to complete
0227   /// an incomplete type.
0228   virtual void CompleteType(TagDecl *Tag);
0229 
0230   /// Gives the external AST source an opportunity to complete an
0231   /// incomplete Objective-C class.
0232   ///
0233   /// This routine will only be invoked if the "externally completed" bit is
0234   /// set on the ObjCInterfaceDecl via the function
0235   /// \c ObjCInterfaceDecl::setExternallyCompleted().
0236   virtual void CompleteType(ObjCInterfaceDecl *Class);
0237 
0238   /// Loads comment ranges.
0239   virtual void ReadComments();
0240 
0241   /// Notify ExternalASTSource that we started deserialization of
0242   /// a decl or type so until FinishedDeserializing is called there may be
0243   /// decls that are initializing. Must be paired with FinishedDeserializing.
0244   ///
0245   /// The default implementation of this method is a no-op.
0246   virtual void StartedDeserializing();
0247 
0248   /// Notify ExternalASTSource that we finished the deserialization of
0249   /// a decl or type. Must be paired with StartedDeserializing.
0250   ///
0251   /// The default implementation of this method is a no-op.
0252   virtual void FinishedDeserializing();
0253 
0254   /// Function that will be invoked when we begin parsing a new
0255   /// translation unit involving this external AST source.
0256   ///
0257   /// The default implementation of this method is a no-op.
0258   virtual void StartTranslationUnit(ASTConsumer *Consumer);
0259 
0260   /// Print any statistics that have been gathered regarding
0261   /// the external AST source.
0262   ///
0263   /// The default implementation of this method is a no-op.
0264   virtual void PrintStats();
0265 
0266   /// Perform layout on the given record.
0267   ///
0268   /// This routine allows the external AST source to provide an specific
0269   /// layout for a record, overriding the layout that would normally be
0270   /// constructed. It is intended for clients who receive specific layout
0271   /// details rather than source code (such as LLDB). The client is expected
0272   /// to fill in the field offsets, base offsets, virtual base offsets, and
0273   /// complete object size.
0274   ///
0275   /// \param Record The record whose layout is being requested.
0276   ///
0277   /// \param Size The final size of the record, in bits.
0278   ///
0279   /// \param Alignment The final alignment of the record, in bits.
0280   ///
0281   /// \param FieldOffsets The offset of each of the fields within the record,
0282   /// expressed in bits. All of the fields must be provided with offsets.
0283   ///
0284   /// \param BaseOffsets The offset of each of the direct, non-virtual base
0285   /// classes. If any bases are not given offsets, the bases will be laid
0286   /// out according to the ABI.
0287   ///
0288   /// \param VirtualBaseOffsets The offset of each of the virtual base classes
0289   /// (either direct or not). If any bases are not given offsets, the bases will be laid
0290   /// out according to the ABI.
0291   ///
0292   /// \returns true if the record layout was provided, false otherwise.
0293   virtual bool layoutRecordType(
0294       const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
0295       llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets,
0296       llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets,
0297       llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets);
0298 
0299   //===--------------------------------------------------------------------===//
0300   // Queries for performance analysis.
0301   //===--------------------------------------------------------------------===//
0302 
0303   struct MemoryBufferSizes {
0304     size_t malloc_bytes;
0305     size_t mmap_bytes;
0306 
0307     MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
0308         : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
0309   };
0310 
0311   /// Return the amount of memory used by memory buffers, breaking down
0312   /// by heap-backed versus mmap'ed memory.
0313   MemoryBufferSizes getMemoryBufferSizes() const {
0314     MemoryBufferSizes sizes(0, 0);
0315     getMemoryBufferSizes(sizes);
0316     return sizes;
0317   }
0318 
0319   virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
0320 
0321   /// LLVM-style RTTI.
0322   /// \{
0323   virtual bool isA(const void *ClassID) const { return ClassID == &ID; }
0324   static bool classof(const ExternalASTSource *S) { return S->isA(&ID); }
0325   /// \}
0326 
0327 protected:
0328   static DeclContextLookupResult
0329   SetExternalVisibleDeclsForName(const DeclContext *DC,
0330                                  DeclarationName Name,
0331                                  ArrayRef<NamedDecl*> Decls);
0332 
0333   static DeclContextLookupResult
0334   SetNoExternalVisibleDeclsForName(const DeclContext *DC,
0335                                    DeclarationName Name);
0336 
0337   /// Increment the current generation.
0338   uint32_t incrementGeneration(ASTContext &C);
0339 };
0340 
0341 /// A lazy pointer to an AST node (of base type T) that resides
0342 /// within an external AST source.
0343 ///
0344 /// The AST node is identified within the external AST source by a
0345 /// 63-bit offset, and can be retrieved via an operation on the
0346 /// external AST source itself.
0347 template<typename T, typename OffsT, T* (ExternalASTSource::*Get)(OffsT Offset)>
0348 struct LazyOffsetPtr {
0349   /// Either a pointer to an AST node or the offset within the
0350   /// external AST source where the AST node can be found.
0351   ///
0352   /// If the low bit is clear, a pointer to the AST node. If the low
0353   /// bit is set, the upper 63 bits are the offset.
0354   static constexpr size_t DataSize = std::max(sizeof(uint64_t), sizeof(T *));
0355   alignas(uint64_t) alignas(T *) mutable unsigned char Data[DataSize] = {};
0356 
0357   unsigned char GetLSB() const {
0358     return Data[llvm::sys::IsBigEndianHost ? DataSize - 1 : 0];
0359   }
0360 
0361   template <typename U> U &As(bool New) const {
0362     unsigned char *Obj =
0363         Data + (llvm::sys::IsBigEndianHost ? DataSize - sizeof(U) : 0);
0364     if (New)
0365       return *new (Obj) U;
0366     return *std::launder(reinterpret_cast<U *>(Obj));
0367   }
0368 
0369   T *&GetPtr() const { return As<T *>(false); }
0370   uint64_t &GetU64() const { return As<uint64_t>(false); }
0371   void SetPtr(T *Ptr) const { As<T *>(true) = Ptr; }
0372   void SetU64(uint64_t U64) const { As<uint64_t>(true) = U64; }
0373 
0374 public:
0375   LazyOffsetPtr() = default;
0376   explicit LazyOffsetPtr(T *Ptr) : Data() { SetPtr(Ptr); }
0377 
0378   explicit LazyOffsetPtr(uint64_t Offset) : Data() {
0379     assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
0380     if (Offset == 0)
0381       SetPtr(nullptr);
0382     else
0383       SetU64((Offset << 1) | 0x01);
0384   }
0385 
0386   LazyOffsetPtr &operator=(T *Ptr) {
0387     SetPtr(Ptr);
0388     return *this;
0389   }
0390 
0391   LazyOffsetPtr &operator=(uint64_t Offset) {
0392     assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
0393     if (Offset == 0)
0394       SetPtr(nullptr);
0395     else
0396       SetU64((Offset << 1) | 0x01);
0397 
0398     return *this;
0399   }
0400 
0401   /// Whether this pointer is non-NULL.
0402   ///
0403   /// This operation does not require the AST node to be deserialized.
0404   explicit operator bool() const { return isOffset() || GetPtr() != nullptr; }
0405 
0406   /// Whether this pointer is non-NULL.
0407   ///
0408   /// This operation does not require the AST node to be deserialized.
0409   bool isValid() const { return isOffset() || GetPtr() != nullptr; }
0410 
0411   /// Whether this pointer is currently stored as an offset.
0412   bool isOffset() const { return GetLSB() & 0x01; }
0413 
0414   /// Retrieve the pointer to the AST node that this lazy pointer points to.
0415   ///
0416   /// \param Source the external AST source.
0417   ///
0418   /// \returns a pointer to the AST node.
0419   T *get(ExternalASTSource *Source) const {
0420     if (isOffset()) {
0421       assert(Source &&
0422              "Cannot deserialize a lazy pointer without an AST source");
0423       SetPtr((Source->*Get)(OffsT(GetU64() >> 1)));
0424     }
0425     return GetPtr();
0426   }
0427 
0428   /// Retrieve the address of the AST node pointer. Deserializes the pointee if
0429   /// necessary.
0430   T **getAddressOfPointer(ExternalASTSource *Source) const {
0431     // Ensure the integer is in pointer form.
0432     (void)get(Source);
0433     return &GetPtr();
0434   }
0435 };
0436 
0437 /// A lazy value (of type T) that is within an AST node of type Owner,
0438 /// where the value might change in later generations of the external AST
0439 /// source.
0440 template<typename Owner, typename T, void (ExternalASTSource::*Update)(Owner)>
0441 struct LazyGenerationalUpdatePtr {
0442   /// A cache of the value of this pointer, in the most recent generation in
0443   /// which we queried it.
0444   struct LazyData {
0445     ExternalASTSource *ExternalSource;
0446     uint32_t LastGeneration = 0;
0447     T LastValue;
0448 
0449     LazyData(ExternalASTSource *Source, T Value)
0450         : ExternalSource(Source), LastValue(Value) {}
0451   };
0452 
0453   // Our value is represented as simply T if there is no external AST source.
0454   using ValueType = llvm::PointerUnion<T, LazyData*>;
0455   ValueType Value;
0456 
0457   LazyGenerationalUpdatePtr(ValueType V) : Value(V) {}
0458 
0459   // Defined in ASTContext.h
0460   static ValueType makeValue(const ASTContext &Ctx, T Value);
0461 
0462 public:
0463   explicit LazyGenerationalUpdatePtr(const ASTContext &Ctx, T Value = T())
0464       : Value(makeValue(Ctx, Value)) {}
0465 
0466   /// Create a pointer that is not potentially updated by later generations of
0467   /// the external AST source.
0468   enum NotUpdatedTag { NotUpdated };
0469   LazyGenerationalUpdatePtr(NotUpdatedTag, T Value = T())
0470       : Value(Value) {}
0471 
0472   /// Forcibly set this pointer (which must be lazy) as needing updates.
0473   void markIncomplete() { cast<LazyData *>(Value)->LastGeneration = 0; }
0474 
0475   /// Set the value of this pointer, in the current generation.
0476   void set(T NewValue) {
0477     if (auto *LazyVal = Value.template dyn_cast<LazyData *>()) {
0478       LazyVal->LastValue = NewValue;
0479       return;
0480     }
0481     Value = NewValue;
0482   }
0483 
0484   /// Set the value of this pointer, for this and all future generations.
0485   void setNotUpdated(T NewValue) { Value = NewValue; }
0486 
0487   /// Get the value of this pointer, updating its owner if necessary.
0488   T get(Owner O) {
0489     if (auto *LazyVal = Value.template dyn_cast<LazyData *>()) {
0490       if (LazyVal->LastGeneration != LazyVal->ExternalSource->getGeneration()) {
0491         LazyVal->LastGeneration = LazyVal->ExternalSource->getGeneration();
0492         (LazyVal->ExternalSource->*Update)(O);
0493       }
0494       return LazyVal->LastValue;
0495     }
0496     return cast<T>(Value);
0497   }
0498 
0499   /// Get the most recently computed value of this pointer without updating it.
0500   T getNotUpdated() const {
0501     if (auto *LazyVal = Value.template dyn_cast<LazyData *>())
0502       return LazyVal->LastValue;
0503     return cast<T>(Value);
0504   }
0505 
0506   void *getOpaqueValue() { return Value.getOpaqueValue(); }
0507   static LazyGenerationalUpdatePtr getFromOpaqueValue(void *Ptr) {
0508     return LazyGenerationalUpdatePtr(ValueType::getFromOpaqueValue(Ptr));
0509   }
0510 };
0511 
0512 } // namespace clang
0513 
0514 namespace llvm {
0515 
0516 /// Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be
0517 /// placed into a PointerUnion.
0518 template<typename Owner, typename T,
0519          void (clang::ExternalASTSource::*Update)(Owner)>
0520 struct PointerLikeTypeTraits<
0521     clang::LazyGenerationalUpdatePtr<Owner, T, Update>> {
0522   using Ptr = clang::LazyGenerationalUpdatePtr<Owner, T, Update>;
0523 
0524   static void *getAsVoidPointer(Ptr P) { return P.getOpaqueValue(); }
0525   static Ptr getFromVoidPointer(void *P) { return Ptr::getFromOpaqueValue(P); }
0526 
0527   static constexpr int NumLowBitsAvailable =
0528       PointerLikeTypeTraits<T>::NumLowBitsAvailable - 1;
0529 };
0530 
0531 } // namespace llvm
0532 
0533 namespace clang {
0534 
0535 /// Represents a lazily-loaded vector of data.
0536 ///
0537 /// The lazily-loaded vector of data contains data that is partially loaded
0538 /// from an external source and partially added by local translation. The
0539 /// items loaded from the external source are loaded lazily, when needed for
0540 /// iteration over the complete vector.
0541 template<typename T, typename Source,
0542          void (Source::*Loader)(SmallVectorImpl<T>&),
0543          unsigned LoadedStorage = 2, unsigned LocalStorage = 4>
0544 class LazyVector {
0545   SmallVector<T, LoadedStorage> Loaded;
0546   SmallVector<T, LocalStorage> Local;
0547 
0548 public:
0549   /// Iteration over the elements in the vector.
0550   ///
0551   /// In a complete iteration, the iterator walks the range [-M, N),
0552   /// where negative values are used to indicate elements
0553   /// loaded from the external source while non-negative values are used to
0554   /// indicate elements added via \c push_back().
0555   /// However, to provide iteration in source order (for, e.g., chained
0556   /// precompiled headers), dereferencing the iterator flips the negative
0557   /// values (corresponding to loaded entities), so that position -M
0558   /// corresponds to element 0 in the loaded entities vector, position -M+1
0559   /// corresponds to element 1 in the loaded entities vector, etc. This
0560   /// gives us a reasonably efficient, source-order walk.
0561   ///
0562   /// We define this as a wrapping iterator around an int. The
0563   /// iterator_adaptor_base class forwards the iterator methods to basic integer
0564   /// arithmetic.
0565   class iterator
0566       : public llvm::iterator_adaptor_base<
0567             iterator, int, std::random_access_iterator_tag, T, int, T *, T &> {
0568     friend class LazyVector;
0569 
0570     LazyVector *Self;
0571 
0572     iterator(LazyVector *Self, int Position)
0573         : iterator::iterator_adaptor_base(Position), Self(Self) {}
0574 
0575     bool isLoaded() const { return this->I < 0; }
0576 
0577   public:
0578     iterator() : iterator(nullptr, 0) {}
0579 
0580     typename iterator::reference operator*() const {
0581       if (isLoaded())
0582         return Self->Loaded.end()[this->I];
0583       return Self->Local.begin()[this->I];
0584     }
0585   };
0586 
0587   iterator begin(Source *source, bool LocalOnly = false) {
0588     if (LocalOnly)
0589       return iterator(this, 0);
0590 
0591     if (source)
0592       (source->*Loader)(Loaded);
0593     return iterator(this, -(int)Loaded.size());
0594   }
0595 
0596   iterator end() {
0597     return iterator(this, Local.size());
0598   }
0599 
0600   void push_back(const T& LocalValue) {
0601     Local.push_back(LocalValue);
0602   }
0603 
0604   void erase(iterator From, iterator To) {
0605     if (From.isLoaded() && To.isLoaded()) {
0606       Loaded.erase(&*From, &*To);
0607       return;
0608     }
0609 
0610     if (From.isLoaded()) {
0611       Loaded.erase(&*From, Loaded.end());
0612       From = begin(nullptr, true);
0613     }
0614 
0615     Local.erase(&*From, &*To);
0616   }
0617 };
0618 
0619 /// A lazy pointer to a statement.
0620 using LazyDeclStmtPtr =
0621     LazyOffsetPtr<Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt>;
0622 
0623 /// A lazy pointer to a declaration.
0624 using LazyDeclPtr =
0625     LazyOffsetPtr<Decl, GlobalDeclID, &ExternalASTSource::GetExternalDecl>;
0626 
0627 /// A lazy pointer to a set of CXXCtorInitializers.
0628 using LazyCXXCtorInitializersPtr =
0629     LazyOffsetPtr<CXXCtorInitializer *, uint64_t,
0630                   &ExternalASTSource::GetExternalCXXCtorInitializers>;
0631 
0632 /// A lazy pointer to a set of CXXBaseSpecifiers.
0633 using LazyCXXBaseSpecifiersPtr =
0634     LazyOffsetPtr<CXXBaseSpecifier, uint64_t,
0635                   &ExternalASTSource::GetExternalCXXBaseSpecifiers>;
0636 
0637 } // namespace clang
0638 
0639 #endif // LLVM_CLANG_AST_EXTERNALASTSOURCE_H