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