Add basic generic CodeGen support for half.
[oota-llvm.git] / lib / Target / TargetData.cpp
1 //===-- TargetData.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 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/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/GetElementPtrTypeIterator.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include <algorithm>
31 #include <cstdlib>
32 using namespace llvm;
33
34 // Handle the Pass registration stuff necessary to use TargetData's.
35
36 // Register the default SparcV9 implementation...
37 INITIALIZE_PASS(TargetData, "targetdata", "Target Data Layout", false, true)
38 char TargetData::ID = 0;
39
40 //===----------------------------------------------------------------------===//
41 // Support for StructLayout
42 //===----------------------------------------------------------------------===//
43
44 StructLayout::StructLayout(StructType *ST, const TargetData &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 = TargetData::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 = TargetData::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 // TargetAlignElem, TargetAlign support
98 //===----------------------------------------------------------------------===//
99
100 TargetAlignElem
101 TargetAlignElem::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   TargetAlignElem 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 TargetAlignElem::operator==(const TargetAlignElem &rhs) const {
114   return (AlignType == rhs.AlignType
115           && ABIAlign == rhs.ABIAlign
116           && PrefAlign == rhs.PrefAlign
117           && TypeBitWidth == rhs.TypeBitWidth);
118 }
119
120 const TargetAlignElem TargetData::InvalidAlignmentElem =
121                 TargetAlignElem::get((AlignTypeEnum) -1, 0, 0, 0);
122
123 //===----------------------------------------------------------------------===//
124 //                       TargetData Class Implementation
125 //===----------------------------------------------------------------------===//
126
127 /// getInt - Get an integer ignoring errors.
128 static int getInt(StringRef R) {
129   int Result = 0;
130   R.getAsInteger(10, Result);
131   return Result;
132 }
133
134 void TargetData::init() {
135   initializeTargetDataPass(*PassRegistry::getPassRegistry());
136
137   LayoutMap = 0;
138   LittleEndian = false;
139   PointerMemSize = 8;
140   PointerABIAlign = 8;
141   PointerPrefAlign = PointerABIAlign;
142   StackNaturalAlign = 0;
143
144   // Default alignments
145   setAlignment(INTEGER_ALIGN,   1,  1, 1);   // i1
146   setAlignment(INTEGER_ALIGN,   1,  1, 8);   // i8
147   setAlignment(INTEGER_ALIGN,   2,  2, 16);  // i16
148   setAlignment(INTEGER_ALIGN,   4,  4, 32);  // i32
149   setAlignment(INTEGER_ALIGN,   4,  8, 64);  // i64
150   setAlignment(FLOAT_ALIGN,     2,  2, 16);  // half
151   setAlignment(FLOAT_ALIGN,     4,  4, 32);  // float
152   setAlignment(FLOAT_ALIGN,     8,  8, 64);  // double
153   setAlignment(VECTOR_ALIGN,    8,  8, 64);  // v2i32, v1i64, ...
154   setAlignment(VECTOR_ALIGN,   16, 16, 128); // v16i8, v8i16, v4i32, ...
155   setAlignment(AGGREGATE_ALIGN, 0,  8,  0);  // struct
156 }
157
158 std::string TargetData::parseSpecifier(StringRef Desc, TargetData *td) {
159
160   if (td)
161     td->init();
162
163   while (!Desc.empty()) {
164     std::pair<StringRef, StringRef> Split = Desc.split('-');
165     StringRef Token = Split.first;
166     Desc = Split.second;
167
168     if (Token.empty())
169       continue;
170
171     Split = Token.split(':');
172     StringRef Specifier = Split.first;
173     Token = Split.second;
174
175     assert(!Specifier.empty() && "Can't be empty here");
176
177     switch (Specifier[0]) {
178     case 'E':
179       if (td)
180         td->LittleEndian = false;
181       break;
182     case 'e':
183       if (td)
184         td->LittleEndian = true;
185       break;
186     case 'p': {
187       // Pointer size.
188       Split = Token.split(':');
189       int PointerMemSizeBits = getInt(Split.first);
190       if (PointerMemSizeBits < 0 || PointerMemSizeBits % 8 != 0)
191         return "invalid pointer size, must be a positive 8-bit multiple";
192       if (td)
193         td->PointerMemSize = PointerMemSizeBits / 8;
194
195       // Pointer ABI alignment.
196       Split = Split.second.split(':');
197       int PointerABIAlignBits = getInt(Split.first);
198       if (PointerABIAlignBits < 0 || PointerABIAlignBits % 8 != 0) {
199         return "invalid pointer ABI alignment, "
200                "must be a positive 8-bit multiple";
201       }
202       if (td)
203         td->PointerABIAlign = PointerABIAlignBits / 8;
204
205       // Pointer preferred alignment.
206       Split = Split.second.split(':');
207       int PointerPrefAlignBits = getInt(Split.first);
208       if (PointerPrefAlignBits < 0 || PointerPrefAlignBits % 8 != 0) {
209         return "invalid pointer preferred alignment, "
210                "must be a positive 8-bit multiple";
211       }
212       if (td) {
213         td->PointerPrefAlign = PointerPrefAlignBits / 8;
214         if (td->PointerPrefAlign == 0)
215           td->PointerPrefAlign = td->PointerABIAlign;
216       }
217       break;
218     }
219     case 'i':
220     case 'v':
221     case 'f':
222     case 'a':
223     case 's': {
224       AlignTypeEnum AlignType;
225       char field = Specifier[0];
226       switch (field) {
227       default:
228       case 'i': AlignType = INTEGER_ALIGN; break;
229       case 'v': AlignType = VECTOR_ALIGN; break;
230       case 'f': AlignType = FLOAT_ALIGN; break;
231       case 'a': AlignType = AGGREGATE_ALIGN; break;
232       case 's': AlignType = STACK_ALIGN; break;
233       }
234       int Size = getInt(Specifier.substr(1));
235       if (Size < 0) {
236         return std::string("invalid ") + field + "-size field, "
237                "must be positive";
238       }
239
240       Split = Token.split(':');
241       int ABIAlignBits = getInt(Split.first);
242       if (ABIAlignBits < 0 || ABIAlignBits % 8 != 0) {
243         return std::string("invalid ") + field +"-abi-alignment field, "
244                "must be a positive 8-bit multiple";
245       }
246       unsigned ABIAlign = ABIAlignBits / 8;
247
248       Split = Split.second.split(':');
249
250       int PrefAlignBits = getInt(Split.first);
251       if (PrefAlignBits < 0 || PrefAlignBits % 8 != 0) {
252         return std::string("invalid ") + field +"-preferred-alignment field, "
253                "must be a positive 8-bit multiple";
254       }
255       unsigned PrefAlign = PrefAlignBits / 8;
256       if (PrefAlign == 0)
257         PrefAlign = ABIAlign;
258       
259       if (td)
260         td->setAlignment(AlignType, ABIAlign, PrefAlign, Size);
261       break;
262     }
263     case 'n':  // Native integer types.
264       Specifier = Specifier.substr(1);
265       do {
266         int Width = getInt(Specifier);
267         if (Width <= 0) {
268           return std::string("invalid native integer size \'") + Specifier.str() +
269                  "\', must be a positive integer.";
270         }
271         if (td && Width != 0)
272           td->LegalIntWidths.push_back(Width);
273         Split = Token.split(':');
274         Specifier = Split.first;
275         Token = Split.second;
276       } while (!Specifier.empty() || !Token.empty());
277       break;
278     case 'S': { // Stack natural alignment.
279       int StackNaturalAlignBits = getInt(Specifier.substr(1));
280       if (StackNaturalAlignBits < 0 || StackNaturalAlignBits % 8 != 0) {
281         return "invalid natural stack alignment (S-field), "
282                "must be a positive 8-bit multiple";
283       }
284       if (td)
285         td->StackNaturalAlign = StackNaturalAlignBits / 8;
286       break;
287     }
288     default:
289       break;
290     }
291   }
292
293   return "";
294 }
295
296 /// Default ctor.
297 ///
298 /// @note This has to exist, because this is a pass, but it should never be
299 /// used.
300 TargetData::TargetData() : ImmutablePass(ID) {
301   report_fatal_error("Bad TargetData ctor used.  "
302                     "Tool did not specify a TargetData to use?");
303 }
304
305 TargetData::TargetData(const Module *M)
306   : ImmutablePass(ID) {
307   std::string errMsg = parseSpecifier(M->getDataLayout(), this);
308   assert(errMsg == "" && "Module M has malformed target data layout string.");
309   (void)errMsg;
310 }
311
312 void
313 TargetData::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
314                          unsigned pref_align, uint32_t bit_width) {
315   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
316   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
317     if (Alignments[i].AlignType == align_type &&
318         Alignments[i].TypeBitWidth == bit_width) {
319       // Update the abi, preferred alignments.
320       Alignments[i].ABIAlign = abi_align;
321       Alignments[i].PrefAlign = pref_align;
322       return;
323     }
324   }
325
326   Alignments.push_back(TargetAlignElem::get(align_type, abi_align,
327                                             pref_align, bit_width));
328 }
329
330 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
331 /// preferred if ABIInfo = false) the target wants for the specified datatype.
332 unsigned TargetData::getAlignmentInfo(AlignTypeEnum AlignType,
333                                       uint32_t BitWidth, bool ABIInfo,
334                                       Type *Ty) const {
335   // Check to see if we have an exact match and remember the best match we see.
336   int BestMatchIdx = -1;
337   int LargestInt = -1;
338   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
339     if (Alignments[i].AlignType == AlignType &&
340         Alignments[i].TypeBitWidth == BitWidth)
341       return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
342
343     // The best match so far depends on what we're looking for.
344      if (AlignType == INTEGER_ALIGN &&
345          Alignments[i].AlignType == INTEGER_ALIGN) {
346       // The "best match" for integers is the smallest size that is larger than
347       // the BitWidth requested.
348       if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
349            Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
350         BestMatchIdx = i;
351       // However, if there isn't one that's larger, then we must use the
352       // largest one we have (see below)
353       if (LargestInt == -1 ||
354           Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
355         LargestInt = i;
356     }
357   }
358
359   // Okay, we didn't find an exact solution.  Fall back here depending on what
360   // is being looked for.
361   if (BestMatchIdx == -1) {
362     // If we didn't find an integer alignment, fall back on most conservative.
363     if (AlignType == INTEGER_ALIGN) {
364       BestMatchIdx = LargestInt;
365     } else {
366       assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
367
368       // By default, use natural alignment for vector types. This is consistent
369       // with what clang and llvm-gcc do.
370       unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
371       Align *= cast<VectorType>(Ty)->getNumElements();
372       // If the alignment is not a power of 2, round up to the next power of 2.
373       // This happens for non-power-of-2 length vectors.
374       if (Align & (Align-1))
375         Align = llvm::NextPowerOf2(Align);
376       return Align;
377     }
378   }
379
380   // Since we got a "best match" index, just return it.
381   return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
382                  : Alignments[BestMatchIdx].PrefAlign;
383 }
384
385 namespace {
386
387 class StructLayoutMap {
388   typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
389   LayoutInfoTy LayoutInfo;
390
391 public:
392   virtual ~StructLayoutMap() {
393     // Remove any layouts.
394     for (LayoutInfoTy::iterator I = LayoutInfo.begin(), E = LayoutInfo.end();
395          I != E; ++I) {
396       StructLayout *Value = I->second;
397       Value->~StructLayout();
398       free(Value);
399     }
400   }
401
402   StructLayout *&operator[](StructType *STy) {
403     return LayoutInfo[STy];
404   }
405
406   // for debugging...
407   virtual void dump() const {}
408 };
409
410 } // end anonymous namespace
411
412 TargetData::~TargetData() {
413   delete static_cast<StructLayoutMap*>(LayoutMap);
414 }
415
416 const StructLayout *TargetData::getStructLayout(StructType *Ty) const {
417   if (!LayoutMap)
418     LayoutMap = new StructLayoutMap();
419
420   StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
421   StructLayout *&SL = (*STM)[Ty];
422   if (SL) return SL;
423
424   // Otherwise, create the struct layout.  Because it is variable length, we
425   // malloc it, then use placement new.
426   int NumElts = Ty->getNumElements();
427   StructLayout *L =
428     (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
429
430   // Set SL before calling StructLayout's ctor.  The ctor could cause other
431   // entries to be added to TheMap, invalidating our reference.
432   SL = L;
433
434   new (L) StructLayout(Ty, *this);
435
436   return L;
437 }
438
439 std::string TargetData::getStringRepresentation() const {
440   std::string Result;
441   raw_string_ostream OS(Result);
442
443   OS << (LittleEndian ? "e" : "E")
444      << "-p:" << PointerMemSize*8 << ':' << PointerABIAlign*8
445      << ':' << PointerPrefAlign*8
446      << "-S" << StackNaturalAlign*8;
447
448   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
449     const TargetAlignElem &AI = Alignments[i];
450     OS << '-' << (char)AI.AlignType << AI.TypeBitWidth << ':'
451        << AI.ABIAlign*8 << ':' << AI.PrefAlign*8;
452   }
453
454   if (!LegalIntWidths.empty()) {
455     OS << "-n" << (unsigned)LegalIntWidths[0];
456
457     for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
458       OS << ':' << (unsigned)LegalIntWidths[i];
459   }
460   return OS.str();
461 }
462
463
464 uint64_t TargetData::getTypeSizeInBits(Type *Ty) const {
465   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
466   switch (Ty->getTypeID()) {
467   case Type::LabelTyID:
468   case Type::PointerTyID:
469     return getPointerSizeInBits();
470   case Type::ArrayTyID: {
471     ArrayType *ATy = cast<ArrayType>(Ty);
472     return getTypeAllocSizeInBits(ATy->getElementType())*ATy->getNumElements();
473   }
474   case Type::StructTyID:
475     // Get the layout annotation... which is lazily created on demand.
476     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
477   case Type::IntegerTyID:
478     return cast<IntegerType>(Ty)->getBitWidth();
479   case Type::VoidTyID:
480     return 8;
481   case Type::HalfTyID:
482     return 16;
483   case Type::FloatTyID:
484     return 32;
485   case Type::DoubleTyID:
486   case Type::X86_MMXTyID:
487     return 64;
488   case Type::PPC_FP128TyID:
489   case Type::FP128TyID:
490     return 128;
491   // In memory objects this is always aligned to a higher boundary, but
492   // only 80 bits contain information.
493   case Type::X86_FP80TyID:
494     return 80;
495   case Type::VectorTyID:
496     return cast<VectorType>(Ty)->getBitWidth();
497   default:
498     llvm_unreachable("TargetData::getTypeSizeInBits(): Unsupported type");
499     break;
500   }
501   return 0;
502 }
503
504 /*!
505   \param abi_or_pref Flag that determines which alignment is returned. true
506   returns the ABI alignment, false returns the preferred alignment.
507   \param Ty The underlying type for which alignment is determined.
508
509   Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
510   == false) for the requested type \a Ty.
511  */
512 unsigned TargetData::getAlignment(Type *Ty, bool abi_or_pref) const {
513   int AlignType = -1;
514
515   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
516   switch (Ty->getTypeID()) {
517   // Early escape for the non-numeric types.
518   case Type::LabelTyID:
519   case Type::PointerTyID:
520     return (abi_or_pref
521             ? getPointerABIAlignment()
522             : getPointerPrefAlignment());
523   case Type::ArrayTyID:
524     return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
525
526   case Type::StructTyID: {
527     // Packed structure types always have an ABI alignment of one.
528     if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
529       return 1;
530
531     // Get the layout annotation... which is lazily created on demand.
532     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
533     unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
534     return std::max(Align, Layout->getAlignment());
535   }
536   case Type::IntegerTyID:
537   case Type::VoidTyID:
538     AlignType = INTEGER_ALIGN;
539     break;
540   case Type::HalfTyID:
541   case Type::FloatTyID:
542   case Type::DoubleTyID:
543   // PPC_FP128TyID and FP128TyID have different data contents, but the
544   // same size and alignment, so they look the same here.
545   case Type::PPC_FP128TyID:
546   case Type::FP128TyID:
547   case Type::X86_FP80TyID:
548     AlignType = FLOAT_ALIGN;
549     break;
550   case Type::X86_MMXTyID:
551   case Type::VectorTyID:
552     AlignType = VECTOR_ALIGN;
553     break;
554   default:
555     llvm_unreachable("Bad type for getAlignment!!!");
556     break;
557   }
558
559   return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
560                           abi_or_pref, Ty);
561 }
562
563 unsigned TargetData::getABITypeAlignment(Type *Ty) const {
564   return getAlignment(Ty, true);
565 }
566
567 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
568 /// an integer type of the specified bitwidth.
569 unsigned TargetData::getABIIntegerTypeAlignment(unsigned BitWidth) const {
570   return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, 0);
571 }
572
573
574 unsigned TargetData::getCallFrameTypeAlignment(Type *Ty) const {
575   for (unsigned i = 0, e = Alignments.size(); i != e; ++i)
576     if (Alignments[i].AlignType == STACK_ALIGN)
577       return Alignments[i].ABIAlign;
578
579   return getABITypeAlignment(Ty);
580 }
581
582 unsigned TargetData::getPrefTypeAlignment(Type *Ty) const {
583   return getAlignment(Ty, false);
584 }
585
586 unsigned TargetData::getPreferredTypeAlignmentShift(Type *Ty) const {
587   unsigned Align = getPrefTypeAlignment(Ty);
588   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
589   return Log2_32(Align);
590 }
591
592 /// getIntPtrType - Return an unsigned integer type that is the same size or
593 /// greater to the host pointer size.
594 IntegerType *TargetData::getIntPtrType(LLVMContext &C) const {
595   return IntegerType::get(C, getPointerSizeInBits());
596 }
597
598
599 uint64_t TargetData::getIndexedOffset(Type *ptrTy,
600                                       ArrayRef<Value *> Indices) const {
601   Type *Ty = ptrTy;
602   assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
603   uint64_t Result = 0;
604
605   generic_gep_type_iterator<Value* const*>
606     TI = gep_type_begin(ptrTy, Indices);
607   for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
608        ++CurIDX, ++TI) {
609     if (StructType *STy = dyn_cast<StructType>(*TI)) {
610       assert(Indices[CurIDX]->getType() ==
611              Type::getInt32Ty(ptrTy->getContext()) &&
612              "Illegal struct idx");
613       unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
614
615       // Get structure layout information...
616       const StructLayout *Layout = getStructLayout(STy);
617
618       // Add in the offset, as calculated by the structure layout info...
619       Result += Layout->getElementOffset(FieldNo);
620
621       // Update Ty to refer to current element
622       Ty = STy->getElementType(FieldNo);
623     } else {
624       // Update Ty to refer to current element
625       Ty = cast<SequentialType>(Ty)->getElementType();
626
627       // Get the array index and the size of each array element.
628       if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
629         Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
630     }
631   }
632
633   return Result;
634 }
635
636 /// getPreferredAlignment - Return the preferred alignment of the specified
637 /// global.  This includes an explicitly requested alignment (if the global
638 /// has one).
639 unsigned TargetData::getPreferredAlignment(const GlobalVariable *GV) const {
640   Type *ElemType = GV->getType()->getElementType();
641   unsigned Alignment = getPrefTypeAlignment(ElemType);
642   unsigned GVAlignment = GV->getAlignment();
643   if (GVAlignment >= Alignment) {
644     Alignment = GVAlignment;
645   } else if (GVAlignment != 0) {
646     Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
647   }
648
649   if (GV->hasInitializer() && GVAlignment == 0) {
650     if (Alignment < 16) {
651       // If the global is not external, see if it is large.  If so, give it a
652       // larger alignment.
653       if (getTypeSizeInBits(ElemType) > 128)
654         Alignment = 16;    // 16-byte alignment.
655     }
656   }
657   return Alignment;
658 }
659
660 /// getPreferredAlignmentLog - Return the preferred alignment of the
661 /// specified global, returned in log form.  This includes an explicitly
662 /// requested alignment (if the global has one).
663 unsigned TargetData::getPreferredAlignmentLog(const GlobalVariable *GV) const {
664   return Log2_32(getPreferredAlignment(GV));
665 }