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