• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- llvm/Target/TargetData.h - Data size & alignment info ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines target properties related to datatype size/offset/alignment
11 // information.  It uses lazy annotations to cache information about how
12 // structure types are laid out and used.
13 //
14 // This structure should be created once, filled in if the defaults are not
15 // correct and then passed around by const&.  None of the members functions
16 // require modification to the object.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #ifndef LLVM_TARGET_TARGETDATA_H
21 #define LLVM_TARGET_TARGETDATA_H
22 
23 #include "llvm/Pass.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/DataTypes.h"
26 
27 namespace llvm {
28 
29 class Value;
30 class Type;
31 class IntegerType;
32 class StructType;
33 class StructLayout;
34 class GlobalVariable;
35 class LLVMContext;
36 template<typename T>
37 class ArrayRef;
38 
39 /// Enum used to categorize the alignment types stored by TargetAlignElem
40 enum AlignTypeEnum {
41   INTEGER_ALIGN = 'i',               ///< Integer type alignment
42   VECTOR_ALIGN = 'v',                ///< Vector type alignment
43   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
44   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
45   STACK_ALIGN = 's'                  ///< Stack objects alignment
46 };
47 
48 /// Target alignment element.
49 ///
50 /// Stores the alignment data associated with a given alignment type (pointer,
51 /// integer, vector, float) and type bit width.
52 ///
53 /// @note The unusual order of elements in the structure attempts to reduce
54 /// padding and make the structure slightly more cache friendly.
55 struct TargetAlignElem {
56   AlignTypeEnum       AlignType : 8;  //< Alignment type (AlignTypeEnum)
57   unsigned            ABIAlign;       //< ABI alignment for this type/bitw
58   unsigned            PrefAlign;      //< Pref. alignment for this type/bitw
59   uint32_t            TypeBitWidth;   //< Type bit width
60 
61   /// Initializer
62   static TargetAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
63                              unsigned pref_align, uint32_t bit_width);
64   /// Equality predicate
65   bool operator==(const TargetAlignElem &rhs) const;
66 };
67 
68 /// TargetData - This class holds a parsed version of the target data layout
69 /// string in a module and provides methods for querying it.  The target data
70 /// layout string is specified *by the target* - a frontend generating LLVM IR
71 /// is required to generate the right target data for the target being codegen'd
72 /// to.  If some measure of portability is desired, an empty string may be
73 /// specified in the module.
74 class TargetData : public ImmutablePass {
75 private:
76   bool          LittleEndian;          ///< Defaults to false
77   unsigned      PointerMemSize;        ///< Pointer size in bytes
78   unsigned      PointerABIAlign;       ///< Pointer ABI alignment
79   unsigned      PointerPrefAlign;      ///< Pointer preferred alignment
80   unsigned      StackNaturalAlign;     ///< Stack natural alignment
81 
82   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
83 
84   /// Alignments- Where the primitive type alignment data is stored.
85   ///
86   /// @sa init().
87   /// @note Could support multiple size pointer alignments, e.g., 32-bit
88   /// pointers vs. 64-bit pointers by extending TargetAlignment, but for now,
89   /// we don't.
90   SmallVector<TargetAlignElem, 16> Alignments;
91 
92   /// InvalidAlignmentElem - This member is a signal that a requested alignment
93   /// type and bit width were not found in the SmallVector.
94   static const TargetAlignElem InvalidAlignmentElem;
95 
96   // The StructType -> StructLayout map.
97   mutable void *LayoutMap;
98 
99   //! Set/initialize target alignments
100   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
101                     unsigned pref_align, uint32_t bit_width);
102   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
103                             bool ABIAlign, Type *Ty) const;
104   //! Internal helper method that returns requested alignment for type.
105   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
106 
107   /// Valid alignment predicate.
108   ///
109   /// Predicate that tests a TargetAlignElem reference returned by get() against
110   /// InvalidAlignmentElem.
validAlignment(const TargetAlignElem & align)111   bool validAlignment(const TargetAlignElem &align) const {
112     return &align != &InvalidAlignmentElem;
113   }
114 
115   /// Initialise a TargetData object with default values, ensure that the
116   /// target data pass is registered.
117   void init();
118 
119 public:
120   /// Default ctor.
121   ///
122   /// @note This has to exist, because this is a pass, but it should never be
123   /// used.
124   TargetData();
125 
126   /// Constructs a TargetData from a specification string. See init().
TargetData(StringRef TargetDescription)127   explicit TargetData(StringRef TargetDescription)
128     : ImmutablePass(ID) {
129     std::string errMsg = parseSpecifier(TargetDescription, this);
130     assert(errMsg == "" && "Invalid target data layout string.");
131     (void)errMsg;
132   }
133 
134   /// Parses a target data specification string. Returns an error message
135   /// if the string is malformed, or the empty string on success. Optionally
136   /// initialises a TargetData object if passed a non-null pointer.
137   static std::string parseSpecifier(StringRef TargetDescription, TargetData* td = 0);
138 
139   /// Initialize target data from properties stored in the module.
140   explicit TargetData(const Module *M);
141 
TargetData(const TargetData & TD)142   TargetData(const TargetData &TD) :
143     ImmutablePass(ID),
144     LittleEndian(TD.isLittleEndian()),
145     PointerMemSize(TD.PointerMemSize),
146     PointerABIAlign(TD.PointerABIAlign),
147     PointerPrefAlign(TD.PointerPrefAlign),
148     LegalIntWidths(TD.LegalIntWidths),
149     Alignments(TD.Alignments),
150     LayoutMap(0)
151   { }
152 
153   ~TargetData();  // Not virtual, do not subclass this class
154 
155   /// Target endianness...
isLittleEndian()156   bool isLittleEndian() const { return LittleEndian; }
isBigEndian()157   bool isBigEndian() const { return !LittleEndian; }
158 
159   /// getStringRepresentation - Return the string representation of the
160   /// TargetData.  This representation is in the same format accepted by the
161   /// string constructor above.
162   std::string getStringRepresentation() const;
163 
164   /// isLegalInteger - This function returns true if the specified type is
165   /// known to be a native integer type supported by the CPU.  For example,
166   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
167   /// one.  This returns false if the integer width is not legal.
168   ///
169   /// The width is specified in bits.
170   ///
isLegalInteger(unsigned Width)171   bool isLegalInteger(unsigned Width) const {
172     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
173       if (LegalIntWidths[i] == Width)
174         return true;
175     return false;
176   }
177 
isIllegalInteger(unsigned Width)178   bool isIllegalInteger(unsigned Width) const {
179     return !isLegalInteger(Width);
180   }
181 
182   /// Returns true if the given alignment exceeds the natural stack alignment.
exceedsNaturalStackAlignment(unsigned Align)183   bool exceedsNaturalStackAlignment(unsigned Align) const {
184     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
185   }
186 
187   /// fitsInLegalInteger - This function returns true if the specified type fits
188   /// in a native integer type supported by the CPU.  For example, if the CPU
189   /// only supports i32 as a native integer type, then i27 fits in a legal
190   // integer type but i45 does not.
fitsInLegalInteger(unsigned Width)191   bool fitsInLegalInteger(unsigned Width) const {
192     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
193       if (Width <= LegalIntWidths[i])
194         return true;
195     return false;
196   }
197 
198   /// Target pointer alignment
getPointerABIAlignment()199   unsigned getPointerABIAlignment() const { return PointerABIAlign; }
200   /// Return target's alignment for stack-based pointers
getPointerPrefAlignment()201   unsigned getPointerPrefAlignment() const { return PointerPrefAlign; }
202   /// Target pointer size
getPointerSize()203   unsigned getPointerSize()         const { return PointerMemSize; }
204   /// Target pointer size, in bits
getPointerSizeInBits()205   unsigned getPointerSizeInBits()   const { return 8*PointerMemSize; }
206 
207   /// Size examples:
208   ///
209   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
210   /// ----        ----------  ---------------  ---------------
211   ///  i1            1           8                8
212   ///  i8            8           8                8
213   ///  i19          19          24               32
214   ///  i32          32          32               32
215   ///  i100        100         104              128
216   ///  i128        128         128              128
217   ///  Float        32          32               32
218   ///  Double       64          64               64
219   ///  X86_FP80     80          80               96
220   ///
221   /// [*] The alloc size depends on the alignment, and thus on the target.
222   ///     These values are for x86-32 linux.
223 
224   /// getTypeSizeInBits - Return the number of bits necessary to hold the
225   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
226   uint64_t getTypeSizeInBits(Type* Ty) const;
227 
228   /// getTypeStoreSize - Return the maximum number of bytes that may be
229   /// overwritten by storing the specified type.  For example, returns 5
230   /// for i36 and 10 for x86_fp80.
getTypeStoreSize(Type * Ty)231   uint64_t getTypeStoreSize(Type *Ty) const {
232     return (getTypeSizeInBits(Ty)+7)/8;
233   }
234 
235   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
236   /// overwritten by storing the specified type; always a multiple of 8.  For
237   /// example, returns 40 for i36 and 80 for x86_fp80.
getTypeStoreSizeInBits(Type * Ty)238   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
239     return 8*getTypeStoreSize(Ty);
240   }
241 
242   /// getTypeAllocSize - Return the offset in bytes between successive objects
243   /// of the specified type, including alignment padding.  This is the amount
244   /// that alloca reserves for this type.  For example, returns 12 or 16 for
245   /// x86_fp80, depending on alignment.
getTypeAllocSize(Type * Ty)246   uint64_t getTypeAllocSize(Type* Ty) const {
247     // Round up to the next alignment boundary.
248     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
249   }
250 
251   /// getTypeAllocSizeInBits - Return the offset in bits between successive
252   /// objects of the specified type, including alignment padding; always a
253   /// multiple of 8.  This is the amount that alloca reserves for this type.
254   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
getTypeAllocSizeInBits(Type * Ty)255   uint64_t getTypeAllocSizeInBits(Type* Ty) const {
256     return 8*getTypeAllocSize(Ty);
257   }
258 
259   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
260   /// specified type.
261   unsigned getABITypeAlignment(Type *Ty) const;
262 
263   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
264   /// an integer type of the specified bitwidth.
265   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
266 
267 
268   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
269   /// for the specified type when it is part of a call frame.
270   unsigned getCallFrameTypeAlignment(Type *Ty) const;
271 
272 
273   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
274   /// the specified type.  This is always at least as good as the ABI alignment.
275   unsigned getPrefTypeAlignment(Type *Ty) const;
276 
277   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
278   /// specified type, returned as log2 of the value (a shift amount).
279   ///
280   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
281 
282   /// getIntPtrType - Return an unsigned integer type that is the same size or
283   /// greater to the host pointer size.
284   ///
285   IntegerType *getIntPtrType(LLVMContext &C) const;
286 
287   /// getIndexedOffset - return the offset from the beginning of the type for
288   /// the specified indices.  This is used to implement getelementptr.
289   ///
290   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
291 
292   /// getStructLayout - Return a StructLayout object, indicating the alignment
293   /// of the struct, its size, and the offsets of its fields.  Note that this
294   /// information is lazily cached.
295   const StructLayout *getStructLayout(StructType *Ty) const;
296 
297   /// getPreferredAlignment - Return the preferred alignment of the specified
298   /// global.  This includes an explicitly requested alignment (if the global
299   /// has one).
300   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
301 
302   /// getPreferredAlignmentLog - Return the preferred alignment of the
303   /// specified global, returned in log form.  This includes an explicitly
304   /// requested alignment (if the global has one).
305   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
306 
307   /// RoundUpAlignment - Round the specified value up to the next alignment
308   /// boundary specified by Alignment.  For example, 7 rounded up to an
309   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
310   /// is 8 because it is already aligned.
311   template <typename UIntTy>
RoundUpAlignment(UIntTy Val,unsigned Alignment)312   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
313     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
314     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
315   }
316 
317   static char ID; // Pass identification, replacement for typeid
318 };
319 
320 /// StructLayout - used to lazily calculate structure layout information for a
321 /// target machine, based on the TargetData structure.
322 ///
323 class StructLayout {
324   uint64_t StructSize;
325   unsigned StructAlignment;
326   unsigned NumElements;
327   uint64_t MemberOffsets[1];  // variable sized array!
328 public:
329 
getSizeInBytes()330   uint64_t getSizeInBytes() const {
331     return StructSize;
332   }
333 
getSizeInBits()334   uint64_t getSizeInBits() const {
335     return 8*StructSize;
336   }
337 
getAlignment()338   unsigned getAlignment() const {
339     return StructAlignment;
340   }
341 
342   /// getElementContainingOffset - Given a valid byte offset into the structure,
343   /// return the structure index that contains it.
344   ///
345   unsigned getElementContainingOffset(uint64_t Offset) const;
346 
getElementOffset(unsigned Idx)347   uint64_t getElementOffset(unsigned Idx) const {
348     assert(Idx < NumElements && "Invalid element idx!");
349     return MemberOffsets[Idx];
350   }
351 
getElementOffsetInBits(unsigned Idx)352   uint64_t getElementOffsetInBits(unsigned Idx) const {
353     return getElementOffset(Idx)*8;
354   }
355 
356 private:
357   friend class TargetData;   // Only TargetData can create this class
358   StructLayout(StructType *ST, const TargetData &TD);
359 };
360 
361 } // End llvm namespace
362 
363 #endif
364