[un]wrap extracted from lib/Target/Target[MachineC].cpp, lib/ExecutionEngine/Executio...
[oota-llvm.git] / include / llvm / IR / DataLayout.h
1 //===--------- llvm/DataLayout.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 layout 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_IR_DATALAYOUT_H
21 #define LLVM_IR_DATALAYOUT_H
22
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/DataTypes.h"
29
30 namespace llvm {
31
32 class Value;
33 class Type;
34 class IntegerType;
35 class StructType;
36 class StructLayout;
37 class Triple;
38 class GlobalVariable;
39 class LLVMContext;
40 template<typename T>
41 class ArrayRef;
42
43 /// Enum used to categorize the alignment types stored by LayoutAlignElem
44 enum AlignTypeEnum {
45   INVALID_ALIGN = 0,                 ///< An invalid alignment
46   INTEGER_ALIGN = 'i',               ///< Integer type alignment
47   VECTOR_ALIGN = 'v',                ///< Vector type alignment
48   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
49   AGGREGATE_ALIGN = 'a'              ///< Aggregate alignment
50 };
51
52 /// Layout alignment element.
53 ///
54 /// Stores the alignment data associated with a given alignment type (integer,
55 /// vector, float) and type bit width.
56 ///
57 /// @note The unusual order of elements in the structure attempts to reduce
58 /// padding and make the structure slightly more cache friendly.
59 struct LayoutAlignElem {
60   unsigned AlignType    : 8;  ///< Alignment type (AlignTypeEnum)
61   unsigned TypeBitWidth : 24; ///< Type bit width
62   unsigned ABIAlign     : 16; ///< ABI alignment for this type/bitw
63   unsigned PrefAlign    : 16; ///< Pref. alignment for this type/bitw
64
65   /// Initializer
66   static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
67                              unsigned pref_align, uint32_t bit_width);
68   /// Equality predicate
69   bool operator==(const LayoutAlignElem &rhs) const;
70 };
71
72 /// Layout pointer alignment element.
73 ///
74 /// Stores the alignment data associated with a given pointer and address space.
75 ///
76 /// @note The unusual order of elements in the structure attempts to reduce
77 /// padding and make the structure slightly more cache friendly.
78 struct PointerAlignElem {
79   unsigned            ABIAlign;       ///< ABI alignment for this type/bitw
80   unsigned            PrefAlign;      ///< Pref. alignment for this type/bitw
81   uint32_t            TypeByteWidth;  ///< Type byte width
82   uint32_t            AddressSpace;   ///< Address space for the pointer type
83
84   /// Initializer
85   static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign,
86                              unsigned PrefAlign, uint32_t TypeByteWidth);
87   /// Equality predicate
88   bool operator==(const PointerAlignElem &rhs) const;
89 };
90
91 /// This class holds a parsed version of the target data layout string in a
92 /// module and provides methods for querying it. The target data layout string
93 /// is specified *by the target* - a frontend generating LLVM IR is required to
94 /// generate the right target data for the target being codegen'd to.
95 class DataLayout {
96 private:
97   bool          LittleEndian;          ///< Defaults to false
98   unsigned      StackNaturalAlign;     ///< Stack natural alignment
99
100   enum ManglingModeT {
101     MM_None,
102     MM_ELF,
103     MM_MachO,
104     MM_WINCOFF,
105     MM_Mips
106   };
107   ManglingModeT ManglingMode;
108
109   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
110
111   /// Alignments - Where the primitive type alignment data is stored.
112   ///
113   /// @sa reset().
114   /// @note Could support multiple size pointer alignments, e.g., 32-bit
115   /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
116   /// we don't.
117   SmallVector<LayoutAlignElem, 16> Alignments;
118   typedef SmallVector<PointerAlignElem, 8> PointersTy;
119   PointersTy Pointers;
120
121   PointersTy::const_iterator
122   findPointerLowerBound(uint32_t AddressSpace) const {
123     return const_cast<DataLayout *>(this)->findPointerLowerBound(AddressSpace);
124   }
125
126   PointersTy::iterator findPointerLowerBound(uint32_t AddressSpace);
127
128   /// InvalidAlignmentElem - This member is a signal that a requested alignment
129   /// type and bit width were not found in the SmallVector.
130   static const LayoutAlignElem InvalidAlignmentElem;
131
132   /// InvalidPointerElem - This member is a signal that a requested pointer
133   /// type and bit width were not found in the DenseSet.
134   static const PointerAlignElem InvalidPointerElem;
135
136   // The StructType -> StructLayout map.
137   mutable void *LayoutMap;
138
139   //! Set/initialize target alignments
140   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
141                     unsigned pref_align, uint32_t bit_width);
142   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
143                             bool ABIAlign, Type *Ty) const;
144
145   //! Set/initialize pointer alignments
146   void setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
147                            unsigned PrefAlign, uint32_t TypeByteWidth);
148
149   //! Internal helper method that returns requested alignment for type.
150   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
151
152   /// Valid alignment predicate.
153   ///
154   /// Predicate that tests a LayoutAlignElem reference returned by get() against
155   /// InvalidAlignmentElem.
156   bool validAlignment(const LayoutAlignElem &align) const {
157     return &align != &InvalidAlignmentElem;
158   }
159
160   /// Valid pointer predicate.
161   ///
162   /// Predicate that tests a PointerAlignElem reference returned by get() against
163   /// InvalidPointerElem.
164   bool validPointer(const PointerAlignElem &align) const {
165     return &align != &InvalidPointerElem;
166   }
167
168   /// Parses a target data specification string. Assert if the string is
169   /// malformed.
170   void parseSpecifier(StringRef LayoutDescription);
171
172   // Free all internal data structures.
173   void clear();
174
175 public:
176   /// Constructs a DataLayout from a specification string. See reset().
177   explicit DataLayout(StringRef LayoutDescription) : LayoutMap(nullptr) {
178     reset(LayoutDescription);
179   }
180
181   /// Initialize target data from properties stored in the module.
182   explicit DataLayout(const Module *M);
183
184   DataLayout(const DataLayout &DL) : LayoutMap(nullptr) { *this = DL; }
185
186   DataLayout &operator=(const DataLayout &DL) {
187     clear();
188     LittleEndian = DL.isLittleEndian();
189     StackNaturalAlign = DL.StackNaturalAlign;
190     ManglingMode = DL.ManglingMode;
191     LegalIntWidths = DL.LegalIntWidths;
192     Alignments = DL.Alignments;
193     Pointers = DL.Pointers;
194     return *this;
195   }
196
197   bool operator==(const DataLayout &Other) const;
198   bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
199
200   ~DataLayout();  // Not virtual, do not subclass this class
201
202   /// Parse a data layout string (with fallback to default values).
203   void reset(StringRef LayoutDescription);
204
205   /// Layout endianness...
206   bool isLittleEndian() const { return LittleEndian; }
207   bool isBigEndian() const { return !LittleEndian; }
208
209   /// getStringRepresentation - Return the string representation of the
210   /// DataLayout.  This representation is in the same format accepted by the
211   /// string constructor above.
212   std::string getStringRepresentation() const;
213
214   /// isLegalInteger - This function returns true if the specified type is
215   /// known to be a native integer type supported by the CPU.  For example,
216   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
217   /// one.  This returns false if the integer width is not legal.
218   ///
219   /// The width is specified in bits.
220   ///
221   bool isLegalInteger(unsigned Width) const {
222     for (unsigned LegalIntWidth : LegalIntWidths)
223       if (LegalIntWidth == Width)
224         return true;
225     return false;
226   }
227
228   bool isIllegalInteger(unsigned Width) const {
229     return !isLegalInteger(Width);
230   }
231
232   /// Returns true if the given alignment exceeds the natural stack alignment.
233   bool exceedsNaturalStackAlignment(unsigned Align) const {
234     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
235   }
236
237   bool hasMicrosoftFastStdCallMangling() const {
238     return ManglingMode == MM_WINCOFF;
239   }
240
241   bool hasLinkerPrivateGlobalPrefix() const {
242     return ManglingMode == MM_MachO;
243   }
244
245   const char *getLinkerPrivateGlobalPrefix() const {
246     if (ManglingMode == MM_MachO)
247       return "l";
248     return getPrivateGlobalPrefix();
249   }
250
251   char getGlobalPrefix() const {
252     switch (ManglingMode) {
253     case MM_None:
254     case MM_ELF:
255     case MM_Mips:
256       return '\0';
257     case MM_MachO:
258     case MM_WINCOFF:
259       return '_';
260     }
261     llvm_unreachable("invalid mangling mode");
262   }
263
264   const char *getPrivateGlobalPrefix() const {
265     switch (ManglingMode) {
266     case MM_None:
267       return "";
268     case MM_ELF:
269       return ".L";
270     case MM_Mips:
271       return "$";
272     case MM_MachO:
273     case MM_WINCOFF:
274       return "L";
275     }
276     llvm_unreachable("invalid mangling mode");
277   }
278
279   static const char *getManglingComponent(const Triple &T);
280
281   /// fitsInLegalInteger - This function returns true if the specified type fits
282   /// in a native integer type supported by the CPU.  For example, if the CPU
283   /// only supports i32 as a native integer type, then i27 fits in a legal
284   /// integer type but i45 does not.
285   bool fitsInLegalInteger(unsigned Width) const {
286     for (unsigned LegalIntWidth : LegalIntWidths)
287       if (Width <= LegalIntWidth)
288         return true;
289     return false;
290   }
291
292   /// Layout pointer alignment
293   /// FIXME: The defaults need to be removed once all of
294   /// the backends/clients are updated.
295   unsigned getPointerABIAlignment(unsigned AS = 0) const;
296
297   /// Return target's alignment for stack-based pointers
298   /// FIXME: The defaults need to be removed once all of
299   /// the backends/clients are updated.
300   unsigned getPointerPrefAlignment(unsigned AS = 0) const;
301
302   /// Layout pointer size
303   /// FIXME: The defaults need to be removed once all of
304   /// the backends/clients are updated.
305   unsigned getPointerSize(unsigned AS = 0) const;
306
307   /// Layout pointer size, in bits
308   /// FIXME: The defaults need to be removed once all of
309   /// the backends/clients are updated.
310   unsigned getPointerSizeInBits(unsigned AS = 0) const {
311     return getPointerSize(AS) * 8;
312   }
313
314   /// Layout pointer size, in bits, based on the type.  If this function is
315   /// called with a pointer type, then the type size of the pointer is returned.
316   /// If this function is called with a vector of pointers, then the type size
317   /// of the pointer is returned.  This should only be called with a pointer or
318   /// vector of pointers.
319   unsigned getPointerTypeSizeInBits(Type *) const;
320
321   unsigned getPointerTypeSize(Type *Ty) const {
322     return getPointerTypeSizeInBits(Ty) / 8;
323   }
324
325   /// Size examples:
326   ///
327   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
328   /// ----        ----------  ---------------  ---------------
329   ///  i1            1           8                8
330   ///  i8            8           8                8
331   ///  i19          19          24               32
332   ///  i32          32          32               32
333   ///  i100        100         104              128
334   ///  i128        128         128              128
335   ///  Float        32          32               32
336   ///  Double       64          64               64
337   ///  X86_FP80     80          80               96
338   ///
339   /// [*] The alloc size depends on the alignment, and thus on the target.
340   ///     These values are for x86-32 linux.
341
342   /// getTypeSizeInBits - Return the number of bits necessary to hold the
343   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
344   /// The type passed must have a size (Type::isSized() must return true).
345   uint64_t getTypeSizeInBits(Type *Ty) const;
346
347   /// getTypeStoreSize - Return the maximum number of bytes that may be
348   /// overwritten by storing the specified type.  For example, returns 5
349   /// for i36 and 10 for x86_fp80.
350   uint64_t getTypeStoreSize(Type *Ty) const {
351     return (getTypeSizeInBits(Ty)+7)/8;
352   }
353
354   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
355   /// overwritten by storing the specified type; always a multiple of 8.  For
356   /// example, returns 40 for i36 and 80 for x86_fp80.
357   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
358     return 8*getTypeStoreSize(Ty);
359   }
360
361   /// getTypeAllocSize - Return the offset in bytes between successive objects
362   /// of the specified type, including alignment padding.  This is the amount
363   /// that alloca reserves for this type.  For example, returns 12 or 16 for
364   /// x86_fp80, depending on alignment.
365   uint64_t getTypeAllocSize(Type *Ty) const {
366     // Round up to the next alignment boundary.
367     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
368   }
369
370   /// getTypeAllocSizeInBits - Return the offset in bits between successive
371   /// objects of the specified type, including alignment padding; always a
372   /// multiple of 8.  This is the amount that alloca reserves for this type.
373   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
374   uint64_t getTypeAllocSizeInBits(Type *Ty) const {
375     return 8*getTypeAllocSize(Ty);
376   }
377
378   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
379   /// specified type.
380   unsigned getABITypeAlignment(Type *Ty) const;
381
382   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
383   /// an integer type of the specified bitwidth.
384   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
385
386   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
387   /// the specified type.  This is always at least as good as the ABI alignment.
388   unsigned getPrefTypeAlignment(Type *Ty) const;
389
390   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
391   /// specified type, returned as log2 of the value (a shift amount).
392   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
393
394   /// getIntPtrType - Return an integer type with size at least as big as that
395   /// of a pointer in the given address space.
396   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
397
398   /// getIntPtrType - Return an integer (vector of integer) type with size at
399   /// least as big as that of a pointer of the given pointer (vector of pointer)
400   /// type.
401   Type *getIntPtrType(Type *) const;
402
403   /// getSmallestLegalIntType - Return the smallest integer type with size at
404   /// least as big as Width bits.
405   Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
406
407   /// getLargestLegalIntType - Return the largest legal integer type, or null if
408   /// none are set.
409   Type *getLargestLegalIntType(LLVMContext &C) const {
410     unsigned LargestSize = getLargestLegalIntTypeSize();
411     return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
412   }
413
414   /// getLargestLegalIntType - Return the size of largest legal integer type
415   /// size, or 0 if none are set.
416   unsigned getLargestLegalIntTypeSize() const;
417
418   /// getIndexedOffset - return the offset from the beginning of the type for
419   /// the specified indices.  This is used to implement getelementptr.
420   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
421
422   /// getStructLayout - Return a StructLayout object, indicating the alignment
423   /// of the struct, its size, and the offsets of its fields.  Note that this
424   /// information is lazily cached.
425   const StructLayout *getStructLayout(StructType *Ty) const;
426
427   /// getPreferredAlignment - Return the preferred alignment of the specified
428   /// global.  This includes an explicitly requested alignment (if the global
429   /// has one).
430   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
431
432   /// getPreferredAlignmentLog - Return the preferred alignment of the
433   /// specified global, returned in log form.  This includes an explicitly
434   /// requested alignment (if the global has one).
435   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
436
437   /// RoundUpAlignment - Round the specified value up to the next alignment
438   /// boundary specified by Alignment.  For example, 7 rounded up to an
439   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
440   /// is 8 because it is already aligned.
441   template <typename UIntTy>
442   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
443     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
444     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
445   }
446 };
447
448 typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
449
450 inline DataLayout *unwrap(LLVMTargetDataRef P) {
451    return reinterpret_cast<DataLayout*>(P);
452 }
453
454 inline LLVMTargetDataRef wrap(const DataLayout *P) {
455    return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
456 }
457
458 class DataLayoutPass : public ImmutablePass {
459   DataLayout DL;
460
461 public:
462   /// This has to exist, because this is a pass, but it should never be used.
463   DataLayoutPass();
464   ~DataLayoutPass();
465
466   const DataLayout &getDataLayout() const { return DL; }
467
468   // For use with the C API. C++ code should always use the constructor that
469   // takes a module.
470   explicit DataLayoutPass(const DataLayout &DL);
471
472   explicit DataLayoutPass(const Module *M);
473
474   static char ID; // Pass identification, replacement for typeid
475 };
476
477 /// StructLayout - used to lazily calculate structure layout information for a
478 /// target machine, based on the DataLayout structure.
479 ///
480 class StructLayout {
481   uint64_t StructSize;
482   unsigned StructAlignment;
483   unsigned NumElements;
484   uint64_t MemberOffsets[1];  // variable sized array!
485 public:
486
487   uint64_t getSizeInBytes() const {
488     return StructSize;
489   }
490
491   uint64_t getSizeInBits() const {
492     return 8*StructSize;
493   }
494
495   unsigned getAlignment() const {
496     return StructAlignment;
497   }
498
499   /// getElementContainingOffset - Given a valid byte offset into the structure,
500   /// return the structure index that contains it.
501   ///
502   unsigned getElementContainingOffset(uint64_t Offset) const;
503
504   uint64_t getElementOffset(unsigned Idx) const {
505     assert(Idx < NumElements && "Invalid element idx!");
506     return MemberOffsets[Idx];
507   }
508
509   uint64_t getElementOffsetInBits(unsigned Idx) const {
510     return getElementOffset(Idx)*8;
511   }
512
513 private:
514   friend class DataLayout;   // Only DataLayout can create this class
515   StructLayout(StructType *ST, const DataLayout &DL);
516 };
517
518
519 // The implementation of this method is provided inline as it is particularly
520 // well suited to constant folding when called on a specific Type subclass.
521 inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
522   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
523   switch (Ty->getTypeID()) {
524   case Type::LabelTyID:
525     return getPointerSizeInBits(0);
526   case Type::PointerTyID:
527     return getPointerSizeInBits(Ty->getPointerAddressSpace());
528   case Type::ArrayTyID: {
529     ArrayType *ATy = cast<ArrayType>(Ty);
530     return ATy->getNumElements() *
531            getTypeAllocSizeInBits(ATy->getElementType());
532   }
533   case Type::StructTyID:
534     // Get the layout annotation... which is lazily created on demand.
535     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
536   case Type::IntegerTyID:
537     return Ty->getIntegerBitWidth();
538   case Type::HalfTyID:
539     return 16;
540   case Type::FloatTyID:
541     return 32;
542   case Type::DoubleTyID:
543   case Type::X86_MMXTyID:
544     return 64;
545   case Type::PPC_FP128TyID:
546   case Type::FP128TyID:
547     return 128;
548     // In memory objects this is always aligned to a higher boundary, but
549   // only 80 bits contain information.
550   case Type::X86_FP80TyID:
551     return 80;
552   case Type::VectorTyID: {
553     VectorType *VTy = cast<VectorType>(Ty);
554     return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
555   }
556   default:
557     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
558   }
559 }
560
561 } // End llvm namespace
562
563 #endif