LLVM API Documentation

TargetData.h

Go to the documentation of this file.
00001 //===-- llvm/Target/TargetData.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 target 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_TARGET_TARGETDATA_H
00021 #define LLVM_TARGET_TARGETDATA_H
00022 
00023 #include "llvm/Pass.h"
00024 #include "llvm/Support/DataTypes.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 #include "llvm/ADT/SmallVector.h"
00027 #include <string>
00028 
00029 namespace llvm {
00030 
00031 class Value;
00032 class Type;
00033 class IntegerType;
00034 class StructType;
00035 class StructLayout;
00036 class GlobalVariable;
00037 class LLVMContext;
00038 
00039 /// Enum used to categorize the alignment types stored by TargetAlignElem
00040 enum AlignTypeEnum {
00041   INTEGER_ALIGN = 'i',               ///< Integer type alignment
00042   VECTOR_ALIGN = 'v',                ///< Vector type alignment
00043   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
00044   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
00045   STACK_ALIGN = 's'                  ///< Stack objects alignment
00046 };
00047 /// Target alignment element.
00048 ///
00049 /// Stores the alignment data associated with a given alignment type (pointer,
00050 /// integer, vector, float) and type bit width.
00051 ///
00052 /// @note The unusual order of elements in the structure attempts to reduce
00053 /// padding and make the structure slightly more cache friendly.
00054 struct TargetAlignElem {
00055   AlignTypeEnum       AlignType : 8;  //< Alignment type (AlignTypeEnum)
00056   unsigned char       ABIAlign;       //< ABI alignment for this type/bitw
00057   unsigned char       PrefAlign;      //< Pref. alignment for this type/bitw
00058   uint32_t            TypeBitWidth;   //< Type bit width
00059 
00060   /// Initializer
00061   static TargetAlignElem get(AlignTypeEnum align_type, unsigned char abi_align,
00062                              unsigned char pref_align, uint32_t bit_width);
00063   /// Equality predicate
00064   bool operator==(const TargetAlignElem &rhs) const;
00065   /// output stream operator
00066   std::ostream &dump(std::ostream &os) const;
00067 };
00068 
00069 class TargetData : public ImmutablePass {
00070 private:
00071   bool          LittleEndian;          ///< Defaults to false
00072   unsigned char PointerMemSize;        ///< Pointer size in bytes
00073   unsigned char PointerABIAlign;       ///< Pointer ABI alignment
00074   unsigned char PointerPrefAlign;      ///< Pointer preferred alignment
00075 
00076   //! Where the primitive type alignment data is stored.
00077   /*!
00078    @sa init().
00079    @note Could support multiple size pointer alignments, e.g., 32-bit pointers
00080    vs. 64-bit pointers by extending TargetAlignment, but for now, we don't.
00081    */
00082   SmallVector<TargetAlignElem, 16> Alignments;
00083   //! Alignment iterator shorthand
00084   typedef SmallVector<TargetAlignElem, 16>::iterator align_iterator;
00085   //! Constant alignment iterator shorthand
00086   typedef SmallVector<TargetAlignElem, 16>::const_iterator align_const_iterator;
00087   //! Invalid alignment.
00088   /*!
00089     This member is a signal that a requested alignment type and bit width were
00090     not found in the SmallVector.
00091    */
00092   static const TargetAlignElem InvalidAlignmentElem;
00093 
00094   // Opaque pointer for the StructType -> StructLayout map.
00095   mutable void* LayoutMap;
00096 
00097   //! Set/initialize target alignments
00098   void setAlignment(AlignTypeEnum align_type, unsigned char abi_align,
00099                     unsigned char pref_align, uint32_t bit_width);
00100   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
00101                             bool ABIAlign, const Type *Ty) const;
00102   //! Internal helper method that returns requested alignment for type.
00103   unsigned char getAlignment(const Type *Ty, bool abi_or_pref) const;
00104 
00105   /// Valid alignment predicate.
00106   ///
00107   /// Predicate that tests a TargetAlignElem reference returned by get() against
00108   /// InvalidAlignmentElem.
00109   inline bool validAlignment(const TargetAlignElem &align) const {
00110     return (&align != &InvalidAlignmentElem);
00111   }
00112 
00113 public:
00114   /// Default ctor.
00115   ///
00116   /// @note This has to exist, because this is a pass, but it should never be
00117   /// used.
00118   TargetData() : ImmutablePass(&ID) {
00119     llvm_report_error("Bad TargetData ctor used.  "
00120                       "Tool did not specify a TargetData to use?");
00121   }
00122 
00123   /// Constructs a TargetData from a specification string. See init().
00124   explicit TargetData(const std::string &TargetDescription)
00125     : ImmutablePass(&ID) {
00126     init(TargetDescription);
00127   }
00128 
00129   /// Initialize target data from properties stored in the module.
00130   explicit TargetData(const Module *M);
00131 
00132   TargetData(const TargetData &TD) :
00133     ImmutablePass(&ID),
00134     LittleEndian(TD.isLittleEndian()),
00135     PointerMemSize(TD.PointerMemSize),
00136     PointerABIAlign(TD.PointerABIAlign),
00137     PointerPrefAlign(TD.PointerPrefAlign),
00138     Alignments(TD.Alignments),
00139     LayoutMap(0)
00140   { }
00141 
00142   ~TargetData();  // Not virtual, do not subclass this class
00143 
00144   //! Parse a target data layout string and initialize TargetData alignments.
00145   void init(const std::string &TargetDescription);
00146 
00147   /// Target endianness...
00148   bool          isLittleEndian()       const { return     LittleEndian; }
00149   bool          isBigEndian()          const { return    !LittleEndian; }
00150 
00151   /// getStringRepresentation - Return the string representation of the
00152   /// TargetData.  This representation is in the same format accepted by the
00153   /// string constructor above.
00154   std::string getStringRepresentation() const;
00155   /// Target pointer alignment
00156   unsigned char getPointerABIAlignment() const { return PointerABIAlign; }
00157   /// Return target's alignment for stack-based pointers
00158   unsigned char getPointerPrefAlignment() const { return PointerPrefAlign; }
00159   /// Target pointer size
00160   unsigned char getPointerSize()         const { return PointerMemSize; }
00161   /// Target pointer size, in bits
00162   unsigned char getPointerSizeInBits()   const { return 8*PointerMemSize; }
00163 
00164   /// Size examples:
00165   ///
00166   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
00167   /// ----        ----------  ---------------  ---------------
00168   ///  i1            1           8                8
00169   ///  i8            8           8                8
00170   ///  i19          19          24               32
00171   ///  i32          32          32               32
00172   ///  i100        100         104              128
00173   ///  i128        128         128              128
00174   ///  Float        32          32               32
00175   ///  Double       64          64               64
00176   ///  X86_FP80     80          80               96
00177   ///
00178   /// [*] The alloc size depends on the alignment, and thus on the target.
00179   ///     These values are for x86-32 linux.
00180 
00181   /// getTypeSizeInBits - Return the number of bits necessary to hold the
00182   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
00183   uint64_t getTypeSizeInBits(const Type* Ty) const;
00184 
00185   /// getTypeStoreSize - Return the maximum number of bytes that may be
00186   /// overwritten by storing the specified type.  For example, returns 5
00187   /// for i36 and 10 for x86_fp80.
00188   uint64_t getTypeStoreSize(const Type *Ty) const {
00189     return (getTypeSizeInBits(Ty)+7)/8;
00190   }
00191 
00192   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
00193   /// overwritten by storing the specified type; always a multiple of 8.  For
00194   /// example, returns 40 for i36 and 80 for x86_fp80.
00195   uint64_t getTypeStoreSizeInBits(const Type *Ty) const {
00196     return 8*getTypeStoreSize(Ty);
00197   }
00198 
00199   /// getTypeAllocSize - Return the offset in bytes between successive objects
00200   /// of the specified type, including alignment padding.  This is the amount
00201   /// that alloca reserves for this type.  For example, returns 12 or 16 for
00202   /// x86_fp80, depending on alignment.
00203   uint64_t getTypeAllocSize(const Type* Ty) const {
00204     // Round up to the next alignment boundary.
00205     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
00206   }
00207 
00208   /// getTypeAllocSizeInBits - Return the offset in bits between successive
00209   /// objects of the specified type, including alignment padding; always a
00210   /// multiple of 8.  This is the amount that alloca reserves for this type.
00211   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
00212   uint64_t getTypeAllocSizeInBits(const Type* Ty) const {
00213     return 8*getTypeAllocSize(Ty);
00214   }
00215 
00216   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
00217   /// specified type.
00218   unsigned char getABITypeAlignment(const Type *Ty) const;
00219 
00220   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
00221   /// for the specified type when it is part of a call frame.
00222   unsigned char getCallFrameTypeAlignment(const Type *Ty) const;
00223 
00224 
00225   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
00226   /// the specified type.  This is always at least as good as the ABI alignment.
00227   unsigned char getPrefTypeAlignment(const Type *Ty) const;
00228 
00229   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
00230   /// specified type, returned as log2 of the value (a shift amount).
00231   ///
00232   unsigned char getPreferredTypeAlignmentShift(const Type *Ty) const;
00233 
00234   /// getIntPtrType - Return an unsigned integer type that is the same size or
00235   /// greater to the host pointer size.
00236   ///
00237   const IntegerType *getIntPtrType(LLVMContext &C) const;
00238 
00239   /// getIndexedOffset - return the offset from the beginning of the type for
00240   /// the specified indices.  This is used to implement getelementptr.
00241   ///
00242   uint64_t getIndexedOffset(const Type *Ty,
00243                             Value* const* Indices, unsigned NumIndices) const;
00244 
00245   /// getStructLayout - Return a StructLayout object, indicating the alignment
00246   /// of the struct, its size, and the offsets of its fields.  Note that this
00247   /// information is lazily cached.
00248   const StructLayout *getStructLayout(const StructType *Ty) const;
00249 
00250   /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
00251   /// objects.  If a TargetData object is alive when types are being refined and
00252   /// removed, this method must be called whenever a StructType is removed to
00253   /// avoid a dangling pointer in this cache.
00254   void InvalidateStructLayoutInfo(const StructType *Ty) const;
00255 
00256   /// getPreferredAlignment - Return the preferred alignment of the specified
00257   /// global.  This includes an explicitly requested alignment (if the global
00258   /// has one).
00259   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
00260 
00261   /// getPreferredAlignmentLog - Return the preferred alignment of the
00262   /// specified global, returned in log form.  This includes an explicitly
00263   /// requested alignment (if the global has one).
00264   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
00265 
00266   /// RoundUpAlignment - Round the specified value up to the next alignment
00267   /// boundary specified by Alignment.  For example, 7 rounded up to an
00268   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
00269   /// is 8 because it is already aligned.
00270   template <typename UIntTy>
00271   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
00272     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
00273     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
00274   }
00275   
00276   static char ID; // Pass identification, replacement for typeid
00277 };
00278 
00279 /// StructLayout - used to lazily calculate structure layout information for a
00280 /// target machine, based on the TargetData structure.
00281 ///
00282 class StructLayout {
00283   uint64_t StructSize;
00284   unsigned StructAlignment;
00285   unsigned NumElements;
00286   uint64_t MemberOffsets[1];  // variable sized array!
00287 public:
00288 
00289   uint64_t getSizeInBytes() const {
00290     return StructSize;
00291   }
00292 
00293   uint64_t getSizeInBits() const {
00294     return 8*StructSize;
00295   }
00296 
00297   unsigned getAlignment() const {
00298     return StructAlignment;
00299   }
00300 
00301   /// getElementContainingOffset - Given a valid byte offset into the structure,
00302   /// return the structure index that contains it.
00303   ///
00304   unsigned getElementContainingOffset(uint64_t Offset) const;
00305 
00306   uint64_t getElementOffset(unsigned Idx) const {
00307     assert(Idx < NumElements && "Invalid element idx!");
00308     return MemberOffsets[Idx];
00309   }
00310 
00311   uint64_t getElementOffsetInBits(unsigned Idx) const {
00312     return getElementOffset(Idx)*8;
00313   }
00314 
00315 private:
00316   friend class TargetData;   // Only TargetData can create this class
00317   StructLayout(const StructType *ST, const TargetData &TD);
00318 };
00319 
00320 } // End llvm namespace
00321 
00322 #endif