Generalize TargetData strings, to support more interesting forms of data.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Support/DataTypes.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include <string>
27
28 namespace llvm {
29
30 class Value;
31 class Type;
32 class StructType;
33 class StructLayout;
34 class GlobalVariable;
35
36 /// Enum used to categorize the alignment types stored by TargetAlignElem
37 enum AlignTypeEnum {
38   INTEGER_ALIGN = 'i',               ///< Integer type alignment
39   PACKED_ALIGN = 'v',                ///< Vector type alignment
40   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
41   AGGREGATE_ALIGN = 'a'              ///< Aggregate alignment
42 };
43 /// Target alignment element.
44 ///
45 /// Stores the alignment data associated with a given alignment type (pointer,
46 /// integer, packed/vector, float) and type bit width.
47 ///
48 /// @note The unusual order of elements in the structure attempts to reduce
49 /// padding and make the structure slightly more cache friendly.
50 struct TargetAlignElem {
51   unsigned char       AlignType;      //< Alignment type (AlignTypeEnum)
52   unsigned char       ABIAlign;       //< ABI alignment for this type/bitw
53   unsigned char       PrefAlign;      //< Pref. alignment for this type/bitw
54   short               TypeBitWidth;   //< Type bit width
55
56   /// Initializer
57   static TargetAlignElem get(AlignTypeEnum align_type, unsigned char abi_align,
58                              unsigned char pref_align, short bit_width);
59   /// Less-than predicate
60   bool operator<(const TargetAlignElem &rhs) const;
61   /// Equality predicate
62   bool operator==(const TargetAlignElem &rhs) const;
63   /// output stream operator
64   std::ostream &dump(std::ostream &os) const;
65 };
66
67 //! TargetAlignElem output stream inserter
68 /*!
69   @sa TargetAlignElem::dump()
70  */
71 std::ostream &operator<<(std::ostream &os, const TargetAlignElem &elem);
72
73 class TargetData : public ImmutablePass {
74 private:
75   bool          LittleEndian;          ///< Defaults to false
76   unsigned char PointerMemSize;        ///< Pointer size in bytes
77   unsigned char PointerABIAlign;       ///< Pointer ABI alignment
78   unsigned char PointerPrefAlign;      ///< Pointer preferred global alignment
79
80   //! Where the primitive type alignment data is stored.
81   /*!
82    @sa init().
83    @note Could support multiple size pointer alignments, e.g., 32-bit pointers
84    vs. 64-bit pointers by extending TargetAlignment, but for now, we don't.
85    */
86   SmallVector<TargetAlignElem, 16> Alignments;
87   //! Alignment iterator shorthand
88   typedef SmallVector<TargetAlignElem, 16>::iterator align_iterator;
89   //! Constant alignment iterator shorthand
90   typedef SmallVector<TargetAlignElem, 16>::const_iterator align_const_iterator;
91   //! Invalid alignment.
92   /*!
93     This member is a signal that a requested alignment type and bit width were
94     not found in the SmallVector.
95    */
96   static const TargetAlignElem InvalidAlignmentElem;
97
98   //! Set/initialize target alignments
99   void setAlignment(AlignTypeEnum align_type, unsigned char abi_align,
100                     unsigned char pref_align, short bit_width);
101   //! Get TargetAlignElem from alignment type and bit width
102   const TargetAlignElem &getAlignment(AlignTypeEnum, short) const;
103   //! Internal helper method that returns requested alignment for type.
104   unsigned char getAlignment(const Type *Ty, bool abi_or_pref) const;
105
106   /// Valid alignment predicate.
107   ///
108   /// Predicate that tests a TargetAlignElem reference returned by get() against
109   /// InvalidAlignmentElem.
110   inline bool validAlignment(const TargetAlignElem &align) const {
111     return (&align != &InvalidAlignmentElem);
112   }
113
114 public:
115   /// Default ctor.
116   ///
117   /// @note This has to exist, because this is a pass, but it should never be
118   /// used.
119   TargetData() {
120     assert(0 && "ERROR: Bad TargetData ctor used.  "
121            "Tool did not specify a TargetData to use?");
122     abort();
123   }
124     
125   /// Constructs a TargetData from a specification string. See init().
126   TargetData(const std::string &TargetDescription) {
127     init(TargetDescription);
128   }
129
130   /// Initialize target data from properties stored in the module.
131   TargetData(const Module *M);
132
133   TargetData(const TargetData &TD) : 
134     ImmutablePass(),
135     LittleEndian(TD.isLittleEndian()),
136     PointerMemSize(TD.PointerMemSize),
137     PointerABIAlign(TD.PointerABIAlign),
138     PointerPrefAlign(TD.PointerPrefAlign),
139     Alignments(TD.Alignments)
140   { }
141
142   ~TargetData();  // Not virtual, do not subclass this class
143
144   //! Parse a target data layout string and initialize TargetData alignments.
145   void init(const std::string &TargetDescription);
146   
147   /// Target endianness...
148   bool          isLittleEndian()       const { return     LittleEndian; }
149   bool          isBigEndian()          const { return    !LittleEndian; }
150
151   /// getStringRepresentation - Return the string representation of the
152   /// TargetData.  This representation is in the same format accepted by the
153   /// string constructor above.
154   std::string getStringRepresentation() const;
155   /// Target pointer alignment
156   unsigned char getPointerABIAlignment() const { return PointerABIAlign; }
157   /// Return target's alignment for stack-based pointers
158   unsigned char getPointerPrefAlignment() const { return PointerPrefAlign; }
159   /// Target pointer size
160   unsigned char getPointerSize()         const { return PointerMemSize; }
161   /// Target pointer size, in bits
162   unsigned char getPointerSizeInBits()   const { return 8*PointerMemSize; }
163
164   /// getTypeSize - Return the number of bytes necessary to hold the specified
165   /// type.
166   uint64_t getTypeSize(const Type *Ty) const;
167
168   /// getTypeSizeInBits - Return the number of bytes necessary to hold the
169   /// specified type.
170   uint64_t getTypeSizeInBits(const Type* Ty) const;
171
172   /// getTypeAlignmentABI - Return the minimum ABI-required alignment for the
173   /// specified type.
174   unsigned char getABITypeAlignment(const Type *Ty) const;
175
176   /// getTypeAlignmentPref - Return the preferred stack/global alignment for
177   /// the specified type.
178   unsigned char getPrefTypeAlignment(const Type *Ty) const;
179
180   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
181   /// specified type, returned as log2 of the value (a shift amount).
182   ///
183   unsigned char getPreferredTypeAlignmentShift(const Type *Ty) const;
184
185   /// getIntPtrType - Return an unsigned integer type that is the same size or
186   /// greater to the host pointer size.
187   ///
188   const Type *getIntPtrType() const;
189
190   /// getIndexOffset - return the offset from the beginning of the type for the
191   /// specified indices.  This is used to implement getelementptr.
192   ///
193   uint64_t getIndexedOffset(const Type *Ty,
194                             Value* const* Indices, unsigned NumIndices) const;
195   
196   /// getStructLayout - Return a StructLayout object, indicating the alignment
197   /// of the struct, its size, and the offsets of its fields.  Note that this
198   /// information is lazily cached.
199   const StructLayout *getStructLayout(const StructType *Ty) const;
200   
201   /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
202   /// objects.  If a TargetData object is alive when types are being refined and
203   /// removed, this method must be called whenever a StructType is removed to
204   /// avoid a dangling pointer in this cache.
205   void InvalidateStructLayoutInfo(const StructType *Ty) const;
206
207   /// getPreferredAlignmentLog - Return the preferred alignment of the
208   /// specified global, returned in log form.  This includes an explicitly
209   /// requested alignment (if the global has one).
210   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
211 };
212
213 /// StructLayout - used to lazily calculate structure layout information for a
214 /// target machine, based on the TargetData structure.
215 ///
216 class StructLayout {
217   uint64_t StructSize;
218   unsigned StructAlignment;
219   unsigned NumElements;
220   uint64_t MemberOffsets[1];  // variable sized array!
221 public:
222
223   uint64_t getSizeInBytes() const {
224     return StructSize;
225   }
226   
227   unsigned getAlignment() const {
228     return StructAlignment;
229   }
230     
231   /// getElementContainingOffset - Given a valid offset into the structure,
232   /// return the structure index that contains it.
233   ///
234   unsigned getElementContainingOffset(uint64_t Offset) const;
235
236   uint64_t getElementOffset(unsigned Idx) const {
237     assert(Idx < NumElements && "Invalid element idx!");
238     return MemberOffsets[Idx];
239   }
240   
241 private:
242   friend class TargetData;   // Only TargetData can create this class
243   StructLayout(const StructType *ST, const TargetData &TD);
244 };
245
246 } // End llvm namespace
247
248 #endif