1249259Sdim//===-- DataLayout.cpp - Data size & alignment routines --------------------==//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file defines layout properties related to datatype size/offset/alignment
11249259Sdim// information.
12249259Sdim//
13249259Sdim// This structure should be created once, filled in if the defaults are not
14249259Sdim// correct and then passed around by const&.  None of the members functions
15249259Sdim// require modification to the object.
16249259Sdim//
17249259Sdim//===----------------------------------------------------------------------===//
18249259Sdim
19249259Sdim#include "llvm/IR/DataLayout.h"
20249259Sdim#include "llvm/ADT/DenseMap.h"
21249259Sdim#include "llvm/IR/Constants.h"
22249259Sdim#include "llvm/IR/DerivedTypes.h"
23249259Sdim#include "llvm/IR/Module.h"
24249259Sdim#include "llvm/Support/ErrorHandling.h"
25249259Sdim#include "llvm/Support/GetElementPtrTypeIterator.h"
26249259Sdim#include "llvm/Support/ManagedStatic.h"
27249259Sdim#include "llvm/Support/MathExtras.h"
28249259Sdim#include "llvm/Support/Mutex.h"
29249259Sdim#include "llvm/Support/raw_ostream.h"
30249259Sdim#include <algorithm>
31249259Sdim#include <cstdlib>
32249259Sdimusing namespace llvm;
33249259Sdim
34249259Sdim// Handle the Pass registration stuff necessary to use DataLayout's.
35249259Sdim
36249259Sdim// Register the default SparcV9 implementation...
37249259SdimINITIALIZE_PASS(DataLayout, "datalayout", "Data Layout", false, true)
38249259Sdimchar DataLayout::ID = 0;
39249259Sdim
40249259Sdim//===----------------------------------------------------------------------===//
41249259Sdim// Support for StructLayout
42249259Sdim//===----------------------------------------------------------------------===//
43249259Sdim
44252723SdimStructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
45249259Sdim  assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
46249259Sdim  StructAlignment = 0;
47249259Sdim  StructSize = 0;
48249259Sdim  NumElements = ST->getNumElements();
49249259Sdim
50249259Sdim  // Loop over each of the elements, placing them in memory.
51249259Sdim  for (unsigned i = 0, e = NumElements; i != e; ++i) {
52249259Sdim    Type *Ty = ST->getElementType(i);
53252723Sdim    unsigned TyAlign = ST->isPacked() ? 1 : DL.getABITypeAlignment(Ty);
54249259Sdim
55249259Sdim    // Add padding if necessary to align the data element properly.
56249259Sdim    if ((StructSize & (TyAlign-1)) != 0)
57249259Sdim      StructSize = DataLayout::RoundUpAlignment(StructSize, TyAlign);
58249259Sdim
59249259Sdim    // Keep track of maximum alignment constraint.
60249259Sdim    StructAlignment = std::max(TyAlign, StructAlignment);
61249259Sdim
62249259Sdim    MemberOffsets[i] = StructSize;
63252723Sdim    StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
64249259Sdim  }
65249259Sdim
66249259Sdim  // Empty structures have alignment of 1 byte.
67249259Sdim  if (StructAlignment == 0) StructAlignment = 1;
68249259Sdim
69249259Sdim  // Add padding to the end of the struct so that it could be put in an array
70249259Sdim  // and all array elements would be aligned correctly.
71249259Sdim  if ((StructSize & (StructAlignment-1)) != 0)
72249259Sdim    StructSize = DataLayout::RoundUpAlignment(StructSize, StructAlignment);
73249259Sdim}
74249259Sdim
75249259Sdim
76249259Sdim/// getElementContainingOffset - Given a valid offset into the structure,
77249259Sdim/// return the structure index that contains it.
78249259Sdimunsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
79249259Sdim  const uint64_t *SI =
80249259Sdim    std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
81249259Sdim  assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
82249259Sdim  --SI;
83249259Sdim  assert(*SI <= Offset && "upper_bound didn't work");
84249259Sdim  assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
85249259Sdim         (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
86249259Sdim         "Upper bound didn't work!");
87249259Sdim
88249259Sdim  // Multiple fields can have the same offset if any of them are zero sized.
89249259Sdim  // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
90249259Sdim  // at the i32 element, because it is the last element at that offset.  This is
91249259Sdim  // the right one to return, because anything after it will have a higher
92249259Sdim  // offset, implying that this element is non-empty.
93249259Sdim  return SI-&MemberOffsets[0];
94249259Sdim}
95249259Sdim
96249259Sdim//===----------------------------------------------------------------------===//
97249259Sdim// LayoutAlignElem, LayoutAlign support
98249259Sdim//===----------------------------------------------------------------------===//
99249259Sdim
100249259SdimLayoutAlignElem
101249259SdimLayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
102249259Sdim                     unsigned pref_align, uint32_t bit_width) {
103249259Sdim  assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
104249259Sdim  LayoutAlignElem retval;
105249259Sdim  retval.AlignType = align_type;
106249259Sdim  retval.ABIAlign = abi_align;
107249259Sdim  retval.PrefAlign = pref_align;
108249259Sdim  retval.TypeBitWidth = bit_width;
109249259Sdim  return retval;
110249259Sdim}
111249259Sdim
112249259Sdimbool
113249259SdimLayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
114249259Sdim  return (AlignType == rhs.AlignType
115249259Sdim          && ABIAlign == rhs.ABIAlign
116249259Sdim          && PrefAlign == rhs.PrefAlign
117249259Sdim          && TypeBitWidth == rhs.TypeBitWidth);
118249259Sdim}
119249259Sdim
120249259Sdimconst LayoutAlignElem
121249259SdimDataLayout::InvalidAlignmentElem = LayoutAlignElem::get(INVALID_ALIGN, 0, 0, 0);
122249259Sdim
123249259Sdim//===----------------------------------------------------------------------===//
124249259Sdim// PointerAlignElem, PointerAlign support
125249259Sdim//===----------------------------------------------------------------------===//
126249259Sdim
127249259SdimPointerAlignElem
128249259SdimPointerAlignElem::get(uint32_t addr_space, unsigned abi_align,
129249259Sdim                      unsigned pref_align, uint32_t bit_width) {
130249259Sdim  assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
131249259Sdim  PointerAlignElem retval;
132249259Sdim  retval.AddressSpace = addr_space;
133249259Sdim  retval.ABIAlign = abi_align;
134249259Sdim  retval.PrefAlign = pref_align;
135249259Sdim  retval.TypeBitWidth = bit_width;
136249259Sdim  return retval;
137249259Sdim}
138249259Sdim
139249259Sdimbool
140249259SdimPointerAlignElem::operator==(const PointerAlignElem &rhs) const {
141249259Sdim  return (ABIAlign == rhs.ABIAlign
142249259Sdim          && AddressSpace == rhs.AddressSpace
143249259Sdim          && PrefAlign == rhs.PrefAlign
144249259Sdim          && TypeBitWidth == rhs.TypeBitWidth);
145249259Sdim}
146249259Sdim
147249259Sdimconst PointerAlignElem
148249259SdimDataLayout::InvalidPointerElem = PointerAlignElem::get(~0U, 0U, 0U, 0U);
149249259Sdim
150249259Sdim//===----------------------------------------------------------------------===//
151249259Sdim//                       DataLayout Class Implementation
152249259Sdim//===----------------------------------------------------------------------===//
153249259Sdim
154249259Sdimvoid DataLayout::init(StringRef Desc) {
155249259Sdim  initializeDataLayoutPass(*PassRegistry::getPassRegistry());
156249259Sdim
157249259Sdim  LayoutMap = 0;
158249259Sdim  LittleEndian = false;
159249259Sdim  StackNaturalAlign = 0;
160249259Sdim
161249259Sdim  // Default alignments
162249259Sdim  setAlignment(INTEGER_ALIGN,   1,  1, 1);   // i1
163249259Sdim  setAlignment(INTEGER_ALIGN,   1,  1, 8);   // i8
164249259Sdim  setAlignment(INTEGER_ALIGN,   2,  2, 16);  // i16
165249259Sdim  setAlignment(INTEGER_ALIGN,   4,  4, 32);  // i32
166249259Sdim  setAlignment(INTEGER_ALIGN,   4,  8, 64);  // i64
167249259Sdim  setAlignment(FLOAT_ALIGN,     2,  2, 16);  // half
168249259Sdim  setAlignment(FLOAT_ALIGN,     4,  4, 32);  // float
169249259Sdim  setAlignment(FLOAT_ALIGN,     8,  8, 64);  // double
170249259Sdim  setAlignment(FLOAT_ALIGN,    16, 16, 128); // ppcf128, quad, ...
171249259Sdim  setAlignment(VECTOR_ALIGN,    8,  8, 64);  // v2i32, v1i64, ...
172249259Sdim  setAlignment(VECTOR_ALIGN,   16, 16, 128); // v16i8, v8i16, v4i32, ...
173249259Sdim  setAlignment(AGGREGATE_ALIGN, 0,  8,  0);  // struct
174249259Sdim  setPointerAlignment(0, 8, 8, 8);
175249259Sdim
176249259Sdim  parseSpecifier(Desc);
177249259Sdim}
178249259Sdim
179249259Sdim/// Checked version of split, to ensure mandatory subparts.
180249259Sdimstatic std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
181249259Sdim  assert(!Str.empty() && "parse error, string can't be empty here");
182249259Sdim  std::pair<StringRef, StringRef> Split = Str.split(Separator);
183249259Sdim  assert((!Split.second.empty() || Split.first == Str) &&
184249259Sdim         "a trailing separator is not allowed");
185249259Sdim  return Split;
186249259Sdim}
187249259Sdim
188249259Sdim/// Get an unsinged integer, including error checks.
189249259Sdimstatic unsigned getInt(StringRef R) {
190249259Sdim  unsigned Result;
191249259Sdim  bool error = R.getAsInteger(10, Result); (void)error;
192249259Sdim  assert(!error && "not a number, or does not fit in an unsigned int");
193249259Sdim  return Result;
194249259Sdim}
195249259Sdim
196249259Sdim/// Convert bits into bytes. Assert if not a byte width multiple.
197249259Sdimstatic unsigned inBytes(unsigned Bits) {
198249259Sdim  assert(Bits % 8 == 0 && "number of bits must be a byte width multiple");
199249259Sdim  return Bits / 8;
200249259Sdim}
201249259Sdim
202249259Sdimvoid DataLayout::parseSpecifier(StringRef Desc) {
203249259Sdim  while (!Desc.empty()) {
204249259Sdim    // Split at '-'.
205249259Sdim    std::pair<StringRef, StringRef> Split = split(Desc, '-');
206249259Sdim    Desc = Split.second;
207249259Sdim
208249259Sdim    // Split at ':'.
209249259Sdim    Split = split(Split.first, ':');
210249259Sdim
211249259Sdim    // Aliases used below.
212249259Sdim    StringRef &Tok  = Split.first;  // Current token.
213249259Sdim    StringRef &Rest = Split.second; // The rest of the string.
214249259Sdim
215249259Sdim    char Specifier = Tok.front();
216249259Sdim    Tok = Tok.substr(1);
217249259Sdim
218249259Sdim    switch (Specifier) {
219249259Sdim    case 'E':
220249259Sdim      LittleEndian = false;
221249259Sdim      break;
222249259Sdim    case 'e':
223249259Sdim      LittleEndian = true;
224249259Sdim      break;
225249259Sdim    case 'p': {
226249259Sdim      // Address space.
227249259Sdim      unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
228249259Sdim      assert(AddrSpace < 1 << 24 &&
229249259Sdim             "Invalid address space, must be a 24bit integer");
230249259Sdim
231249259Sdim      // Size.
232249259Sdim      Split = split(Rest, ':');
233249259Sdim      unsigned PointerMemSize = inBytes(getInt(Tok));
234249259Sdim
235249259Sdim      // ABI alignment.
236249259Sdim      Split = split(Rest, ':');
237249259Sdim      unsigned PointerABIAlign = inBytes(getInt(Tok));
238249259Sdim
239249259Sdim      // Preferred alignment.
240249259Sdim      unsigned PointerPrefAlign = PointerABIAlign;
241249259Sdim      if (!Rest.empty()) {
242249259Sdim        Split = split(Rest, ':');
243249259Sdim        PointerPrefAlign = inBytes(getInt(Tok));
244249259Sdim      }
245249259Sdim
246249259Sdim      setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
247249259Sdim                          PointerMemSize);
248249259Sdim      break;
249249259Sdim    }
250249259Sdim    case 'i':
251249259Sdim    case 'v':
252249259Sdim    case 'f':
253249259Sdim    case 'a':
254249259Sdim    case 's': {
255249259Sdim      AlignTypeEnum AlignType;
256249259Sdim      switch (Specifier) {
257249259Sdim      default:
258249259Sdim      case 'i': AlignType = INTEGER_ALIGN; break;
259249259Sdim      case 'v': AlignType = VECTOR_ALIGN; break;
260249259Sdim      case 'f': AlignType = FLOAT_ALIGN; break;
261249259Sdim      case 'a': AlignType = AGGREGATE_ALIGN; break;
262249259Sdim      case 's': AlignType = STACK_ALIGN; break;
263249259Sdim      }
264249259Sdim
265249259Sdim      // Bit size.
266249259Sdim      unsigned Size = Tok.empty() ? 0 : getInt(Tok);
267249259Sdim
268249259Sdim      // ABI alignment.
269249259Sdim      Split = split(Rest, ':');
270249259Sdim      unsigned ABIAlign = inBytes(getInt(Tok));
271249259Sdim
272249259Sdim      // Preferred alignment.
273249259Sdim      unsigned PrefAlign = ABIAlign;
274249259Sdim      if (!Rest.empty()) {
275249259Sdim        Split = split(Rest, ':');
276249259Sdim        PrefAlign = inBytes(getInt(Tok));
277249259Sdim      }
278249259Sdim
279249259Sdim      setAlignment(AlignType, ABIAlign, PrefAlign, Size);
280249259Sdim
281249259Sdim      break;
282249259Sdim    }
283249259Sdim    case 'n':  // Native integer types.
284249259Sdim      for (;;) {
285249259Sdim        unsigned Width = getInt(Tok);
286249259Sdim        assert(Width != 0 && "width must be non-zero");
287249259Sdim        LegalIntWidths.push_back(Width);
288249259Sdim        if (Rest.empty())
289249259Sdim          break;
290249259Sdim        Split = split(Rest, ':');
291249259Sdim      }
292249259Sdim      break;
293249259Sdim    case 'S': { // Stack natural alignment.
294249259Sdim      StackNaturalAlign = inBytes(getInt(Tok));
295249259Sdim      break;
296249259Sdim    }
297249259Sdim    default:
298249259Sdim      llvm_unreachable("Unknown specifier in datalayout string");
299249259Sdim      break;
300249259Sdim    }
301249259Sdim  }
302249259Sdim}
303249259Sdim
304249259Sdim/// Default ctor.
305249259Sdim///
306249259Sdim/// @note This has to exist, because this is a pass, but it should never be
307249259Sdim/// used.
308249259SdimDataLayout::DataLayout() : ImmutablePass(ID) {
309249259Sdim  report_fatal_error("Bad DataLayout ctor used.  "
310249259Sdim                     "Tool did not specify a DataLayout to use?");
311249259Sdim}
312249259Sdim
313249259SdimDataLayout::DataLayout(const Module *M)
314249259Sdim  : ImmutablePass(ID) {
315249259Sdim  init(M->getDataLayout());
316249259Sdim}
317249259Sdim
318249259Sdimvoid
319249259SdimDataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
320249259Sdim                         unsigned pref_align, uint32_t bit_width) {
321249259Sdim  assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
322249259Sdim  assert(pref_align < (1 << 16) && "Alignment doesn't fit in bitfield");
323249259Sdim  assert(bit_width < (1 << 24) && "Bit width doesn't fit in bitfield");
324249259Sdim  for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
325249259Sdim    if (Alignments[i].AlignType == (unsigned)align_type &&
326249259Sdim        Alignments[i].TypeBitWidth == bit_width) {
327249259Sdim      // Update the abi, preferred alignments.
328249259Sdim      Alignments[i].ABIAlign = abi_align;
329249259Sdim      Alignments[i].PrefAlign = pref_align;
330249259Sdim      return;
331249259Sdim    }
332249259Sdim  }
333249259Sdim
334249259Sdim  Alignments.push_back(LayoutAlignElem::get(align_type, abi_align,
335249259Sdim                                            pref_align, bit_width));
336249259Sdim}
337249259Sdim
338249259Sdimvoid
339249259SdimDataLayout::setPointerAlignment(uint32_t addr_space, unsigned abi_align,
340249259Sdim                         unsigned pref_align, uint32_t bit_width) {
341249259Sdim  assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
342249259Sdim  DenseMap<unsigned,PointerAlignElem>::iterator val = Pointers.find(addr_space);
343249259Sdim  if (val == Pointers.end()) {
344249259Sdim    Pointers[addr_space] = PointerAlignElem::get(addr_space,
345249259Sdim          abi_align, pref_align, bit_width);
346249259Sdim  } else {
347249259Sdim    val->second.ABIAlign = abi_align;
348249259Sdim    val->second.PrefAlign = pref_align;
349249259Sdim    val->second.TypeBitWidth = bit_width;
350249259Sdim  }
351249259Sdim}
352249259Sdim
353249259Sdim/// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
354249259Sdim/// preferred if ABIInfo = false) the layout wants for the specified datatype.
355249259Sdimunsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
356249259Sdim                                      uint32_t BitWidth, bool ABIInfo,
357249259Sdim                                      Type *Ty) const {
358249259Sdim  // Check to see if we have an exact match and remember the best match we see.
359249259Sdim  int BestMatchIdx = -1;
360249259Sdim  int LargestInt = -1;
361249259Sdim  for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
362249259Sdim    if (Alignments[i].AlignType == (unsigned)AlignType &&
363249259Sdim        Alignments[i].TypeBitWidth == BitWidth)
364249259Sdim      return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
365249259Sdim
366249259Sdim    // The best match so far depends on what we're looking for.
367249259Sdim     if (AlignType == INTEGER_ALIGN &&
368249259Sdim         Alignments[i].AlignType == INTEGER_ALIGN) {
369249259Sdim      // The "best match" for integers is the smallest size that is larger than
370249259Sdim      // the BitWidth requested.
371249259Sdim      if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
372249259Sdim          Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
373249259Sdim        BestMatchIdx = i;
374249259Sdim      // However, if there isn't one that's larger, then we must use the
375249259Sdim      // largest one we have (see below)
376249259Sdim      if (LargestInt == -1 ||
377249259Sdim          Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
378249259Sdim        LargestInt = i;
379249259Sdim    }
380249259Sdim  }
381249259Sdim
382249259Sdim  // Okay, we didn't find an exact solution.  Fall back here depending on what
383249259Sdim  // is being looked for.
384249259Sdim  if (BestMatchIdx == -1) {
385249259Sdim    // If we didn't find an integer alignment, fall back on most conservative.
386249259Sdim    if (AlignType == INTEGER_ALIGN) {
387249259Sdim      BestMatchIdx = LargestInt;
388249259Sdim    } else {
389249259Sdim      assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
390249259Sdim
391249259Sdim      // By default, use natural alignment for vector types. This is consistent
392249259Sdim      // with what clang and llvm-gcc do.
393249259Sdim      unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
394249259Sdim      Align *= cast<VectorType>(Ty)->getNumElements();
395249259Sdim      // If the alignment is not a power of 2, round up to the next power of 2.
396249259Sdim      // This happens for non-power-of-2 length vectors.
397249259Sdim      if (Align & (Align-1))
398249259Sdim        Align = NextPowerOf2(Align);
399249259Sdim      return Align;
400249259Sdim    }
401249259Sdim  }
402249259Sdim
403249259Sdim  // Since we got a "best match" index, just return it.
404249259Sdim  return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
405249259Sdim                 : Alignments[BestMatchIdx].PrefAlign;
406249259Sdim}
407249259Sdim
408249259Sdimnamespace {
409249259Sdim
410249259Sdimclass StructLayoutMap {
411249259Sdim  typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
412249259Sdim  LayoutInfoTy LayoutInfo;
413249259Sdim
414249259Sdimpublic:
415249259Sdim  virtual ~StructLayoutMap() {
416249259Sdim    // Remove any layouts.
417249259Sdim    for (LayoutInfoTy::iterator I = LayoutInfo.begin(), E = LayoutInfo.end();
418249259Sdim         I != E; ++I) {
419249259Sdim      StructLayout *Value = I->second;
420249259Sdim      Value->~StructLayout();
421249259Sdim      free(Value);
422249259Sdim    }
423249259Sdim  }
424249259Sdim
425249259Sdim  StructLayout *&operator[](StructType *STy) {
426249259Sdim    return LayoutInfo[STy];
427249259Sdim  }
428249259Sdim
429249259Sdim  // for debugging...
430249259Sdim  virtual void dump() const {}
431249259Sdim};
432249259Sdim
433249259Sdim} // end anonymous namespace
434249259Sdim
435249259SdimDataLayout::~DataLayout() {
436249259Sdim  delete static_cast<StructLayoutMap*>(LayoutMap);
437249259Sdim}
438249259Sdim
439249259Sdimbool DataLayout::doFinalization(Module &M) {
440249259Sdim  delete static_cast<StructLayoutMap*>(LayoutMap);
441249259Sdim  LayoutMap = 0;
442249259Sdim  return false;
443249259Sdim}
444249259Sdim
445249259Sdimconst StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
446249259Sdim  if (!LayoutMap)
447249259Sdim    LayoutMap = new StructLayoutMap();
448249259Sdim
449249259Sdim  StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
450249259Sdim  StructLayout *&SL = (*STM)[Ty];
451249259Sdim  if (SL) return SL;
452249259Sdim
453249259Sdim  // Otherwise, create the struct layout.  Because it is variable length, we
454249259Sdim  // malloc it, then use placement new.
455249259Sdim  int NumElts = Ty->getNumElements();
456249259Sdim  StructLayout *L =
457249259Sdim    (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
458249259Sdim
459249259Sdim  // Set SL before calling StructLayout's ctor.  The ctor could cause other
460249259Sdim  // entries to be added to TheMap, invalidating our reference.
461249259Sdim  SL = L;
462249259Sdim
463249259Sdim  new (L) StructLayout(Ty, *this);
464249259Sdim
465249259Sdim  return L;
466249259Sdim}
467249259Sdim
468249259Sdimstd::string DataLayout::getStringRepresentation() const {
469249259Sdim  std::string Result;
470249259Sdim  raw_string_ostream OS(Result);
471249259Sdim
472249259Sdim  OS << (LittleEndian ? "e" : "E");
473249259Sdim  SmallVector<unsigned, 8> addrSpaces;
474249259Sdim  // Lets get all of the known address spaces and sort them
475249259Sdim  // into increasing order so that we can emit the string
476249259Sdim  // in a cleaner format.
477249259Sdim  for (DenseMap<unsigned, PointerAlignElem>::const_iterator
478249259Sdim      pib = Pointers.begin(), pie = Pointers.end();
479249259Sdim      pib != pie; ++pib) {
480249259Sdim    addrSpaces.push_back(pib->first);
481249259Sdim  }
482249259Sdim  std::sort(addrSpaces.begin(), addrSpaces.end());
483263509Sdim  for (SmallVectorImpl<unsigned>::iterator asb = addrSpaces.begin(),
484249259Sdim      ase = addrSpaces.end(); asb != ase; ++asb) {
485249259Sdim    const PointerAlignElem &PI = Pointers.find(*asb)->second;
486249259Sdim    OS << "-p";
487249259Sdim    if (PI.AddressSpace) {
488249259Sdim      OS << PI.AddressSpace;
489249259Sdim    }
490249259Sdim     OS << ":" << PI.TypeBitWidth*8 << ':' << PI.ABIAlign*8
491249259Sdim        << ':' << PI.PrefAlign*8;
492249259Sdim  }
493249259Sdim  OS << "-S" << StackNaturalAlign*8;
494249259Sdim
495249259Sdim  for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
496249259Sdim    const LayoutAlignElem &AI = Alignments[i];
497249259Sdim    OS << '-' << (char)AI.AlignType << AI.TypeBitWidth << ':'
498249259Sdim       << AI.ABIAlign*8 << ':' << AI.PrefAlign*8;
499249259Sdim  }
500249259Sdim
501249259Sdim  if (!LegalIntWidths.empty()) {
502249259Sdim    OS << "-n" << (unsigned)LegalIntWidths[0];
503249259Sdim
504249259Sdim    for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
505249259Sdim      OS << ':' << (unsigned)LegalIntWidths[i];
506249259Sdim  }
507249259Sdim  return OS.str();
508249259Sdim}
509249259Sdim
510263509Sdimunsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
511263509Sdim  assert(Ty->isPtrOrPtrVectorTy() &&
512263509Sdim         "This should only be called with a pointer or pointer vector type");
513249259Sdim
514263509Sdim  if (Ty->isPointerTy())
515263509Sdim    return getTypeSizeInBits(Ty);
516263509Sdim
517263509Sdim  return getTypeSizeInBits(Ty->getScalarType());
518263509Sdim}
519263509Sdim
520249259Sdim/*!
521249259Sdim  \param abi_or_pref Flag that determines which alignment is returned. true
522249259Sdim  returns the ABI alignment, false returns the preferred alignment.
523249259Sdim  \param Ty The underlying type for which alignment is determined.
524249259Sdim
525249259Sdim  Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
526249259Sdim  == false) for the requested type \a Ty.
527249259Sdim */
528249259Sdimunsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
529249259Sdim  int AlignType = -1;
530249259Sdim
531249259Sdim  assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
532249259Sdim  switch (Ty->getTypeID()) {
533249259Sdim  // Early escape for the non-numeric types.
534249259Sdim  case Type::LabelTyID:
535249259Sdim    return (abi_or_pref
536249259Sdim            ? getPointerABIAlignment(0)
537249259Sdim            : getPointerPrefAlignment(0));
538249259Sdim  case Type::PointerTyID: {
539249259Sdim    unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
540249259Sdim    return (abi_or_pref
541249259Sdim            ? getPointerABIAlignment(AS)
542249259Sdim            : getPointerPrefAlignment(AS));
543249259Sdim    }
544249259Sdim  case Type::ArrayTyID:
545249259Sdim    return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
546249259Sdim
547249259Sdim  case Type::StructTyID: {
548249259Sdim    // Packed structure types always have an ABI alignment of one.
549249259Sdim    if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
550249259Sdim      return 1;
551249259Sdim
552249259Sdim    // Get the layout annotation... which is lazily created on demand.
553249259Sdim    const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
554249259Sdim    unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
555249259Sdim    return std::max(Align, Layout->getAlignment());
556249259Sdim  }
557249259Sdim  case Type::IntegerTyID:
558249259Sdim    AlignType = INTEGER_ALIGN;
559249259Sdim    break;
560249259Sdim  case Type::HalfTyID:
561249259Sdim  case Type::FloatTyID:
562249259Sdim  case Type::DoubleTyID:
563249259Sdim  // PPC_FP128TyID and FP128TyID have different data contents, but the
564249259Sdim  // same size and alignment, so they look the same here.
565249259Sdim  case Type::PPC_FP128TyID:
566249259Sdim  case Type::FP128TyID:
567249259Sdim  case Type::X86_FP80TyID:
568249259Sdim    AlignType = FLOAT_ALIGN;
569249259Sdim    break;
570249259Sdim  case Type::X86_MMXTyID:
571249259Sdim  case Type::VectorTyID:
572249259Sdim    AlignType = VECTOR_ALIGN;
573249259Sdim    break;
574249259Sdim  default:
575249259Sdim    llvm_unreachable("Bad type for getAlignment!!!");
576249259Sdim  }
577249259Sdim
578249259Sdim  return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
579249259Sdim                          abi_or_pref, Ty);
580249259Sdim}
581249259Sdim
582249259Sdimunsigned DataLayout::getABITypeAlignment(Type *Ty) const {
583249259Sdim  return getAlignment(Ty, true);
584249259Sdim}
585249259Sdim
586249259Sdim/// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
587249259Sdim/// an integer type of the specified bitwidth.
588249259Sdimunsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
589249259Sdim  return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, 0);
590249259Sdim}
591249259Sdim
592249259Sdimunsigned DataLayout::getCallFrameTypeAlignment(Type *Ty) const {
593249259Sdim  for (unsigned i = 0, e = Alignments.size(); i != e; ++i)
594249259Sdim    if (Alignments[i].AlignType == STACK_ALIGN)
595249259Sdim      return Alignments[i].ABIAlign;
596249259Sdim
597249259Sdim  return getABITypeAlignment(Ty);
598249259Sdim}
599249259Sdim
600249259Sdimunsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
601249259Sdim  return getAlignment(Ty, false);
602249259Sdim}
603249259Sdim
604249259Sdimunsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
605249259Sdim  unsigned Align = getPrefTypeAlignment(Ty);
606249259Sdim  assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
607249259Sdim  return Log2_32(Align);
608249259Sdim}
609249259Sdim
610249259SdimIntegerType *DataLayout::getIntPtrType(LLVMContext &C,
611249259Sdim                                       unsigned AddressSpace) const {
612249259Sdim  return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
613249259Sdim}
614249259Sdim
615249259SdimType *DataLayout::getIntPtrType(Type *Ty) const {
616249259Sdim  assert(Ty->isPtrOrPtrVectorTy() &&
617249259Sdim         "Expected a pointer or pointer vector type.");
618249259Sdim  unsigned NumBits = getTypeSizeInBits(Ty->getScalarType());
619249259Sdim  IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
620249259Sdim  if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
621249259Sdim    return VectorType::get(IntTy, VecTy->getNumElements());
622249259Sdim  return IntTy;
623249259Sdim}
624249259Sdim
625249259SdimType *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
626249259Sdim  for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
627249259Sdim    if (Width <= LegalIntWidths[i])
628249259Sdim      return Type::getIntNTy(C, LegalIntWidths[i]);
629249259Sdim  return 0;
630249259Sdim}
631249259Sdim
632263509Sdimunsigned DataLayout::getLargestLegalIntTypeSize() const {
633263509Sdim  unsigned MaxWidth = 0;
634263509Sdim  for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
635263509Sdim    MaxWidth = std::max<unsigned>(MaxWidth, LegalIntWidths[i]);
636263509Sdim  return MaxWidth;
637263509Sdim}
638263509Sdim
639249259Sdimuint64_t DataLayout::getIndexedOffset(Type *ptrTy,
640249259Sdim                                      ArrayRef<Value *> Indices) const {
641249259Sdim  Type *Ty = ptrTy;
642249259Sdim  assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
643249259Sdim  uint64_t Result = 0;
644249259Sdim
645249259Sdim  generic_gep_type_iterator<Value* const*>
646249259Sdim    TI = gep_type_begin(ptrTy, Indices);
647249259Sdim  for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
648249259Sdim       ++CurIDX, ++TI) {
649249259Sdim    if (StructType *STy = dyn_cast<StructType>(*TI)) {
650249259Sdim      assert(Indices[CurIDX]->getType() ==
651249259Sdim             Type::getInt32Ty(ptrTy->getContext()) &&
652249259Sdim             "Illegal struct idx");
653249259Sdim      unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
654249259Sdim
655249259Sdim      // Get structure layout information...
656249259Sdim      const StructLayout *Layout = getStructLayout(STy);
657249259Sdim
658249259Sdim      // Add in the offset, as calculated by the structure layout info...
659249259Sdim      Result += Layout->getElementOffset(FieldNo);
660249259Sdim
661249259Sdim      // Update Ty to refer to current element
662249259Sdim      Ty = STy->getElementType(FieldNo);
663249259Sdim    } else {
664249259Sdim      // Update Ty to refer to current element
665249259Sdim      Ty = cast<SequentialType>(Ty)->getElementType();
666249259Sdim
667249259Sdim      // Get the array index and the size of each array element.
668249259Sdim      if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
669249259Sdim        Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
670249259Sdim    }
671249259Sdim  }
672249259Sdim
673249259Sdim  return Result;
674249259Sdim}
675249259Sdim
676249259Sdim/// getPreferredAlignment - Return the preferred alignment of the specified
677249259Sdim/// global.  This includes an explicitly requested alignment (if the global
678249259Sdim/// has one).
679249259Sdimunsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
680249259Sdim  Type *ElemType = GV->getType()->getElementType();
681249259Sdim  unsigned Alignment = getPrefTypeAlignment(ElemType);
682249259Sdim  unsigned GVAlignment = GV->getAlignment();
683249259Sdim  if (GVAlignment >= Alignment) {
684249259Sdim    Alignment = GVAlignment;
685249259Sdim  } else if (GVAlignment != 0) {
686249259Sdim    Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
687249259Sdim  }
688249259Sdim
689249259Sdim  if (GV->hasInitializer() && GVAlignment == 0) {
690249259Sdim    if (Alignment < 16) {
691249259Sdim      // If the global is not external, see if it is large.  If so, give it a
692249259Sdim      // larger alignment.
693249259Sdim      if (getTypeSizeInBits(ElemType) > 128)
694249259Sdim        Alignment = 16;    // 16-byte alignment.
695249259Sdim    }
696249259Sdim  }
697249259Sdim  return Alignment;
698249259Sdim}
699249259Sdim
700249259Sdim/// getPreferredAlignmentLog - Return the preferred alignment of the
701249259Sdim/// specified global, returned in log form.  This includes an explicitly
702249259Sdim/// requested alignment (if the global has one).
703249259Sdimunsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
704249259Sdim  return Log2_32(getPreferredAlignment(GV));
705249259Sdim}
706