LLVM API Documentation

DataLayout.h
Go to the documentation of this file.
00001 //===--------- llvm/DataLayout.h - Data size & alignment info ---*- C++ -*-===//
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 // This file defines layout properties related to datatype size/offset/alignment
00011 // information.  It uses lazy annotations to cache information about how
00012 // structure types are laid out and used.
00013 //
00014 // This structure should be created once, filled in if the defaults are not
00015 // correct and then passed around by const&.  None of the members functions
00016 // require modification to the object.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #ifndef LLVM_IR_DATALAYOUT_H
00021 #define LLVM_IR_DATALAYOUT_H
00022 
00023 #include "llvm/ADT/DenseMap.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/Type.h"
00027 #include "llvm/Pass.h"
00028 #include "llvm/Support/DataTypes.h"
00029 
00030 // This needs to be outside of the namespace, to avoid conflict with llvm-c
00031 // decl.
00032 typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
00033 
00034 namespace llvm {
00035 
00036 class Value;
00037 class Type;
00038 class IntegerType;
00039 class StructType;
00040 class StructLayout;
00041 class Triple;
00042 class GlobalVariable;
00043 class LLVMContext;
00044 template<typename T>
00045 class ArrayRef;
00046 
00047 /// Enum used to categorize the alignment types stored by LayoutAlignElem
00048 enum AlignTypeEnum {
00049   INVALID_ALIGN = 0,
00050   INTEGER_ALIGN = 'i',
00051   VECTOR_ALIGN = 'v',
00052   FLOAT_ALIGN = 'f',
00053   AGGREGATE_ALIGN = 'a'
00054 };
00055 
00056 /// \brief Layout alignment element.
00057 ///
00058 /// Stores the alignment data associated with a given alignment type (integer,
00059 /// vector, float) and type bit width.
00060 ///
00061 /// \note The unusual order of elements in the structure attempts to reduce
00062 /// padding and make the structure slightly more cache friendly.
00063 struct LayoutAlignElem {
00064   /// \brief Alignment type from \c AlignTypeEnum
00065   unsigned AlignType : 8;
00066   unsigned TypeBitWidth : 24;
00067   unsigned ABIAlign : 16;
00068   unsigned PrefAlign : 16;
00069 
00070   static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
00071                              unsigned pref_align, uint32_t bit_width);
00072   bool operator==(const LayoutAlignElem &rhs) const;
00073 };
00074 
00075 /// \brief Layout pointer alignment element.
00076 ///
00077 /// Stores the alignment data associated with a given pointer and address space.
00078 ///
00079 /// \note The unusual order of elements in the structure attempts to reduce
00080 /// padding and make the structure slightly more cache friendly.
00081 struct PointerAlignElem {
00082   unsigned ABIAlign;
00083   unsigned PrefAlign;
00084   uint32_t TypeByteWidth;
00085   uint32_t AddressSpace;
00086 
00087   /// Initializer
00088   static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign,
00089                               unsigned PrefAlign, uint32_t TypeByteWidth);
00090   bool operator==(const PointerAlignElem &rhs) const;
00091 };
00092 
00093 /// \brief A parsed version of the target data layout string in and methods for
00094 /// querying it.
00095 ///
00096 /// The target data layout string is specified *by the target* - a frontend
00097 /// generating LLVM IR is required to generate the right target data for the
00098 /// target being codegen'd to.
00099 class DataLayout {
00100 private:
00101   /// Defaults to false.
00102   bool BigEndian;
00103 
00104   unsigned StackNaturalAlign;
00105 
00106   enum ManglingModeT { MM_None, MM_ELF, MM_MachO, MM_WINCOFF, MM_Mips };
00107   ManglingModeT ManglingMode;
00108 
00109   SmallVector<unsigned char, 8> LegalIntWidths;
00110 
00111   /// \brief Primitive type alignment data.
00112   SmallVector<LayoutAlignElem, 16> Alignments;
00113 
00114   typedef SmallVector<PointerAlignElem, 8> PointersTy;
00115   PointersTy Pointers;
00116 
00117   PointersTy::const_iterator
00118   findPointerLowerBound(uint32_t AddressSpace) const {
00119     return const_cast<DataLayout *>(this)->findPointerLowerBound(AddressSpace);
00120   }
00121 
00122   PointersTy::iterator findPointerLowerBound(uint32_t AddressSpace);
00123 
00124   /// This member is a signal that a requested alignment type and bit width were
00125   /// not found in the SmallVector.
00126   static const LayoutAlignElem InvalidAlignmentElem;
00127 
00128   /// This member is a signal that a requested pointer type and bit width were
00129   /// not found in the DenseSet.
00130   static const PointerAlignElem InvalidPointerElem;
00131 
00132   // The StructType -> StructLayout map.
00133   mutable void *LayoutMap;
00134 
00135   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
00136                     unsigned pref_align, uint32_t bit_width);
00137   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
00138                             bool ABIAlign, Type *Ty) const;
00139   void setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
00140                            unsigned PrefAlign, uint32_t TypeByteWidth);
00141 
00142   /// Internal helper method that returns requested alignment for type.
00143   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
00144 
00145   /// \brief Valid alignment predicate.
00146   ///
00147   /// Predicate that tests a LayoutAlignElem reference returned by get() against
00148   /// InvalidAlignmentElem.
00149   bool validAlignment(const LayoutAlignElem &align) const {
00150     return &align != &InvalidAlignmentElem;
00151   }
00152 
00153   /// \brief Valid pointer predicate.
00154   ///
00155   /// Predicate that tests a PointerAlignElem reference returned by get()
00156   /// against \c InvalidPointerElem.
00157   bool validPointer(const PointerAlignElem &align) const {
00158     return &align != &InvalidPointerElem;
00159   }
00160 
00161   /// Parses a target data specification string. Assert if the string is
00162   /// malformed.
00163   void parseSpecifier(StringRef LayoutDescription);
00164 
00165   // Free all internal data structures.
00166   void clear();
00167 
00168 public:
00169   /// Constructs a DataLayout from a specification string. See reset().
00170   explicit DataLayout(StringRef LayoutDescription) : LayoutMap(nullptr) {
00171     reset(LayoutDescription);
00172   }
00173 
00174   /// Initialize target data from properties stored in the module.
00175   explicit DataLayout(const Module *M);
00176 
00177   void init(const Module *M);
00178 
00179   DataLayout(const DataLayout &DL) : LayoutMap(nullptr) { *this = DL; }
00180 
00181   DataLayout &operator=(const DataLayout &DL) {
00182     clear();
00183     BigEndian = DL.isBigEndian();
00184     StackNaturalAlign = DL.StackNaturalAlign;
00185     ManglingMode = DL.ManglingMode;
00186     LegalIntWidths = DL.LegalIntWidths;
00187     Alignments = DL.Alignments;
00188     Pointers = DL.Pointers;
00189     return *this;
00190   }
00191 
00192   bool operator==(const DataLayout &Other) const;
00193   bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
00194 
00195   ~DataLayout(); // Not virtual, do not subclass this class
00196 
00197   /// Parse a data layout string (with fallback to default values).
00198   void reset(StringRef LayoutDescription);
00199 
00200   /// Layout endianness...
00201   bool isLittleEndian() const { return !BigEndian; }
00202   bool isBigEndian() const { return BigEndian; }
00203 
00204   /// \brief Returns the string representation of the DataLayout.
00205   ///
00206   /// This representation is in the same format accepted by the string
00207   /// constructor above.
00208   std::string getStringRepresentation() const;
00209 
00210   /// \brief Returns true if the specified type is known to be a native integer
00211   /// type supported by the CPU.
00212   ///
00213   /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
00214   /// on any known one. This returns false if the integer width is not legal.
00215   ///
00216   /// The width is specified in bits.
00217   bool isLegalInteger(unsigned Width) const {
00218     for (unsigned LegalIntWidth : LegalIntWidths)
00219       if (LegalIntWidth == Width)
00220         return true;
00221     return false;
00222   }
00223 
00224   bool isIllegalInteger(unsigned Width) const { return !isLegalInteger(Width); }
00225 
00226   /// Returns true if the given alignment exceeds the natural stack alignment.
00227   bool exceedsNaturalStackAlignment(unsigned Align) const {
00228     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
00229   }
00230 
00231   bool hasMicrosoftFastStdCallMangling() const {
00232     return ManglingMode == MM_WINCOFF;
00233   }
00234 
00235   bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
00236 
00237   const char *getLinkerPrivateGlobalPrefix() const {
00238     if (ManglingMode == MM_MachO)
00239       return "l";
00240     return getPrivateGlobalPrefix();
00241   }
00242 
00243   char getGlobalPrefix() const {
00244     switch (ManglingMode) {
00245     case MM_None:
00246     case MM_ELF:
00247     case MM_Mips:
00248       return '\0';
00249     case MM_MachO:
00250     case MM_WINCOFF:
00251       return '_';
00252     }
00253     llvm_unreachable("invalid mangling mode");
00254   }
00255 
00256   const char *getPrivateGlobalPrefix() const {
00257     switch (ManglingMode) {
00258     case MM_None:
00259       return "";
00260     case MM_ELF:
00261       return ".L";
00262     case MM_Mips:
00263       return "$";
00264     case MM_MachO:
00265     case MM_WINCOFF:
00266       return "L";
00267     }
00268     llvm_unreachable("invalid mangling mode");
00269   }
00270 
00271   static const char *getManglingComponent(const Triple &T);
00272 
00273   /// \brief Returns true if the specified type fits in a native integer type
00274   /// supported by the CPU.
00275   ///
00276   /// For example, if the CPU only supports i32 as a native integer type, then
00277   /// i27 fits in a legal integer type but i45 does not.
00278   bool fitsInLegalInteger(unsigned Width) const {
00279     for (unsigned LegalIntWidth : LegalIntWidths)
00280       if (Width <= LegalIntWidth)
00281         return true;
00282     return false;
00283   }
00284 
00285   /// Layout pointer alignment
00286   /// FIXME: The defaults need to be removed once all of
00287   /// the backends/clients are updated.
00288   unsigned getPointerABIAlignment(unsigned AS = 0) const;
00289 
00290   /// Return target's alignment for stack-based pointers
00291   /// FIXME: The defaults need to be removed once all of
00292   /// the backends/clients are updated.
00293   unsigned getPointerPrefAlignment(unsigned AS = 0) const;
00294 
00295   /// Layout pointer size
00296   /// FIXME: The defaults need to be removed once all of
00297   /// the backends/clients are updated.
00298   unsigned getPointerSize(unsigned AS = 0) const;
00299 
00300   /// Layout pointer size, in bits
00301   /// FIXME: The defaults need to be removed once all of
00302   /// the backends/clients are updated.
00303   unsigned getPointerSizeInBits(unsigned AS = 0) const {
00304     return getPointerSize(AS) * 8;
00305   }
00306 
00307   /// Layout pointer size, in bits, based on the type.  If this function is
00308   /// called with a pointer type, then the type size of the pointer is returned.
00309   /// If this function is called with a vector of pointers, then the type size
00310   /// of the pointer is returned.  This should only be called with a pointer or
00311   /// vector of pointers.
00312   unsigned getPointerTypeSizeInBits(Type *) const;
00313 
00314   unsigned getPointerTypeSize(Type *Ty) const {
00315     return getPointerTypeSizeInBits(Ty) / 8;
00316   }
00317 
00318   /// Size examples:
00319   ///
00320   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
00321   /// ----        ----------  ---------------  ---------------
00322   ///  i1            1           8                8
00323   ///  i8            8           8                8
00324   ///  i19          19          24               32
00325   ///  i32          32          32               32
00326   ///  i100        100         104              128
00327   ///  i128        128         128              128
00328   ///  Float        32          32               32
00329   ///  Double       64          64               64
00330   ///  X86_FP80     80          80               96
00331   ///
00332   /// [*] The alloc size depends on the alignment, and thus on the target.
00333   ///     These values are for x86-32 linux.
00334 
00335   /// \brief Returns the number of bits necessary to hold the specified type.
00336   ///
00337   /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
00338   /// have a size (Type::isSized() must return true).
00339   uint64_t getTypeSizeInBits(Type *Ty) const;
00340 
00341   /// \brief Returns the maximum number of bytes that may be overwritten by
00342   /// storing the specified type.
00343   ///
00344   /// For example, returns 5 for i36 and 10 for x86_fp80.
00345   uint64_t getTypeStoreSize(Type *Ty) const {
00346     return (getTypeSizeInBits(Ty) + 7) / 8;
00347   }
00348 
00349   /// \brief Returns the maximum number of bits that may be overwritten by
00350   /// storing the specified type; always a multiple of 8.
00351   ///
00352   /// For example, returns 40 for i36 and 80 for x86_fp80.
00353   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
00354     return 8 * getTypeStoreSize(Ty);
00355   }
00356 
00357   /// \brief Returns the offset in bytes between successive objects of the
00358   /// specified type, including alignment padding.
00359   ///
00360   /// This is the amount that alloca reserves for this type. For example,
00361   /// returns 12 or 16 for x86_fp80, depending on alignment.
00362   uint64_t getTypeAllocSize(Type *Ty) const {
00363     // Round up to the next alignment boundary.
00364     return RoundUpToAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
00365   }
00366 
00367   /// \brief Returns the offset in bits between successive objects of the
00368   /// specified type, including alignment padding; always a multiple of 8.
00369   ///
00370   /// This is the amount that alloca reserves for this type. For example,
00371   /// returns 96 or 128 for x86_fp80, depending on alignment.
00372   uint64_t getTypeAllocSizeInBits(Type *Ty) const {
00373     return 8 * getTypeAllocSize(Ty);
00374   }
00375 
00376   /// \brief Returns the minimum ABI-required alignment for the specified type.
00377   unsigned getABITypeAlignment(Type *Ty) const;
00378 
00379   /// \brief Returns the minimum ABI-required alignment for an integer type of
00380   /// the specified bitwidth.
00381   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
00382 
00383   /// \brief Returns the preferred stack/global alignment for the specified
00384   /// type.
00385   ///
00386   /// This is always at least as good as the ABI alignment.
00387   unsigned getPrefTypeAlignment(Type *Ty) const;
00388 
00389   /// \brief Returns the preferred alignment for the specified type, returned as
00390   /// log2 of the value (a shift amount).
00391   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
00392 
00393   /// \brief Returns an integer type with size at least as big as that of a
00394   /// pointer in the given address space.
00395   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
00396 
00397   /// \brief Returns an integer (vector of integer) type with size at least as
00398   /// big as that of a pointer of the given pointer (vector of pointer) type.
00399   Type *getIntPtrType(Type *) const;
00400 
00401   /// \brief Returns the smallest integer type with size at least as big as
00402   /// Width bits.
00403   Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
00404 
00405   /// \brief Returns the largest legal integer type, or null if none are set.
00406   Type *getLargestLegalIntType(LLVMContext &C) const {
00407     unsigned LargestSize = getLargestLegalIntTypeSize();
00408     return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
00409   }
00410 
00411   /// \brief Returns the size of largest legal integer type size, or 0 if none
00412   /// are set.
00413   unsigned getLargestLegalIntTypeSize() const;
00414 
00415   /// \brief Returns the offset from the beginning of the type for the specified
00416   /// indices.
00417   ///
00418   /// This is used to implement getelementptr.
00419   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
00420 
00421   /// \brief Returns a StructLayout object, indicating the alignment of the
00422   /// struct, its size, and the offsets of its fields.
00423   ///
00424   /// Note that this information is lazily cached.
00425   const StructLayout *getStructLayout(StructType *Ty) const;
00426 
00427   /// \brief Returns the preferred alignment of the specified global.
00428   ///
00429   /// This includes an explicitly requested alignment (if the global has one).
00430   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
00431 
00432   /// \brief Returns the preferred alignment of the specified global, returned
00433   /// in log form.
00434   ///
00435   /// This includes an explicitly requested alignment (if the global has one).
00436   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
00437 };
00438 
00439 inline DataLayout *unwrap(LLVMTargetDataRef P) {
00440   return reinterpret_cast<DataLayout *>(P);
00441 }
00442 
00443 inline LLVMTargetDataRef wrap(const DataLayout *P) {
00444   return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
00445 }
00446 
00447 class DataLayoutPass : public ImmutablePass {
00448   DataLayout DL;
00449 
00450 public:
00451   /// This has to exist, because this is a pass, but it should never be used.
00452   DataLayoutPass();
00453   ~DataLayoutPass();
00454 
00455   const DataLayout &getDataLayout() const { return DL; }
00456 
00457   static char ID; // Pass identification, replacement for typeid
00458 
00459   bool doFinalization(Module &M) override;
00460   bool doInitialization(Module &M) override;
00461 };
00462 
00463 /// Used to lazily calculate structure layout information for a target machine,
00464 /// based on the DataLayout structure.
00465 class StructLayout {
00466   uint64_t StructSize;
00467   unsigned StructAlignment;
00468   unsigned NumElements;
00469   uint64_t MemberOffsets[1]; // variable sized array!
00470 public:
00471   uint64_t getSizeInBytes() const { return StructSize; }
00472 
00473   uint64_t getSizeInBits() const { return 8 * StructSize; }
00474 
00475   unsigned getAlignment() const { return StructAlignment; }
00476 
00477   /// \brief Given a valid byte offset into the structure, returns the structure
00478   /// index that contains it.
00479   unsigned getElementContainingOffset(uint64_t Offset) const;
00480 
00481   uint64_t getElementOffset(unsigned Idx) const {
00482     assert(Idx < NumElements && "Invalid element idx!");
00483     return MemberOffsets[Idx];
00484   }
00485 
00486   uint64_t getElementOffsetInBits(unsigned Idx) const {
00487     return getElementOffset(Idx) * 8;
00488   }
00489 
00490 private:
00491   friend class DataLayout; // Only DataLayout can create this class
00492   StructLayout(StructType *ST, const DataLayout &DL);
00493 };
00494 
00495 // The implementation of this method is provided inline as it is particularly
00496 // well suited to constant folding when called on a specific Type subclass.
00497 inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
00498   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
00499   switch (Ty->getTypeID()) {
00500   case Type::LabelTyID:
00501     return getPointerSizeInBits(0);
00502   case Type::PointerTyID:
00503     return getPointerSizeInBits(Ty->getPointerAddressSpace());
00504   case Type::ArrayTyID: {
00505     ArrayType *ATy = cast<ArrayType>(Ty);
00506     return ATy->getNumElements() *
00507            getTypeAllocSizeInBits(ATy->getElementType());
00508   }
00509   case Type::StructTyID:
00510     // Get the layout annotation... which is lazily created on demand.
00511     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
00512   case Type::IntegerTyID:
00513     return Ty->getIntegerBitWidth();
00514   case Type::HalfTyID:
00515     return 16;
00516   case Type::FloatTyID:
00517     return 32;
00518   case Type::DoubleTyID:
00519   case Type::X86_MMXTyID:
00520     return 64;
00521   case Type::PPC_FP128TyID:
00522   case Type::FP128TyID:
00523     return 128;
00524   // In memory objects this is always aligned to a higher boundary, but
00525   // only 80 bits contain information.
00526   case Type::X86_FP80TyID:
00527     return 80;
00528   case Type::VectorTyID: {
00529     VectorType *VTy = cast<VectorType>(Ty);
00530     return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
00531   }
00532   default:
00533     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
00534   }
00535 }
00536 
00537 } // End llvm namespace
00538 
00539 #endif