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 namespace llvm {
00031 
00032 class Value;
00033 class Type;
00034 class IntegerType;
00035 class StructType;
00036 class StructLayout;
00037 class GlobalVariable;
00038 class LLVMContext;
00039 template<typename T>
00040 class ArrayRef;
00041 
00042 /// Enum used to categorize the alignment types stored by LayoutAlignElem
00043 enum AlignTypeEnum {
00044   INVALID_ALIGN = 0,                 ///< An invalid alignment
00045   INTEGER_ALIGN = 'i',               ///< Integer type alignment
00046   VECTOR_ALIGN = 'v',                ///< Vector type alignment
00047   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
00048   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
00049   STACK_ALIGN = 's'                  ///< Stack objects alignment
00050 };
00051 
00052 /// Layout alignment element.
00053 ///
00054 /// Stores the alignment data associated with a given alignment type (integer,
00055 /// vector, float) and type bit width.
00056 ///
00057 /// @note The unusual order of elements in the structure attempts to reduce
00058 /// padding and make the structure slightly more cache friendly.
00059 struct LayoutAlignElem {
00060   unsigned AlignType    : 8;  ///< Alignment type (AlignTypeEnum)
00061   unsigned TypeBitWidth : 24; ///< Type bit width
00062   unsigned ABIAlign     : 16; ///< ABI alignment for this type/bitw
00063   unsigned PrefAlign    : 16; ///< Pref. alignment for this type/bitw
00064 
00065   /// Initializer
00066   static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
00067                              unsigned pref_align, uint32_t bit_width);
00068   /// Equality predicate
00069   bool operator==(const LayoutAlignElem &rhs) const;
00070 };
00071 
00072 /// Layout pointer alignment element.
00073 ///
00074 /// Stores the alignment data associated with a given pointer and address space.
00075 ///
00076 /// @note The unusual order of elements in the structure attempts to reduce
00077 /// padding and make the structure slightly more cache friendly.
00078 struct PointerAlignElem {
00079   unsigned            ABIAlign;       ///< ABI alignment for this type/bitw
00080   unsigned            PrefAlign;      ///< Pref. alignment for this type/bitw
00081   uint32_t            TypeBitWidth;   ///< Type bit width
00082   uint32_t            AddressSpace;   ///< Address space for the pointer type
00083 
00084   /// Initializer
00085   static PointerAlignElem get(uint32_t addr_space, unsigned abi_align,
00086                              unsigned pref_align, uint32_t bit_width);
00087   /// Equality predicate
00088   bool operator==(const PointerAlignElem &rhs) const;
00089 };
00090 
00091 
00092 /// DataLayout - This class holds a parsed version of the target data layout
00093 /// string in a module and provides methods for querying it.  The target data
00094 /// layout string is specified *by the target* - a frontend generating LLVM IR
00095 /// is required to generate the right target data for the target being codegen'd
00096 /// to.  If some measure of portability is desired, an empty string may be
00097 /// specified in the module.
00098 class DataLayout : public ImmutablePass {
00099 private:
00100   bool          LittleEndian;          ///< Defaults to false
00101   unsigned      StackNaturalAlign;     ///< Stack natural alignment
00102 
00103   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
00104 
00105   /// Alignments - Where the primitive type alignment data is stored.
00106   ///
00107   /// @sa init().
00108   /// @note Could support multiple size pointer alignments, e.g., 32-bit
00109   /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
00110   /// we don't.
00111   SmallVector<LayoutAlignElem, 16> Alignments;
00112   DenseMap<unsigned, PointerAlignElem> Pointers;
00113 
00114   /// InvalidAlignmentElem - This member is a signal that a requested alignment
00115   /// type and bit width were not found in the SmallVector.
00116   static const LayoutAlignElem InvalidAlignmentElem;
00117 
00118   /// InvalidPointerElem - This member is a signal that a requested pointer
00119   /// type and bit width were not found in the DenseSet.
00120   static const PointerAlignElem InvalidPointerElem;
00121 
00122   // The StructType -> StructLayout map.
00123   mutable void *LayoutMap;
00124 
00125   //! Set/initialize target alignments
00126   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
00127                     unsigned pref_align, uint32_t bit_width);
00128   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
00129                             bool ABIAlign, Type *Ty) const;
00130 
00131   //! Set/initialize pointer alignments
00132   void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
00133       unsigned pref_align, uint32_t bit_width);
00134 
00135   //! Internal helper method that returns requested alignment for type.
00136   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
00137 
00138   /// Valid alignment predicate.
00139   ///
00140   /// Predicate that tests a LayoutAlignElem reference returned by get() against
00141   /// InvalidAlignmentElem.
00142   bool validAlignment(const LayoutAlignElem &align) const {
00143     return &align != &InvalidAlignmentElem;
00144   }
00145 
00146   /// Valid pointer predicate.
00147   ///
00148   /// Predicate that tests a PointerAlignElem reference returned by get() against
00149   /// InvalidPointerElem.
00150   bool validPointer(const PointerAlignElem &align) const {
00151     return &align != &InvalidPointerElem;
00152   }
00153 
00154   /// Parses a target data specification string. Assert if the string is
00155   /// malformed.
00156   void parseSpecifier(StringRef LayoutDescription);
00157 
00158 public:
00159   /// Default ctor.
00160   ///
00161   /// @note This has to exist, because this is a pass, but it should never be
00162   /// used.
00163   DataLayout();
00164 
00165   /// Constructs a DataLayout from a specification string. See init().
00166   explicit DataLayout(StringRef LayoutDescription)
00167     : ImmutablePass(ID) {
00168     init(LayoutDescription);
00169   }
00170 
00171   /// Initialize target data from properties stored in the module.
00172   explicit DataLayout(const Module *M);
00173 
00174   DataLayout(const DataLayout &DL) :
00175     ImmutablePass(ID),
00176     LittleEndian(DL.isLittleEndian()),
00177     StackNaturalAlign(DL.StackNaturalAlign),
00178     LegalIntWidths(DL.LegalIntWidths),
00179     Alignments(DL.Alignments),
00180     Pointers(DL.Pointers),
00181     LayoutMap(0)
00182   { }
00183 
00184   ~DataLayout();  // Not virtual, do not subclass this class
00185 
00186   /// DataLayout is an immutable pass, but holds state.  This allows the pass
00187   /// manager to clear its mutable state.
00188   bool doFinalization(Module &M);
00189 
00190   /// Parse a data layout string (with fallback to default values). Ensure that
00191   /// the data layout pass is registered.
00192   void init(StringRef LayoutDescription);
00193 
00194   /// Layout endianness...
00195   bool isLittleEndian() const { return LittleEndian; }
00196   bool isBigEndian() const { return !LittleEndian; }
00197 
00198   /// getStringRepresentation - Return the string representation of the
00199   /// DataLayout.  This representation is in the same format accepted by the
00200   /// string constructor above.
00201   std::string getStringRepresentation() const;
00202 
00203   /// isLegalInteger - This function returns true if the specified type is
00204   /// known to be a native integer type supported by the CPU.  For example,
00205   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
00206   /// one.  This returns false if the integer width is not legal.
00207   ///
00208   /// The width is specified in bits.
00209   ///
00210   bool isLegalInteger(unsigned Width) const {
00211     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
00212       if (LegalIntWidths[i] == Width)
00213         return true;
00214     return false;
00215   }
00216 
00217   bool isIllegalInteger(unsigned Width) const {
00218     return !isLegalInteger(Width);
00219   }
00220 
00221   /// Returns true if the given alignment exceeds the natural stack alignment.
00222   bool exceedsNaturalStackAlignment(unsigned Align) const {
00223     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
00224   }
00225 
00226   /// fitsInLegalInteger - This function returns true if the specified type fits
00227   /// in a native integer type supported by the CPU.  For example, if the CPU
00228   /// only supports i32 as a native integer type, then i27 fits in a legal
00229   // integer type but i45 does not.
00230   bool fitsInLegalInteger(unsigned Width) const {
00231     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
00232       if (Width <= LegalIntWidths[i])
00233         return true;
00234     return false;
00235   }
00236 
00237   /// Layout pointer alignment
00238   /// FIXME: The defaults need to be removed once all of
00239   /// the backends/clients are updated.
00240   unsigned getPointerABIAlignment(unsigned AS = 0)  const {
00241     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
00242     if (val == Pointers.end()) {
00243       val = Pointers.find(0);
00244     }
00245     return val->second.ABIAlign;
00246   }
00247   /// Return target's alignment for stack-based pointers
00248   /// FIXME: The defaults need to be removed once all of
00249   /// the backends/clients are updated.
00250   unsigned getPointerPrefAlignment(unsigned AS = 0) const {
00251     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
00252     if (val == Pointers.end()) {
00253       val = Pointers.find(0);
00254     }
00255     return val->second.PrefAlign;
00256   }
00257   /// Layout pointer size
00258   /// FIXME: The defaults need to be removed once all of
00259   /// the backends/clients are updated.
00260   unsigned getPointerSize(unsigned AS = 0)          const {
00261     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
00262     if (val == Pointers.end()) {
00263       val = Pointers.find(0);
00264     }
00265     return val->second.TypeBitWidth;
00266   }
00267   /// Layout pointer size, in bits
00268   /// FIXME: The defaults need to be removed once all of
00269   /// the backends/clients are updated.
00270   unsigned getPointerSizeInBits(unsigned AS = 0)    const {
00271     return getPointerSize(AS) * 8;
00272   }
00273   /// Size examples:
00274   ///
00275   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
00276   /// ----        ----------  ---------------  ---------------
00277   ///  i1            1           8                8
00278   ///  i8            8           8                8
00279   ///  i19          19          24               32
00280   ///  i32          32          32               32
00281   ///  i100        100         104              128
00282   ///  i128        128         128              128
00283   ///  Float        32          32               32
00284   ///  Double       64          64               64
00285   ///  X86_FP80     80          80               96
00286   ///
00287   /// [*] The alloc size depends on the alignment, and thus on the target.
00288   ///     These values are for x86-32 linux.
00289 
00290   /// getTypeSizeInBits - Return the number of bits necessary to hold the
00291   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
00292   /// The type passed must have a size (Type::isSized() must return true).
00293   uint64_t getTypeSizeInBits(Type *Ty) const;
00294 
00295   /// getTypeStoreSize - Return the maximum number of bytes that may be
00296   /// overwritten by storing the specified type.  For example, returns 5
00297   /// for i36 and 10 for x86_fp80.
00298   uint64_t getTypeStoreSize(Type *Ty) const {
00299     return (getTypeSizeInBits(Ty)+7)/8;
00300   }
00301 
00302   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
00303   /// overwritten by storing the specified type; always a multiple of 8.  For
00304   /// example, returns 40 for i36 and 80 for x86_fp80.
00305   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
00306     return 8*getTypeStoreSize(Ty);
00307   }
00308 
00309   /// getTypeAllocSize - Return the offset in bytes between successive objects
00310   /// of the specified type, including alignment padding.  This is the amount
00311   /// that alloca reserves for this type.  For example, returns 12 or 16 for
00312   /// x86_fp80, depending on alignment.
00313   uint64_t getTypeAllocSize(Type *Ty) const {
00314     // Round up to the next alignment boundary.
00315     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
00316   }
00317 
00318   /// getTypeAllocSizeInBits - Return the offset in bits between successive
00319   /// objects of the specified type, including alignment padding; always a
00320   /// multiple of 8.  This is the amount that alloca reserves for this type.
00321   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
00322   uint64_t getTypeAllocSizeInBits(Type *Ty) const {
00323     return 8*getTypeAllocSize(Ty);
00324   }
00325 
00326   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
00327   /// specified type.
00328   unsigned getABITypeAlignment(Type *Ty) const;
00329 
00330   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
00331   /// an integer type of the specified bitwidth.
00332   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
00333 
00334   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
00335   /// for the specified type when it is part of a call frame.
00336   unsigned getCallFrameTypeAlignment(Type *Ty) const;
00337 
00338   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
00339   /// the specified type.  This is always at least as good as the ABI alignment.
00340   unsigned getPrefTypeAlignment(Type *Ty) const;
00341 
00342   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
00343   /// specified type, returned as log2 of the value (a shift amount).
00344   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
00345 
00346   /// getIntPtrType - Return an integer type with size at least as big as that
00347   /// of a pointer in the given address space.
00348   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
00349 
00350   /// getIntPtrType - Return an integer (vector of integer) type with size at
00351   /// least as big as that of a pointer of the given pointer (vector of pointer)
00352   /// type.
00353   Type *getIntPtrType(Type *) const;
00354 
00355   /// getSmallestLegalIntType - Return the smallest integer type with size at
00356   /// least as big as Width bits.
00357   Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
00358 
00359   /// getIndexedOffset - return the offset from the beginning of the type for
00360   /// the specified indices.  This is used to implement getelementptr.
00361   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
00362 
00363   /// getStructLayout - Return a StructLayout object, indicating the alignment
00364   /// of the struct, its size, and the offsets of its fields.  Note that this
00365   /// information is lazily cached.
00366   const StructLayout *getStructLayout(StructType *Ty) const;
00367 
00368   /// getPreferredAlignment - Return the preferred alignment of the specified
00369   /// global.  This includes an explicitly requested alignment (if the global
00370   /// has one).
00371   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
00372 
00373   /// getPreferredAlignmentLog - Return the preferred alignment of the
00374   /// specified global, returned in log form.  This includes an explicitly
00375   /// requested alignment (if the global has one).
00376   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
00377 
00378   /// RoundUpAlignment - Round the specified value up to the next alignment
00379   /// boundary specified by Alignment.  For example, 7 rounded up to an
00380   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
00381   /// is 8 because it is already aligned.
00382   template <typename UIntTy>
00383   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
00384     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
00385     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
00386   }
00387 
00388   static char ID; // Pass identification, replacement for typeid
00389 };
00390 
00391 /// StructLayout - used to lazily calculate structure layout information for a
00392 /// target machine, based on the DataLayout structure.
00393 ///
00394 class StructLayout {
00395   uint64_t StructSize;
00396   unsigned StructAlignment;
00397   unsigned NumElements;
00398   uint64_t MemberOffsets[1];  // variable sized array!
00399 public:
00400 
00401   uint64_t getSizeInBytes() const {
00402     return StructSize;
00403   }
00404 
00405   uint64_t getSizeInBits() const {
00406     return 8*StructSize;
00407   }
00408 
00409   unsigned getAlignment() const {
00410     return StructAlignment;
00411   }
00412 
00413   /// getElementContainingOffset - Given a valid byte offset into the structure,
00414   /// return the structure index that contains it.
00415   ///
00416   unsigned getElementContainingOffset(uint64_t Offset) const;
00417 
00418   uint64_t getElementOffset(unsigned Idx) const {
00419     assert(Idx < NumElements && "Invalid element idx!");
00420     return MemberOffsets[Idx];
00421   }
00422 
00423   uint64_t getElementOffsetInBits(unsigned Idx) const {
00424     return getElementOffset(Idx)*8;
00425   }
00426 
00427 private:
00428   friend class DataLayout;   // Only DataLayout can create this class
00429   StructLayout(StructType *ST, const DataLayout &DL);
00430 };
00431 
00432 
00433 // The implementation of this method is provided inline as it is particularly
00434 // well suited to constant folding when called on a specific Type subclass.
00435 inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
00436   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
00437   switch (Ty->getTypeID()) {
00438   case Type::LabelTyID:
00439     return getPointerSizeInBits(0);
00440   case Type::PointerTyID:
00441     return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
00442   case Type::ArrayTyID: {
00443     ArrayType *ATy = cast<ArrayType>(Ty);
00444     return ATy->getNumElements() *
00445            getTypeAllocSizeInBits(ATy->getElementType());
00446   }
00447   case Type::StructTyID:
00448     // Get the layout annotation... which is lazily created on demand.
00449     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
00450   case Type::IntegerTyID:
00451     return cast<IntegerType>(Ty)->getBitWidth();
00452   case Type::HalfTyID:
00453     return 16;
00454   case Type::FloatTyID:
00455     return 32;
00456   case Type::DoubleTyID:
00457   case Type::X86_MMXTyID:
00458     return 64;
00459   case Type::PPC_FP128TyID:
00460   case Type::FP128TyID:
00461     return 128;
00462     // In memory objects this is always aligned to a higher boundary, but
00463   // only 80 bits contain information.
00464   case Type::X86_FP80TyID:
00465     return 80;
00466   case Type::VectorTyID: {
00467     VectorType *VTy = cast<VectorType>(Ty);
00468     return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
00469   }
00470   default:
00471     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
00472   }
00473 }
00474 
00475 } // End llvm namespace
00476 
00477 #endif