Teach TargetData to handle 'preferred' alignment for each target, and use
[oota-llvm.git] / lib / Target / TargetData.cpp
1 //===-- TargetData.cpp - Data size & alignment routines --------------------==//
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.
12 //
13 // This structure should be created once, filled in if the defaults are not
14 // correct and then passed around by const&.  None of the members functions
15 // require modification to the object.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Support/GetElementPtrTypeIterator.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include <algorithm>
27 #include <cstdlib>
28 #include <sstream>
29 using namespace llvm;
30
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 namespace {
33   // Register the default SparcV9 implementation...
34   RegisterPass<TargetData> X("targetdata", "Target Data Layout");
35 }
36
37 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
38                                   uint64_t &Size, unsigned char &Alignment);
39
40 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
41                                    uint64_t &Size, unsigned char &Alignment);
42
43 //===----------------------------------------------------------------------===//
44 // Support for StructLayout
45 //===----------------------------------------------------------------------===//
46
47 StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
48   StructAlignment = 0;
49   StructSize = 0;
50
51   // Loop over each of the elements, placing them in memory...
52   for (StructType::element_iterator TI = ST->element_begin(),
53          TE = ST->element_end(); TI != TE; ++TI) {
54     const Type *Ty = *TI;
55     unsigned char A;
56     unsigned TyAlign;
57     uint64_t TySize;
58     getTypeInfoABI(Ty, &TD, TySize, A);
59     TyAlign = ST->isPacked() ? 1 : A;
60
61     // Add padding if necessary to make the data element aligned properly...
62     if (StructSize % TyAlign != 0)
63       StructSize = (StructSize/TyAlign + 1) * TyAlign;   // Add padding...
64
65     // Keep track of maximum alignment constraint
66     StructAlignment = std::max(TyAlign, StructAlignment);
67
68     MemberOffsets.push_back(StructSize);
69     StructSize += TySize;                 // Consume space for this data item
70   }
71
72   // Empty structures have alignment of 1 byte.
73   if (StructAlignment == 0) StructAlignment = 1;
74
75   // Add padding to the end of the struct so that it could be put in an array
76   // and all array elements would be aligned correctly.
77   if (StructSize % StructAlignment != 0)
78     StructSize = (StructSize/StructAlignment + 1) * StructAlignment;
79 }
80
81
82 /// getElementContainingOffset - Given a valid offset into the structure,
83 /// return the structure index that contains it.
84 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
85   std::vector<uint64_t>::const_iterator SI =
86     std::upper_bound(MemberOffsets.begin(), MemberOffsets.end(), Offset);
87   assert(SI != MemberOffsets.begin() && "Offset not in structure type!");
88   --SI;
89   assert(*SI <= Offset && "upper_bound didn't work");
90   assert((SI == MemberOffsets.begin() || *(SI-1) < Offset) &&
91          (SI+1 == MemberOffsets.end() || *(SI+1) > Offset) &&
92          "Upper bound didn't work!");
93   return SI-MemberOffsets.begin();
94 }
95
96 //===----------------------------------------------------------------------===//
97 //                       TargetData Class Implementation
98 //===----------------------------------------------------------------------===//
99
100 void TargetData::init(const std::string &TargetDescription) {
101   std::string temp = TargetDescription;
102   
103   LittleEndian = false;
104   PointerMemSize = 8;
105   PointerABIAlignment   = 8;
106   DoubleABIAlignment = 8;
107   FloatABIAlignment = 4;
108   LongABIAlignment   = 8;
109   IntABIAlignment   = 4;
110   ShortABIAlignment  = 2;
111   ByteABIAlignment  = 1;
112   BoolABIAlignment   = 1;
113   BoolPrefAlignment = BoolABIAlignment;
114   BytePrefAlignment = ByteABIAlignment;
115   ShortPrefAlignment = ShortABIAlignment;
116   IntPrefAlignment = IntABIAlignment;
117   LongPrefAlignment = LongABIAlignment;
118   FloatPrefAlignment = FloatABIAlignment;
119   DoublePrefAlignment = DoubleABIAlignment;
120   PointerPrefAlignment = PointerABIAlignment;
121   AggMinPrefAlignment = 0;
122   
123   while (!temp.empty()) {
124     std::string token = getToken(temp, "-");
125     
126     char signal = getToken(token, ":")[0];
127     
128     switch(signal) {
129     case 'E':
130       LittleEndian = false;
131       break;
132     case 'e':
133       LittleEndian = true;
134       break;
135     case 'p':
136       PointerMemSize = atoi(getToken(token,":").c_str()) / 8;
137       PointerABIAlignment = atoi(getToken(token,":").c_str()) / 8;
138       PointerPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
139       if (PointerPrefAlignment == 0)
140         PointerPrefAlignment = PointerABIAlignment;
141       break;
142     case 'd':
143       DoubleABIAlignment = atoi(getToken(token,":").c_str()) / 8;
144       DoublePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
145       if (DoublePrefAlignment == 0)
146         DoublePrefAlignment = DoubleABIAlignment;
147       break;
148     case 'f':
149       FloatABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
150       FloatPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
151       if (FloatPrefAlignment == 0)
152         FloatPrefAlignment = FloatABIAlignment;
153       break;
154     case 'l':
155       LongABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
156       LongPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
157       if (LongPrefAlignment == 0)
158         LongPrefAlignment = LongABIAlignment;
159       break;
160     case 'i':
161       IntABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
162       IntPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
163       if (IntPrefAlignment == 0)
164         IntPrefAlignment = IntABIAlignment;
165       break;
166     case 's':
167       ShortABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
168       ShortPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
169       if (ShortPrefAlignment == 0)
170         ShortPrefAlignment = ShortABIAlignment;
171       break;
172     case 'b':
173       ByteABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
174       BytePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
175       if (BytePrefAlignment == 0)
176         BytePrefAlignment = ByteABIAlignment;
177       break;
178     case 'B':
179       BoolABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
180       BoolPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
181       if (BoolPrefAlignment == 0)
182         BoolPrefAlignment = BoolABIAlignment;
183       break;
184     case 'A':
185       AggMinPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
186       if (AggMinPrefAlignment == 0)
187         AggMinPrefAlignment = 0;
188       break;
189     default:
190       break;
191     }
192   }
193 }
194
195 TargetData::TargetData(const Module *M) {
196   LittleEndian       = M->getEndianness() != Module::BigEndian;
197   PointerMemSize     = M->getPointerSize() != Module::Pointer64 ? 4 : 8;
198   PointerABIAlignment = PointerMemSize;
199   DoubleABIAlignment  = PointerMemSize;
200   FloatABIAlignment   = 4;
201   LongABIAlignment    = PointerMemSize;
202   IntABIAlignment     = 4;
203   ShortABIAlignment   = 2;
204   ByteABIAlignment    = 1;
205   BoolABIAlignment    = 1;
206   BoolPrefAlignment = BoolABIAlignment;
207   BytePrefAlignment = ByteABIAlignment;
208   ShortPrefAlignment = ShortABIAlignment;
209   IntPrefAlignment = IntABIAlignment;
210   LongPrefAlignment = LongABIAlignment;
211   FloatPrefAlignment = FloatABIAlignment;
212   DoublePrefAlignment = DoubleABIAlignment;
213   PointerPrefAlignment = PointerABIAlignment;
214   AggMinPrefAlignment = 0;
215 }
216
217 /// Layouts - The lazy cache of structure layout information maintained by
218 /// TargetData.
219 ///
220 static std::map<std::pair<const TargetData*,const StructType*>,
221                 StructLayout> *Layouts = 0;
222
223
224 TargetData::~TargetData() {
225   if (Layouts) {
226     // Remove any layouts for this TD.
227     std::map<std::pair<const TargetData*,
228       const StructType*>, StructLayout>::iterator
229       I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));
230     while (I != Layouts->end() && I->first.first == this)
231       Layouts->erase(I++);
232     if (Layouts->empty()) {
233       delete Layouts;
234       Layouts = 0;
235     }
236   }
237 }
238
239 std::string TargetData::getStringRepresentation() const {
240   std::stringstream repr;
241   
242   if (LittleEndian)
243     repr << "e";
244   else
245     repr << "E";
246   
247   repr << "-p:" << (PointerMemSize * 8) << ":" << (PointerABIAlignment * 8);
248   repr << "-d:" << (DoubleABIAlignment * 8) << ":"
249        << (DoublePrefAlignment * 8);
250   repr << "-f:" << (FloatABIAlignment * 8) << ":"
251        << (FloatPrefAlignment * 8);
252   repr << "-l:" << (LongABIAlignment * 8) << ":"
253        << (LongPrefAlignment * 8);
254   repr << "-i:" << (IntABIAlignment * 8) << ":"
255        << (IntPrefAlignment * 8);
256   repr << "-s:" << (ShortABIAlignment * 8) << ":"
257        << (ShortPrefAlignment * 8);
258   repr << "-b:" << (ByteABIAlignment * 8) << ":"
259        << (BytePrefAlignment * 8);
260   repr << "-B:" << (BoolABIAlignment * 8) << ":"
261        << (BoolPrefAlignment * 8);
262   repr << "-A:" << (AggMinPrefAlignment * 8);
263   
264   return repr.str();
265 }
266
267 const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
268   if (Layouts == 0)
269     Layouts = new std::map<std::pair<const TargetData*,const StructType*>,
270                            StructLayout>();
271   std::map<std::pair<const TargetData*,const StructType*>,
272                      StructLayout>::iterator
273     I = Layouts->lower_bound(std::make_pair(this, Ty));
274   if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)
275     return &I->second;
276   else {
277     return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),
278                                               StructLayout(Ty, *this)))->second;
279   }
280 }
281
282 /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
283 /// objects.  If a TargetData object is alive when types are being refined and
284 /// removed, this method must be called whenever a StructType is removed to
285 /// avoid a dangling pointer in this cache.
286 void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {
287   if (!Layouts) return;  // No cache.
288
289   std::map<std::pair<const TargetData*,const StructType*>,
290            StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty));
291   if (I != Layouts->end())
292     Layouts->erase(I);
293 }
294
295
296
297 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
298                                   uint64_t &Size, unsigned char &Alignment) {
299   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
300   switch (Ty->getTypeID()) {
301   case Type::IntegerTyID: {
302     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
303     if (BitWidth <= 8) {
304       Size = 1; Alignment = TD->getByteABIAlignment();
305     } else if (BitWidth <= 16) {
306       Size = 2; Alignment = TD->getShortABIAlignment();
307     } else if (BitWidth <= 32) {
308       Size = 4; Alignment = TD->getIntABIAlignment();
309     } else if (BitWidth <= 64) {
310       Size = 8; Alignment = TD->getLongABIAlignment();
311     } else
312       assert(0 && "Integer types > 64 bits not supported.");
313     return;
314   }
315   case Type::VoidTyID:   Size = 1; Alignment = TD->getByteABIAlignment(); return;
316   case Type::FloatTyID:  Size = 4; Alignment = TD->getFloatABIAlignment(); return;
317   case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleABIAlignment(); return;
318   case Type::LabelTyID:
319   case Type::PointerTyID:
320     Size = TD->getPointerSize(); Alignment = TD->getPointerABIAlignment();
321     return;
322   case Type::ArrayTyID: {
323     const ArrayType *ATy = cast<ArrayType>(Ty);
324     getTypeInfoABI(ATy->getElementType(), TD, Size, Alignment);
325     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
326     Size = AlignedSize*ATy->getNumElements();
327     return;
328   }
329   case Type::PackedTyID: {
330     const PackedType *PTy = cast<PackedType>(Ty);
331     getTypeInfoABI(PTy->getElementType(), TD, Size, Alignment);
332     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
333     Size = AlignedSize*PTy->getNumElements();
334     // FIXME: The alignments of specific packed types are target dependent.
335     // For now, just set it to be equal to Size.
336     Alignment = Size;
337     return;
338   }
339   case Type::StructTyID: {
340     // Get the layout annotation... which is lazily created on demand.
341     const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
342     Size = Layout->StructSize; Alignment = Layout->StructAlignment;
343     return;
344   }
345
346   default:
347     assert(0 && "Bad type for getTypeInfo!!!");
348     return;
349   }
350 }
351
352 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
353                                    uint64_t &Size, unsigned char &Alignment) {
354   assert(Ty->isSized() && "Cannot getTypeInfoPref() on a type that is unsized!");
355   switch (Ty->getTypeID()) {
356   case Type::IntegerTyID: {
357     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
358     if (BitWidth <= 8) {
359       Size = 1; Alignment = TD->getBytePrefAlignment();
360     } else if (BitWidth <= 16) {
361       Size = 2; Alignment = TD->getShortPrefAlignment();
362     } else if (BitWidth <= 32) {
363       Size = 4; Alignment = TD->getIntPrefAlignment();
364     } else if (BitWidth <= 64) {
365       Size = 8; Alignment = TD->getLongPrefAlignment();
366     } else
367       assert(0 && "Integer types > 64 bits not supported.");
368     return;
369   }
370   case Type::VoidTyID:
371     Size = 1; Alignment = TD->getBytePrefAlignment();
372     return;
373   case Type::FloatTyID:
374     Size = 4; Alignment = TD->getFloatPrefAlignment();
375     return;
376   case Type::DoubleTyID:
377     Size = 8; Alignment = TD->getDoublePrefAlignment();
378     return;
379   case Type::LabelTyID:
380   case Type::PointerTyID:
381     Size = TD->getPointerSize(); Alignment = TD->getPointerPrefAlignment();
382     return;
383   case Type::ArrayTyID: {
384     const ArrayType *ATy = cast<ArrayType>(Ty);
385     getTypeInfoPref(ATy->getElementType(), TD, Size, Alignment);
386     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
387     Size = AlignedSize*ATy->getNumElements();
388     return;
389   }
390   case Type::PackedTyID: {
391     const PackedType *PTy = cast<PackedType>(Ty);
392     getTypeInfoPref(PTy->getElementType(), TD, Size, Alignment);
393     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
394     Size = AlignedSize*PTy->getNumElements();
395     // FIXME: The alignments of specific packed types are target dependent.
396     // For now, just set it to be equal to Size.
397     Alignment = Size;
398     return;
399   }
400   case Type::StructTyID: {
401     // Get the layout annotation... which is lazily created on demand;
402     // enforce minimum aggregate alignment.
403     const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
404     Size = Layout->StructSize;
405     Alignment = std::max(Layout->StructAlignment,
406                          (const unsigned int) TD->getAggMinPrefAlignment());
407     return;
408   }
409
410   default:
411     assert(0 && "Bad type for getTypeInfoPref!!!");
412     return;
413   }
414 }
415
416
417 uint64_t TargetData::getTypeSize(const Type *Ty) const {
418   uint64_t Size;
419   unsigned char Align;
420   getTypeInfoABI(Ty, this, Size, Align);
421   return Size;
422 }
423
424 unsigned char TargetData::getTypeAlignmentABI(const Type *Ty) const {
425   uint64_t Size;
426   unsigned char Align;
427   getTypeInfoABI(Ty, this, Size, Align);
428   return Align;
429 }
430
431 unsigned char TargetData::getTypeAlignmentPref(const Type *Ty) const {
432   uint64_t Size;
433   unsigned char Align;
434   getTypeInfoPref(Ty, this, Size, Align);
435   return Align;
436 }
437
438 unsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const {
439   unsigned Align = getTypeAlignmentABI(Ty);
440   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
441   return Log2_32(Align);
442 }
443
444 /// getIntPtrType - Return an unsigned integer type that is the same size or
445 /// greater to the host pointer size.
446 const Type *TargetData::getIntPtrType() const {
447   switch (getPointerSize()) {
448   default: assert(0 && "Unknown pointer size!");
449   case 2: return Type::Int16Ty;
450   case 4: return Type::Int32Ty;
451   case 8: return Type::Int64Ty;
452   }
453 }
454
455
456 uint64_t TargetData::getIndexedOffset(const Type *ptrTy,
457                                       const std::vector<Value*> &Idx) const {
458   const Type *Ty = ptrTy;
459   assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
460   uint64_t Result = 0;
461
462   generic_gep_type_iterator<std::vector<Value*>::const_iterator>
463     TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());
464   for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {
465     if (const StructType *STy = dyn_cast<StructType>(*TI)) {
466       assert(Idx[CurIDX]->getType() == Type::Int32Ty && "Illegal struct idx");
467       unsigned FieldNo = cast<ConstantInt>(Idx[CurIDX])->getZExtValue();
468
469       // Get structure layout information...
470       const StructLayout *Layout = getStructLayout(STy);
471
472       // Add in the offset, as calculated by the structure layout info...
473       assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!");
474       Result += Layout->MemberOffsets[FieldNo];
475
476       // Update Ty to refer to current element
477       Ty = STy->getElementType(FieldNo);
478     } else {
479       // Update Ty to refer to current element
480       Ty = cast<SequentialType>(Ty)->getElementType();
481
482       // Get the array index and the size of each array element.
483       int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getSExtValue();
484       Result += arrayIdx * (int64_t)getTypeSize(Ty);
485     }
486   }
487
488   return Result;
489 }
490
491 /// getPreferredAlignmentLog - Return the preferred alignment of the
492 /// specified global, returned in log form.  This includes an explicitly
493 /// requested alignment (if the global has one).
494 unsigned TargetData::getPreferredAlignmentLog(const GlobalVariable *GV) const {
495   const Type *ElemType = GV->getType()->getElementType();
496   unsigned Alignment = getTypeAlignmentShift(ElemType);
497   if (GV->getAlignment() > (1U << Alignment))
498     Alignment = Log2_32(GV->getAlignment());
499   
500   if (GV->hasInitializer()) {
501     // Always round up alignment of global doubles to 8 bytes.
502     if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
503       Alignment = 3;
504     if (Alignment < 4) {
505       // If the global is not external, see if it is large.  If so, give it a
506       // larger alignment.
507       if (getTypeSize(ElemType) > 128)
508         Alignment = 4;    // 16-byte alignment.
509     }
510   }
511   return Alignment;
512 }
513