Stylistic tweak.
[oota-llvm.git] / lib / VMCore / DataLayout.cpp
1 //===-- DataLayout.cpp - Data size & alignment routines --------------------==//
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.
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/DataLayout.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cstdlib>
32 using namespace llvm;
33
34 // Handle the Pass registration stuff necessary to use DataLayout's.
35
36 // Register the default SparcV9 implementation...
37 INITIALIZE_PASS(DataLayout, "datalayout", "Data Layout", false, true)
38 char DataLayout::ID = 0;
39
40 //===----------------------------------------------------------------------===//
41 // Support for StructLayout
42 //===----------------------------------------------------------------------===//
43
44 StructLayout::StructLayout(StructType *ST, const DataLayout &TD) {
45   assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
46   StructAlignment = 0;
47   StructSize = 0;
48   NumElements = ST->getNumElements();
49
50   // Loop over each of the elements, placing them in memory.
51   for (unsigned i = 0, e = NumElements; i != e; ++i) {
52     Type *Ty = ST->getElementType(i);
53     unsigned TyAlign = ST->isPacked() ? 1 : TD.getABITypeAlignment(Ty);
54
55     // Add padding if necessary to align the data element properly.
56     if ((StructSize & (TyAlign-1)) != 0)
57       StructSize = DataLayout::RoundUpAlignment(StructSize, TyAlign);
58
59     // Keep track of maximum alignment constraint.
60     StructAlignment = std::max(TyAlign, StructAlignment);
61
62     MemberOffsets[i] = StructSize;
63     StructSize += TD.getTypeAllocSize(Ty); // Consume space for this data item
64   }
65
66   // Empty structures have alignment of 1 byte.
67   if (StructAlignment == 0) StructAlignment = 1;
68
69   // Add padding to the end of the struct so that it could be put in an array
70   // and all array elements would be aligned correctly.
71   if ((StructSize & (StructAlignment-1)) != 0)
72     StructSize = DataLayout::RoundUpAlignment(StructSize, StructAlignment);
73 }
74
75
76 /// getElementContainingOffset - Given a valid offset into the structure,
77 /// return the structure index that contains it.
78 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
79   const uint64_t *SI =
80     std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
81   assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
82   --SI;
83   assert(*SI <= Offset && "upper_bound didn't work");
84   assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
85          (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
86          "Upper bound didn't work!");
87
88   // Multiple fields can have the same offset if any of them are zero sized.
89   // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
90   // at the i32 element, because it is the last element at that offset.  This is
91   // the right one to return, because anything after it will have a higher
92   // offset, implying that this element is non-empty.
93   return SI-&MemberOffsets[0];
94 }
95
96 //===----------------------------------------------------------------------===//
97 // LayoutAlignElem, LayoutAlign support
98 //===----------------------------------------------------------------------===//
99
100 LayoutAlignElem
101 LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
102                      unsigned pref_align, uint32_t bit_width) {
103   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
104   LayoutAlignElem retval;
105   retval.AlignType = align_type;
106   retval.ABIAlign = abi_align;
107   retval.PrefAlign = pref_align;
108   retval.TypeBitWidth = bit_width;
109   return retval;
110 }
111
112 bool
113 LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
114   return (AlignType == rhs.AlignType
115           && ABIAlign == rhs.ABIAlign
116           && PrefAlign == rhs.PrefAlign
117           && TypeBitWidth == rhs.TypeBitWidth);
118 }
119
120 const LayoutAlignElem
121 DataLayout::InvalidAlignmentElem =
122             LayoutAlignElem::get((AlignTypeEnum) -1, 0, 0, 0);
123
124 //===----------------------------------------------------------------------===//
125 // PointerAlignElem, PointerAlign support
126 //===----------------------------------------------------------------------===//
127
128 PointerAlignElem
129 PointerAlignElem::get(uint32_t addr_space, unsigned abi_align,
130                      unsigned pref_align, uint32_t bit_width) {
131   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
132   PointerAlignElem retval;
133   retval.AddressSpace = addr_space;
134   retval.ABIAlign = abi_align;
135   retval.PrefAlign = pref_align;
136   retval.TypeBitWidth = bit_width;
137   return retval;
138 }
139
140 bool
141 PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
142   return (ABIAlign == rhs.ABIAlign
143           && AddressSpace == rhs.AddressSpace
144           && PrefAlign == rhs.PrefAlign
145           && TypeBitWidth == rhs.TypeBitWidth);
146 }
147
148 const PointerAlignElem
149 DataLayout::InvalidPointerElem = PointerAlignElem::get(~0U, 0U, 0U, 0U);
150
151 //===----------------------------------------------------------------------===//
152 //                       DataLayout Class Implementation
153 //===----------------------------------------------------------------------===//
154
155 void DataLayout::init(StringRef Desc) {
156   initializeDataLayoutPass(*PassRegistry::getPassRegistry());
157
158   LayoutMap = 0;
159   LittleEndian = false;
160   StackNaturalAlign = 0;
161
162   // Default alignments
163   setAlignment(INTEGER_ALIGN,   1,  1, 1);   // i1
164   setAlignment(INTEGER_ALIGN,   1,  1, 8);   // i8
165   setAlignment(INTEGER_ALIGN,   2,  2, 16);  // i16
166   setAlignment(INTEGER_ALIGN,   4,  4, 32);  // i32
167   setAlignment(INTEGER_ALIGN,   4,  8, 64);  // i64
168   setAlignment(FLOAT_ALIGN,     2,  2, 16);  // half
169   setAlignment(FLOAT_ALIGN,     4,  4, 32);  // float
170   setAlignment(FLOAT_ALIGN,     8,  8, 64);  // double
171   setAlignment(FLOAT_ALIGN,    16, 16, 128); // ppcf128, quad, ...
172   setAlignment(VECTOR_ALIGN,    8,  8, 64);  // v2i32, v1i64, ...
173   setAlignment(VECTOR_ALIGN,   16, 16, 128); // v16i8, v8i16, v4i32, ...
174   setAlignment(AGGREGATE_ALIGN, 0,  8,  0);  // struct
175   setPointerAlignment(0, 8, 8, 8);
176
177   parseSpecifier(Desc);
178 }
179
180 /// Checked version of split, to ensure mandatory subparts.
181 static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
182   assert(!Str.empty() && "parse error, string can't be empty here");
183   std::pair<StringRef, StringRef> Split = Str.split(Separator);
184   assert((!Split.second.empty() || Split.first == Str) &&
185          "a trailing separator is not allowed");
186   return Split;
187 }
188
189 /// Get an unsinged integer, including error checks.
190 static unsigned getInt(StringRef R) {
191   unsigned Result;
192   bool error = R.getAsInteger(10, Result); (void)error;
193   assert(!error && "not a number, or does not fit in an unsigned int");
194   return Result;
195 }
196
197 /// Convert bits into bytes. Assert if not a byte width multiple.
198 static unsigned inBytes(unsigned Bits) {
199   assert(Bits % 8 == 0 && "number of bits must be a byte width multiple");
200   return Bits / 8;
201 }
202
203 void DataLayout::parseSpecifier(StringRef Desc) {
204
205   while (!Desc.empty()) {
206
207     // Split at '-'.
208     std::pair<StringRef, StringRef> Split = split(Desc, '-');
209     Desc = Split.second;
210
211     // Split at ':'.
212     Split = split(Split.first, ':');
213
214     // Aliases used below.
215     StringRef &Tok  = Split.first;  // Current token.
216     StringRef &Rest = Split.second; // The rest of the string.
217
218     char Specifier = Tok.front();
219     Tok = Tok.substr(1);
220
221     switch (Specifier) {
222     case 'E':
223       LittleEndian = false;
224       break;
225     case 'e':
226       LittleEndian = true;
227       break;
228     case 'p': {
229       // Address space.
230       unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
231       assert(AddrSpace < 1 << 24 &&
232              "Invalid address space, must be a 24bit integer");
233
234       // Size.
235       Split = split(Rest, ':');
236       unsigned PointerMemSize = inBytes(getInt(Tok));
237
238       // ABI alignment.
239       Split = split(Rest, ':');
240       unsigned PointerABIAlign = inBytes(getInt(Tok));
241
242       // Preferred alignment.
243       unsigned PointerPrefAlign = PointerABIAlign;
244       if (!Rest.empty()) {
245         Split = split(Rest, ':');
246         PointerPrefAlign = inBytes(getInt(Tok));
247       }
248
249       setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
250                           PointerMemSize);
251       break;
252     }
253     case 'i':
254     case 'v':
255     case 'f':
256     case 'a':
257     case 's': {
258       AlignTypeEnum AlignType;
259       switch (Specifier) {
260       default:
261       case 'i': AlignType = INTEGER_ALIGN; break;
262       case 'v': AlignType = VECTOR_ALIGN; break;
263       case 'f': AlignType = FLOAT_ALIGN; break;
264       case 'a': AlignType = AGGREGATE_ALIGN; break;
265       case 's': AlignType = STACK_ALIGN; break;
266       }
267
268       // Bit size.
269       unsigned Size = Tok.empty() ? 0 : getInt(Tok);
270
271       // ABI alignment.
272       Split = split(Rest, ':');
273       unsigned ABIAlign = inBytes(getInt(Tok));
274
275       // Preferred alignment.
276       unsigned PrefAlign = ABIAlign;
277       if (!Rest.empty()) {
278         Split = split(Rest, ':');
279         PrefAlign = inBytes(getInt(Tok));
280       }
281
282       setAlignment(AlignType, ABIAlign, PrefAlign, Size);
283
284       break;
285     }
286     case 'n':  // Native integer types.
287       for (;;) {
288         unsigned Width = getInt(Tok);
289         assert(Width != 0 && "width must be non-zero");
290         LegalIntWidths.push_back(Width);
291         if (Rest.empty())
292           break;
293         Split = split(Rest, ':');
294       }
295       break;
296     case 'S': { // Stack natural alignment.
297       StackNaturalAlign = inBytes(getInt(Tok));
298       break;
299     }
300     default:
301       llvm_unreachable("Unknown specifier in datalayout string");
302       break;
303     }
304   }
305 }
306
307 /// Default ctor.
308 ///
309 /// @note This has to exist, because this is a pass, but it should never be
310 /// used.
311 DataLayout::DataLayout() : ImmutablePass(ID) {
312   report_fatal_error("Bad DataLayout ctor used.  "
313                     "Tool did not specify a DataLayout to use?");
314 }
315
316 DataLayout::DataLayout(const Module *M)
317   : ImmutablePass(ID) {
318   init(M->getDataLayout());
319 }
320
321 void
322 DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
323                          unsigned pref_align, uint32_t bit_width) {
324   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
325   assert(pref_align < (1 << 16) && "Alignment doesn't fit in bitfield");
326   assert(bit_width < (1 << 24) && "Bit width doesn't fit in bitfield");
327   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
328     if (Alignments[i].AlignType == (unsigned)align_type &&
329         Alignments[i].TypeBitWidth == bit_width) {
330       // Update the abi, preferred alignments.
331       Alignments[i].ABIAlign = abi_align;
332       Alignments[i].PrefAlign = pref_align;
333       return;
334     }
335   }
336
337   Alignments.push_back(LayoutAlignElem::get(align_type, abi_align,
338                                             pref_align, bit_width));
339 }
340
341 void
342 DataLayout::setPointerAlignment(uint32_t addr_space, unsigned abi_align,
343                          unsigned pref_align, uint32_t bit_width) {
344   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
345   DenseMap<unsigned,PointerAlignElem>::iterator val = Pointers.find(addr_space);
346   if (val == Pointers.end()) {
347     Pointers[addr_space] = PointerAlignElem::get(addr_space,
348           abi_align, pref_align, bit_width);
349   } else {
350     val->second.ABIAlign = abi_align;
351     val->second.PrefAlign = pref_align;
352     val->second.TypeBitWidth = bit_width;
353   }
354 }
355
356 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
357 /// preferred if ABIInfo = false) the layout wants for the specified datatype.
358 unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
359                                       uint32_t BitWidth, bool ABIInfo,
360                                       Type *Ty) const {
361   // Check to see if we have an exact match and remember the best match we see.
362   int BestMatchIdx = -1;
363   int LargestInt = -1;
364   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
365     if (Alignments[i].AlignType == (unsigned)AlignType &&
366         Alignments[i].TypeBitWidth == BitWidth)
367       return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
368
369     // The best match so far depends on what we're looking for.
370      if (AlignType == INTEGER_ALIGN &&
371          Alignments[i].AlignType == INTEGER_ALIGN) {
372       // The "best match" for integers is the smallest size that is larger than
373       // the BitWidth requested.
374       if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
375            Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
376         BestMatchIdx = i;
377       // However, if there isn't one that's larger, then we must use the
378       // largest one we have (see below)
379       if (LargestInt == -1 ||
380           Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
381         LargestInt = i;
382     }
383   }
384
385   // Okay, we didn't find an exact solution.  Fall back here depending on what
386   // is being looked for.
387   if (BestMatchIdx == -1) {
388     // If we didn't find an integer alignment, fall back on most conservative.
389     if (AlignType == INTEGER_ALIGN) {
390       BestMatchIdx = LargestInt;
391     } else {
392       assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
393
394       // By default, use natural alignment for vector types. This is consistent
395       // with what clang and llvm-gcc do.
396       unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
397       Align *= cast<VectorType>(Ty)->getNumElements();
398       // If the alignment is not a power of 2, round up to the next power of 2.
399       // This happens for non-power-of-2 length vectors.
400       if (Align & (Align-1))
401         Align = NextPowerOf2(Align);
402       return Align;
403     }
404   }
405
406   // Since we got a "best match" index, just return it.
407   return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
408                  : Alignments[BestMatchIdx].PrefAlign;
409 }
410
411 namespace {
412
413 class StructLayoutMap {
414   typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
415   LayoutInfoTy LayoutInfo;
416
417 public:
418   virtual ~StructLayoutMap() {
419     // Remove any layouts.
420     for (LayoutInfoTy::iterator I = LayoutInfo.begin(), E = LayoutInfo.end();
421          I != E; ++I) {
422       StructLayout *Value = I->second;
423       Value->~StructLayout();
424       free(Value);
425     }
426   }
427
428   StructLayout *&operator[](StructType *STy) {
429     return LayoutInfo[STy];
430   }
431
432   // for debugging...
433   virtual void dump() const {}
434 };
435
436 } // end anonymous namespace
437
438 DataLayout::~DataLayout() {
439   delete static_cast<StructLayoutMap*>(LayoutMap);
440 }
441
442 const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
443   if (!LayoutMap)
444     LayoutMap = new StructLayoutMap();
445
446   StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
447   StructLayout *&SL = (*STM)[Ty];
448   if (SL) return SL;
449
450   // Otherwise, create the struct layout.  Because it is variable length, we
451   // malloc it, then use placement new.
452   int NumElts = Ty->getNumElements();
453   StructLayout *L =
454     (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
455
456   // Set SL before calling StructLayout's ctor.  The ctor could cause other
457   // entries to be added to TheMap, invalidating our reference.
458   SL = L;
459
460   new (L) StructLayout(Ty, *this);
461
462   return L;
463 }
464
465 std::string DataLayout::getStringRepresentation() const {
466   std::string Result;
467   raw_string_ostream OS(Result);
468
469   OS << (LittleEndian ? "e" : "E");
470   SmallVector<unsigned, 8> addrSpaces;
471   // Lets get all of the known address spaces and sort them
472   // into increasing order so that we can emit the string
473   // in a cleaner format.
474   for (DenseMap<unsigned, PointerAlignElem>::const_iterator
475       pib = Pointers.begin(), pie = Pointers.end();
476       pib != pie; ++pib) {
477     addrSpaces.push_back(pib->first);
478   }
479   std::sort(addrSpaces.begin(), addrSpaces.end());
480   for (SmallVector<unsigned, 8>::iterator asb = addrSpaces.begin(),
481       ase = addrSpaces.end(); asb != ase; ++asb) {
482     const PointerAlignElem &PI = Pointers.find(*asb)->second;
483     OS << "-p";
484     if (PI.AddressSpace) {
485       OS << PI.AddressSpace;
486     }
487      OS << ":" << PI.TypeBitWidth*8 << ':' << PI.ABIAlign*8
488         << ':' << PI.PrefAlign*8;
489   }
490   OS << "-S" << StackNaturalAlign*8;
491
492   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
493     const LayoutAlignElem &AI = Alignments[i];
494     OS << '-' << (char)AI.AlignType << AI.TypeBitWidth << ':'
495        << AI.ABIAlign*8 << ':' << AI.PrefAlign*8;
496   }
497
498   if (!LegalIntWidths.empty()) {
499     OS << "-n" << (unsigned)LegalIntWidths[0];
500
501     for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
502       OS << ':' << (unsigned)LegalIntWidths[i];
503   }
504   return OS.str();
505 }
506
507
508 uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
509   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
510   switch (Ty->getTypeID()) {
511   case Type::LabelTyID:
512     return getPointerSizeInBits(0);
513   case Type::PointerTyID: {
514     unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
515     return getPointerSizeInBits(AS);
516     }
517   case Type::ArrayTyID: {
518     ArrayType *ATy = cast<ArrayType>(Ty);
519     return getTypeAllocSizeInBits(ATy->getElementType())*ATy->getNumElements();
520   }
521   case Type::StructTyID:
522     // Get the layout annotation... which is lazily created on demand.
523     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
524   case Type::IntegerTyID:
525     return cast<IntegerType>(Ty)->getBitWidth();
526   case Type::HalfTyID:
527     return 16;
528   case Type::FloatTyID:
529     return 32;
530   case Type::DoubleTyID:
531   case Type::X86_MMXTyID:
532     return 64;
533   case Type::PPC_FP128TyID:
534   case Type::FP128TyID:
535     return 128;
536   // In memory objects this is always aligned to a higher boundary, but
537   // only 80 bits contain information.
538   case Type::X86_FP80TyID:
539     return 80;
540   case Type::VectorTyID: {
541     VectorType *VTy = cast<VectorType>(Ty);
542     return VTy->getNumElements()*getTypeSizeInBits(VTy->getElementType());
543   }
544   default:
545     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
546   }
547 }
548
549 /*!
550   \param abi_or_pref Flag that determines which alignment is returned. true
551   returns the ABI alignment, false returns the preferred alignment.
552   \param Ty The underlying type for which alignment is determined.
553
554   Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
555   == false) for the requested type \a Ty.
556  */
557 unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
558   int AlignType = -1;
559
560   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
561   switch (Ty->getTypeID()) {
562   // Early escape for the non-numeric types.
563   case Type::LabelTyID:
564     return (abi_or_pref
565             ? getPointerABIAlignment(0)
566             : getPointerPrefAlignment(0));
567   case Type::PointerTyID: {
568     unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
569     return (abi_or_pref
570             ? getPointerABIAlignment(AS)
571             : getPointerPrefAlignment(AS));
572     }
573   case Type::ArrayTyID:
574     return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
575
576   case Type::StructTyID: {
577     // Packed structure types always have an ABI alignment of one.
578     if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
579       return 1;
580
581     // Get the layout annotation... which is lazily created on demand.
582     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
583     unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
584     return std::max(Align, Layout->getAlignment());
585   }
586   case Type::IntegerTyID:
587     AlignType = INTEGER_ALIGN;
588     break;
589   case Type::HalfTyID:
590   case Type::FloatTyID:
591   case Type::DoubleTyID:
592   // PPC_FP128TyID and FP128TyID have different data contents, but the
593   // same size and alignment, so they look the same here.
594   case Type::PPC_FP128TyID:
595   case Type::FP128TyID:
596   case Type::X86_FP80TyID:
597     AlignType = FLOAT_ALIGN;
598     break;
599   case Type::X86_MMXTyID:
600   case Type::VectorTyID:
601     AlignType = VECTOR_ALIGN;
602     break;
603   default:
604     llvm_unreachable("Bad type for getAlignment!!!");
605   }
606
607   return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
608                           abi_or_pref, Ty);
609 }
610
611 unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
612   return getAlignment(Ty, true);
613 }
614
615 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
616 /// an integer type of the specified bitwidth.
617 unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
618   return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, 0);
619 }
620
621
622 unsigned DataLayout::getCallFrameTypeAlignment(Type *Ty) const {
623   for (unsigned i = 0, e = Alignments.size(); i != e; ++i)
624     if (Alignments[i].AlignType == STACK_ALIGN)
625       return Alignments[i].ABIAlign;
626
627   return getABITypeAlignment(Ty);
628 }
629
630 unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
631   return getAlignment(Ty, false);
632 }
633
634 unsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
635   unsigned Align = getPrefTypeAlignment(Ty);
636   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
637   return Log2_32(Align);
638 }
639
640 /// getIntPtrType - Return an integer type with size at least as big as that
641 /// of a pointer in the given address space.
642 IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
643                                        unsigned AddressSpace) const {
644   return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
645 }
646
647 /// getIntPtrType - Return an integer (vector of integer) type with size at
648 /// least as big as that of a pointer of the given pointer (vector of pointer)
649 /// type.
650 Type *DataLayout::getIntPtrType(Type *Ty) const {
651   assert(Ty->isPtrOrPtrVectorTy() &&
652          "Expected a pointer or pointer vector type.");
653   unsigned NumBits = getTypeSizeInBits(Ty->getScalarType());
654   IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
655   if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
656     return VectorType::get(IntTy, VecTy->getNumElements());
657   return IntTy;
658 }
659
660 uint64_t DataLayout::getIndexedOffset(Type *ptrTy,
661                                       ArrayRef<Value *> Indices) const {
662   Type *Ty = ptrTy;
663   assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
664   uint64_t Result = 0;
665
666   generic_gep_type_iterator<Value* const*>
667     TI = gep_type_begin(ptrTy, Indices);
668   for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
669        ++CurIDX, ++TI) {
670     if (StructType *STy = dyn_cast<StructType>(*TI)) {
671       assert(Indices[CurIDX]->getType() ==
672              Type::getInt32Ty(ptrTy->getContext()) &&
673              "Illegal struct idx");
674       unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
675
676       // Get structure layout information...
677       const StructLayout *Layout = getStructLayout(STy);
678
679       // Add in the offset, as calculated by the structure layout info...
680       Result += Layout->getElementOffset(FieldNo);
681
682       // Update Ty to refer to current element
683       Ty = STy->getElementType(FieldNo);
684     } else {
685       // Update Ty to refer to current element
686       Ty = cast<SequentialType>(Ty)->getElementType();
687
688       // Get the array index and the size of each array element.
689       if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
690         Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
691     }
692   }
693
694   return Result;
695 }
696
697 /// getPreferredAlignment - Return the preferred alignment of the specified
698 /// global.  This includes an explicitly requested alignment (if the global
699 /// has one).
700 unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
701   Type *ElemType = GV->getType()->getElementType();
702   unsigned Alignment = getPrefTypeAlignment(ElemType);
703   unsigned GVAlignment = GV->getAlignment();
704   if (GVAlignment >= Alignment) {
705     Alignment = GVAlignment;
706   } else if (GVAlignment != 0) {
707     Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
708   }
709
710   if (GV->hasInitializer() && GVAlignment == 0) {
711     if (Alignment < 16) {
712       // If the global is not external, see if it is large.  If so, give it a
713       // larger alignment.
714       if (getTypeSizeInBits(ElemType) > 128)
715         Alignment = 16;    // 16-byte alignment.
716     }
717   }
718   return Alignment;
719 }
720
721 /// getPreferredAlignmentLog - Return the preferred alignment of the
722 /// specified global, returned in log form.  This includes an explicitly
723 /// requested alignment (if the global has one).
724 unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
725   return Log2_32(getPreferredAlignment(GV));
726 }