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