blob: ffb3adcdbf8a07940f93e7d05bdb5cf6dd8d39c3 [file] [log] [blame]
Eugene Zelenkof53a7b42017-05-05 22:30:37 +00001//===- DataLayout.cpp - Data size & alignment routines ---------------------==//
Micah Villmowac34b5c2012-10-04 22:08:14 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Micah Villmowac34b5c2012-10-04 22:08:14 +00006//
7//===----------------------------------------------------------------------===//
8//
Micah Villmowb4faa152012-10-04 23:01:22 +00009// This file defines layout properties related to datatype size/offset/alignment
Micah Villmowac34b5c2012-10-04 22:08:14 +000010// information.
11//
12// This structure should be created once, filled in if the defaults are not
13// correct and then passed around by const&. None of the members functions
14// require modification to the object.
15//
16//===----------------------------------------------------------------------===//
17
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000020#include "llvm/ADT/StringRef.h"
Rafael Espindola58873562014-01-03 19:21:54 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000024#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000025#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000027#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/Casting.h"
Alex Zinenko874aef82020-08-17 13:34:07 +020030#include "llvm/Support/Error.h"
Micah Villmowac34b5c2012-10-04 22:08:14 +000031#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/MathExtras.h"
Graham Hunterb3025612019-10-08 12:53:54 +000033#include "llvm/Support/TypeSize.h"
Micah Villmowac34b5c2012-10-04 22:08:14 +000034#include <algorithm>
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000035#include <cassert>
36#include <cstdint>
Micah Villmowac34b5c2012-10-04 22:08:14 +000037#include <cstdlib>
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000038#include <tuple>
39#include <utility>
40
Micah Villmowac34b5c2012-10-04 22:08:14 +000041using namespace llvm;
42
Micah Villmowac34b5c2012-10-04 22:08:14 +000043//===----------------------------------------------------------------------===//
44// Support for StructLayout
45//===----------------------------------------------------------------------===//
46
Pete Cooper0ae73932015-07-27 17:15:28 +000047StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
Micah Villmowac34b5c2012-10-04 22:08:14 +000048 assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
Micah Villmowac34b5c2012-10-04 22:08:14 +000049 StructSize = 0;
Mehdi Amini1c131b32015-12-15 01:44:07 +000050 IsPadded = false;
Micah Villmowac34b5c2012-10-04 22:08:14 +000051 NumElements = ST->getNumElements();
52
53 // Loop over each of the elements, placing them in memory.
54 for (unsigned i = 0, e = NumElements; i != e; ++i) {
55 Type *Ty = ST->getElementType(i);
Guillaume Chateletd3085c22020-07-01 14:31:56 +000056 const Align TyAlign = ST->isPacked() ? Align(1) : DL.getABITypeAlign(Ty);
Micah Villmowac34b5c2012-10-04 22:08:14 +000057
58 // Add padding if necessary to align the data element properly.
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +000059 if (!isAligned(TyAlign, StructSize)) {
Mehdi Amini1c131b32015-12-15 01:44:07 +000060 IsPadded = true;
Rui Ueyamada00f2f2016-01-14 21:06:47 +000061 StructSize = alignTo(StructSize, TyAlign);
Mehdi Amini1c131b32015-12-15 01:44:07 +000062 }
Micah Villmowac34b5c2012-10-04 22:08:14 +000063
64 // Keep track of maximum alignment constraint.
65 StructAlignment = std::max(TyAlign, StructAlignment);
66
67 MemberOffsets[i] = StructSize;
Eli Bendersky41913c72013-04-16 15:41:18 +000068 StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
Micah Villmowac34b5c2012-10-04 22:08:14 +000069 }
70
Micah Villmowac34b5c2012-10-04 22:08:14 +000071 // Add padding to the end of the struct so that it could be put in an array
72 // and all array elements would be aligned correctly.
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +000073 if (!isAligned(StructAlignment, StructSize)) {
Mehdi Amini1c131b32015-12-15 01:44:07 +000074 IsPadded = true;
Rui Ueyamada00f2f2016-01-14 21:06:47 +000075 StructSize = alignTo(StructSize, StructAlignment);
Mehdi Amini1c131b32015-12-15 01:44:07 +000076 }
Micah Villmowac34b5c2012-10-04 22:08:14 +000077}
78
Micah Villmowac34b5c2012-10-04 22:08:14 +000079/// getElementContainingOffset - Given a valid offset into the structure,
80/// return the structure index that contains it.
81unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
82 const uint64_t *SI =
83 std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
84 assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
85 --SI;
86 assert(*SI <= Offset && "upper_bound didn't work");
87 assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
88 (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
89 "Upper bound didn't work!");
90
91 // Multiple fields can have the same offset if any of them are zero sized.
92 // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
93 // at the i32 element, because it is the last element at that offset. This is
94 // the right one to return, because anything after it will have a higher
95 // offset, implying that this element is non-empty.
96 return SI-&MemberOffsets[0];
97}
98
99//===----------------------------------------------------------------------===//
Micah Villmowb4faa152012-10-04 23:01:22 +0000100// LayoutAlignElem, LayoutAlign support
Micah Villmowac34b5c2012-10-04 22:08:14 +0000101//===----------------------------------------------------------------------===//
102
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000103LayoutAlignElem LayoutAlignElem::get(AlignTypeEnum align_type, Align abi_align,
104 Align pref_align, uint32_t bit_width) {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000105 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
Micah Villmowb4faa152012-10-04 23:01:22 +0000106 LayoutAlignElem retval;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000107 retval.AlignType = align_type;
108 retval.ABIAlign = abi_align;
109 retval.PrefAlign = pref_align;
110 retval.TypeBitWidth = bit_width;
111 return retval;
112}
113
114bool
Micah Villmowb4faa152012-10-04 23:01:22 +0000115LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000116 return (AlignType == rhs.AlignType
117 && ABIAlign == rhs.ABIAlign
118 && PrefAlign == rhs.PrefAlign
119 && TypeBitWidth == rhs.TypeBitWidth);
120}
121
Micah Villmow89021e42012-10-09 16:06:12 +0000122//===----------------------------------------------------------------------===//
123// PointerAlignElem, PointerAlign support
124//===----------------------------------------------------------------------===//
125
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000126PointerAlignElem PointerAlignElem::get(uint32_t AddressSpace, Align ABIAlign,
127 Align PrefAlign, uint32_t TypeByteWidth,
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000128 uint32_t IndexWidth) {
Rafael Espindolaf39136c2013-12-13 23:15:20 +0000129 assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
Micah Villmow89021e42012-10-09 16:06:12 +0000130 PointerAlignElem retval;
Rafael Espindolaf39136c2013-12-13 23:15:20 +0000131 retval.AddressSpace = AddressSpace;
132 retval.ABIAlign = ABIAlign;
133 retval.PrefAlign = PrefAlign;
134 retval.TypeByteWidth = TypeByteWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000135 retval.IndexWidth = IndexWidth;
Micah Villmow89021e42012-10-09 16:06:12 +0000136 return retval;
137}
138
139bool
140PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
141 return (ABIAlign == rhs.ABIAlign
142 && AddressSpace == rhs.AddressSpace
143 && PrefAlign == rhs.PrefAlign
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000144 && TypeByteWidth == rhs.TypeByteWidth
145 && IndexWidth == rhs.IndexWidth);
Micah Villmow89021e42012-10-09 16:06:12 +0000146}
147
Micah Villmowac34b5c2012-10-04 22:08:14 +0000148//===----------------------------------------------------------------------===//
Micah Villmowb4faa152012-10-04 23:01:22 +0000149// DataLayout Class Implementation
Micah Villmowac34b5c2012-10-04 22:08:14 +0000150//===----------------------------------------------------------------------===//
151
Rafael Espindola58873562014-01-03 19:21:54 +0000152const char *DataLayout::getManglingComponent(const Triple &T) {
153 if (T.isOSBinFormatMachO())
154 return "-m:o";
David Majnemer7db449a2015-03-17 23:54:51 +0000155 if (T.isOSWindows() && T.isOSBinFormatCOFF())
156 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
jasonliu572dde52020-07-02 22:45:59 +0000157 if (T.isOSBinFormatXCOFF())
158 return "-m:a";
Saleem Abdulrasoolcd130822014-04-02 20:32:05 +0000159 return "-m:e";
Rafael Espindola58873562014-01-03 19:21:54 +0000160}
161
Rafael Espindolae23b8772013-12-20 15:21:32 +0000162static const LayoutAlignElem DefaultAlignments[] = {
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000163 {INTEGER_ALIGN, 1, Align(1), Align(1)}, // i1
164 {INTEGER_ALIGN, 8, Align(1), Align(1)}, // i8
165 {INTEGER_ALIGN, 16, Align(2), Align(2)}, // i16
166 {INTEGER_ALIGN, 32, Align(4), Align(4)}, // i32
167 {INTEGER_ALIGN, 64, Align(4), Align(8)}, // i64
Ties Stuij8c24f332020-03-31 23:49:38 +0100168 {FLOAT_ALIGN, 16, Align(2), Align(2)}, // half, bfloat
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000169 {FLOAT_ALIGN, 32, Align(4), Align(4)}, // float
170 {FLOAT_ALIGN, 64, Align(8), Align(8)}, // double
171 {FLOAT_ALIGN, 128, Align(16), Align(16)}, // ppcf128, quad, ...
172 {VECTOR_ALIGN, 64, Align(8), Align(8)}, // v2i32, v1i64, ...
173 {VECTOR_ALIGN, 128, Align(16), Align(16)}, // v16i8, v8i16, v4i32, ...
174 {AGGREGATE_ALIGN, 0, Align(1), Align(8)} // struct
Rafael Espindola458a4852013-12-19 23:03:03 +0000175};
176
Rafael Espindola248ac132014-02-25 22:23:04 +0000177void DataLayout::reset(StringRef Desc) {
178 clear();
179
Craig Topperc6207612014-04-09 06:08:46 +0000180 LayoutMap = nullptr;
Chandler Carruthf67321c2014-10-20 10:41:29 +0000181 BigEndian = false;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000182 AllocaAddrSpace = 0;
Guillaume Chatelet65e4b472019-08-05 09:00:43 +0000183 StackNaturalAlign.reset();
Dylan McKayced2fe62018-02-19 09:56:22 +0000184 ProgramAddrSpace = 0;
Guillaume Chatelet65e4b472019-08-05 09:00:43 +0000185 FunctionPtrAlign.reset();
Michael Platings308e82e2019-03-08 10:44:06 +0000186 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
Rafael Espindola58873562014-01-03 19:21:54 +0000187 ManglingMode = MM_None;
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000188 NonIntegralAddressSpaces.clear();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000189
190 // Default alignments
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000191 for (const LayoutAlignElem &E : DefaultAlignments) {
Alex Zinenko874aef82020-08-17 13:34:07 +0200192 if (Error Err = setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign,
193 E.PrefAlign, E.TypeBitWidth))
194 return report_fatal_error(std::move(Err));
Rafael Espindola458a4852013-12-19 23:03:03 +0000195 }
Alex Zinenko874aef82020-08-17 13:34:07 +0200196 if (Error Err = setPointerAlignment(0, Align(8), Align(8), 8, 8))
197 return report_fatal_error(std::move(Err));
Patrik Hägglund01860a62012-11-14 09:04:56 +0000198
Alex Zinenko874aef82020-08-17 13:34:07 +0200199 if (Error Err = parseSpecifier(Desc))
200 return report_fatal_error(std::move(Err));
201}
202
203Expected<DataLayout> DataLayout::parse(StringRef LayoutDescription) {
204 DataLayout Layout("");
205 if (Error Err = Layout.parseSpecifier(LayoutDescription))
206 return std::move(Err);
207 return Layout;
208}
209
210static Error reportError(const Twine &Message) {
211 return createStringError(inconvertibleErrorCode(), Message);
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000212}
213
214/// Checked version of split, to ensure mandatory subparts.
Alex Zinenko874aef82020-08-17 13:34:07 +0200215static Error split(StringRef Str, char Separator,
216 std::pair<StringRef, StringRef> &Split) {
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000217 assert(!Str.empty() && "parse error, string can't be empty here");
Alex Zinenko874aef82020-08-17 13:34:07 +0200218 Split = Str.split(Separator);
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000219 if (Split.second.empty() && Split.first != Str)
Alex Zinenko874aef82020-08-17 13:34:07 +0200220 return reportError("Trailing separator in datalayout string");
David Majnemer612f3122014-12-10 02:36:41 +0000221 if (!Split.second.empty() && Split.first.empty())
Alex Zinenko874aef82020-08-17 13:34:07 +0200222 return reportError("Expected token before separator in datalayout string");
223 return Error::success();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000224}
225
Cameron McInally8af9eac2014-01-07 19:51:38 +0000226/// Get an unsigned integer, including error checks.
Alex Zinenko874aef82020-08-17 13:34:07 +0200227template <typename IntTy> static Error getInt(StringRef R, IntTy &Result) {
Patrik Hägglund504f4782012-11-28 14:32:52 +0000228 bool error = R.getAsInteger(10, Result); (void)error;
Cameron McInallyf0379fa2014-01-13 22:04:55 +0000229 if (error)
Alex Zinenko874aef82020-08-17 13:34:07 +0200230 return reportError("not a number, or does not fit in an unsigned int");
231 return Error::success();
Patrik Hägglund3eb16c52012-11-28 12:13:12 +0000232}
233
Alex Zinenko874aef82020-08-17 13:34:07 +0200234/// Get an unsigned integer representing the number of bits and convert it into
235/// bytes. Error out of not a byte width multiple.
236template <typename IntTy>
237static Error getIntInBytes(StringRef R, IntTy &Result) {
238 if (Error Err = getInt<IntTy>(R, Result))
239 return Err;
240 if (Result % 8)
241 return reportError("number of bits must be a byte width multiple");
242 Result /= 8;
243 return Error::success();
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000244}
245
Alex Zinenko874aef82020-08-17 13:34:07 +0200246static Error getAddrSpace(StringRef R, unsigned &AddrSpace) {
247 if (Error Err = getInt(R, AddrSpace))
248 return Err;
Dylan McKayced2fe62018-02-19 09:56:22 +0000249 if (!isUInt<24>(AddrSpace))
Alex Zinenko874aef82020-08-17 13:34:07 +0200250 return reportError("Invalid address space, must be a 24-bit integer");
251 return Error::success();
Dylan McKayced2fe62018-02-19 09:56:22 +0000252}
253
Alex Zinenko874aef82020-08-17 13:34:07 +0200254Error DataLayout::parseSpecifier(StringRef Desc) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100255 StringRepresentation = std::string(Desc);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000256 while (!Desc.empty()) {
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000257 // Split at '-'.
Alex Zinenko874aef82020-08-17 13:34:07 +0200258 std::pair<StringRef, StringRef> Split;
259 if (Error Err = split(Desc, '-', Split))
260 return Err;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000261 Desc = Split.second;
262
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000263 // Split at ':'.
Alex Zinenko874aef82020-08-17 13:34:07 +0200264 if (Error Err = split(Split.first, ':', Split))
265 return Err;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000266
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000267 // Aliases used below.
268 StringRef &Tok = Split.first; // Current token.
269 StringRef &Rest = Split.second; // The rest of the string.
Micah Villmowac34b5c2012-10-04 22:08:14 +0000270
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000271 if (Tok == "ni") {
272 do {
Alex Zinenko874aef82020-08-17 13:34:07 +0200273 if (Error Err = split(Rest, ':', Split))
274 return Err;
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000275 Rest = Split.second;
Alex Zinenko874aef82020-08-17 13:34:07 +0200276 unsigned AS;
277 if (Error Err = getInt(Split.first, AS))
278 return Err;
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000279 if (AS == 0)
Alex Zinenko874aef82020-08-17 13:34:07 +0200280 return reportError("Address space 0 can never be non-integral");
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000281 NonIntegralAddressSpaces.push_back(AS);
282 } while (!Rest.empty());
283
284 continue;
285 }
286
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000287 char Specifier = Tok.front();
288 Tok = Tok.substr(1);
289
290 switch (Specifier) {
Rafael Espindola6994fdf2014-01-01 22:29:43 +0000291 case 's':
Mehdi Amini4abf0242020-06-25 23:49:07 +0000292 // Deprecated, but ignoring here to preserve loading older textual llvm
293 // ASM file
Rafael Espindola6994fdf2014-01-01 22:29:43 +0000294 break;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000295 case 'E':
Chandler Carruthf67321c2014-10-20 10:41:29 +0000296 BigEndian = true;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000297 break;
298 case 'e':
Chandler Carruthf67321c2014-10-20 10:41:29 +0000299 BigEndian = false;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000300 break;
301 case 'p': {
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000302 // Address space.
Alex Zinenko874aef82020-08-17 13:34:07 +0200303 unsigned AddrSpace = 0;
304 if (!Tok.empty())
305 if (Error Err = getInt(Tok, AddrSpace))
306 return Err;
David Majnemer5330c692014-12-10 01:17:08 +0000307 if (!isUInt<24>(AddrSpace))
Alex Zinenko874aef82020-08-17 13:34:07 +0200308 return reportError("Invalid address space, must be a 24bit integer");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000309
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000310 // Size.
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000311 if (Rest.empty())
Alex Zinenko874aef82020-08-17 13:34:07 +0200312 return reportError(
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000313 "Missing size specification for pointer in datalayout string");
Alex Zinenko874aef82020-08-17 13:34:07 +0200314 if (Error Err = split(Rest, ':', Split))
315 return Err;
316 unsigned PointerMemSize;
317 if (Error Err = getIntInBytes(Tok, PointerMemSize))
318 return Err;
Owen Anderson5bc2bbe2015-03-02 06:00:02 +0000319 if (!PointerMemSize)
Alex Zinenko874aef82020-08-17 13:34:07 +0200320 return reportError("Invalid pointer size of 0 bytes");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000321
322 // ABI alignment.
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000323 if (Rest.empty())
Alex Zinenko874aef82020-08-17 13:34:07 +0200324 return reportError(
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000325 "Missing alignment specification for pointer in datalayout string");
Alex Zinenko874aef82020-08-17 13:34:07 +0200326 if (Error Err = split(Rest, ':', Split))
327 return Err;
328 unsigned PointerABIAlign;
329 if (Error Err = getIntInBytes(Tok, PointerABIAlign))
330 return Err;
Owen Anderson040f2f82015-03-02 06:33:51 +0000331 if (!isPowerOf2_64(PointerABIAlign))
Alex Zinenko874aef82020-08-17 13:34:07 +0200332 return reportError("Pointer ABI alignment must be a power of 2");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000333
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000334 // Size of index used in GEP for address calculation.
335 // The parameter is optional. By default it is equal to size of pointer.
336 unsigned IndexSize = PointerMemSize;
337
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000338 // Preferred alignment.
339 unsigned PointerPrefAlign = PointerABIAlign;
340 if (!Rest.empty()) {
Alex Zinenko874aef82020-08-17 13:34:07 +0200341 if (Error Err = split(Rest, ':', Split))
342 return Err;
343 if (Error Err = getIntInBytes(Tok, PointerPrefAlign))
344 return Err;
Owen Anderson040f2f82015-03-02 06:33:51 +0000345 if (!isPowerOf2_64(PointerPrefAlign))
Alex Zinenko874aef82020-08-17 13:34:07 +0200346 return reportError(
347 "Pointer preferred alignment must be a power of 2");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000348
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000349 // Now read the index. It is the second optional parameter here.
350 if (!Rest.empty()) {
Alex Zinenko874aef82020-08-17 13:34:07 +0200351 if (Error Err = split(Rest, ':', Split))
352 return Err;
353 if (Error Err = getIntInBytes(Tok, IndexSize))
354 return Err;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000355 if (!IndexSize)
Alex Zinenko874aef82020-08-17 13:34:07 +0200356 return reportError("Invalid index size of 0 bytes");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000357 }
358 }
Alex Zinenko874aef82020-08-17 13:34:07 +0200359 if (Error Err = setPointerAlignment(
360 AddrSpace, assumeAligned(PointerABIAlign),
361 assumeAligned(PointerPrefAlign), PointerMemSize, IndexSize))
362 return Err;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000363 break;
364 }
365 case 'i':
366 case 'v':
367 case 'f':
Rafael Espindola6994fdf2014-01-01 22:29:43 +0000368 case 'a': {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000369 AlignTypeEnum AlignType;
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000370 switch (Specifier) {
Craig Topper64a65ec2017-05-22 19:28:36 +0000371 default: llvm_unreachable("Unexpected specifier!");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000372 case 'i': AlignType = INTEGER_ALIGN; break;
373 case 'v': AlignType = VECTOR_ALIGN; break;
374 case 'f': AlignType = FLOAT_ALIGN; break;
375 case 'a': AlignType = AGGREGATE_ALIGN; break;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000376 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000377
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000378 // Bit size.
Alex Zinenko874aef82020-08-17 13:34:07 +0200379 unsigned Size = 0;
380 if (!Tok.empty())
381 if (Error Err = getInt(Tok, Size))
382 return Err;
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000383
David Majnemer5330c692014-12-10 01:17:08 +0000384 if (AlignType == AGGREGATE_ALIGN && Size != 0)
Alex Zinenko874aef82020-08-17 13:34:07 +0200385 return reportError(
David Majnemer5330c692014-12-10 01:17:08 +0000386 "Sized aggregate specification in datalayout string");
Rafael Espindolaabdd7262014-01-06 21:40:24 +0000387
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000388 // ABI alignment.
David Majnemer612f3122014-12-10 02:36:41 +0000389 if (Rest.empty())
Alex Zinenko874aef82020-08-17 13:34:07 +0200390 return reportError(
David Majnemer612f3122014-12-10 02:36:41 +0000391 "Missing alignment specification in datalayout string");
Alex Zinenko874aef82020-08-17 13:34:07 +0200392 if (Error Err = split(Rest, ':', Split))
393 return Err;
394 unsigned ABIAlign;
395 if (Error Err = getIntInBytes(Tok, ABIAlign))
396 return Err;
Owen Andersonab1c7a72015-03-02 09:34:59 +0000397 if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
Alex Zinenko874aef82020-08-17 13:34:07 +0200398 return reportError(
Owen Andersonab1c7a72015-03-02 09:34:59 +0000399 "ABI alignment specification must be >0 for non-aggregate types");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000400
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000401 if (!isUInt<16>(ABIAlign))
Alex Zinenko874aef82020-08-17 13:34:07 +0200402 return reportError("Invalid ABI alignment, must be a 16bit integer");
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000403 if (ABIAlign != 0 && !isPowerOf2_64(ABIAlign))
Alex Zinenko874aef82020-08-17 13:34:07 +0200404 return reportError("Invalid ABI alignment, must be a power of 2");
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000405
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000406 // Preferred alignment.
407 unsigned PrefAlign = ABIAlign;
408 if (!Rest.empty()) {
Alex Zinenko874aef82020-08-17 13:34:07 +0200409 if (Error Err = split(Rest, ':', Split))
410 return Err;
411 if (Error Err = getIntInBytes(Tok, PrefAlign))
412 return Err;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000413 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000414
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000415 if (!isUInt<16>(PrefAlign))
Alex Zinenko874aef82020-08-17 13:34:07 +0200416 return reportError(
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000417 "Invalid preferred alignment, must be a 16bit integer");
418 if (PrefAlign != 0 && !isPowerOf2_64(PrefAlign))
Alex Zinenko874aef82020-08-17 13:34:07 +0200419 return reportError("Invalid preferred alignment, must be a power of 2");
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000420
Alex Zinenko874aef82020-08-17 13:34:07 +0200421 if (Error Err = setAlignment(AlignType, assumeAligned(ABIAlign),
422 assumeAligned(PrefAlign), Size))
423 return Err;
Micah Villmowb4faa152012-10-04 23:01:22 +0000424
Micah Villmowac34b5c2012-10-04 22:08:14 +0000425 break;
426 }
427 case 'n': // Native integer types.
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000428 while (true) {
Alex Zinenko874aef82020-08-17 13:34:07 +0200429 unsigned Width;
430 if (Error Err = getInt(Tok, Width))
431 return Err;
David Majnemer5330c692014-12-10 01:17:08 +0000432 if (Width == 0)
Alex Zinenko874aef82020-08-17 13:34:07 +0200433 return reportError(
David Majnemer5330c692014-12-10 01:17:08 +0000434 "Zero width native integer type in datalayout string");
Patrik Hägglund3eb16c52012-11-28 12:13:12 +0000435 LegalIntWidths.push_back(Width);
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000436 if (Rest.empty())
437 break;
Alex Zinenko874aef82020-08-17 13:34:07 +0200438 if (Error Err = split(Rest, ':', Split))
439 return Err;
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000440 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000441 break;
442 case 'S': { // Stack natural alignment.
Alex Zinenko874aef82020-08-17 13:34:07 +0200443 uint64_t Alignment;
444 if (Error Err = getIntInBytes(Tok, Alignment))
445 return Err;
Florian Hahnd8c3c172019-08-07 17:20:55 +0000446 if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
Alex Zinenko874aef82020-08-17 13:34:07 +0200447 return reportError("Alignment is neither 0 nor a power of 2");
Florian Hahnd8c3c172019-08-07 17:20:55 +0000448 StackNaturalAlign = MaybeAlign(Alignment);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000449 break;
450 }
Michael Platings308e82e2019-03-08 10:44:06 +0000451 case 'F': {
452 switch (Tok.front()) {
453 case 'i':
454 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
455 break;
456 case 'n':
457 TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
458 break;
459 default:
Alex Zinenko874aef82020-08-17 13:34:07 +0200460 return reportError("Unknown function pointer alignment type in "
Michael Platings308e82e2019-03-08 10:44:06 +0000461 "datalayout string");
462 }
463 Tok = Tok.substr(1);
Alex Zinenko874aef82020-08-17 13:34:07 +0200464 uint64_t Alignment;
465 if (Error Err = getIntInBytes(Tok, Alignment))
466 return Err;
Florian Hahnd8c3c172019-08-07 17:20:55 +0000467 if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
Alex Zinenko874aef82020-08-17 13:34:07 +0200468 return reportError("Alignment is neither 0 nor a power of 2");
Florian Hahnd8c3c172019-08-07 17:20:55 +0000469 FunctionPtrAlign = MaybeAlign(Alignment);
Michael Platings308e82e2019-03-08 10:44:06 +0000470 break;
471 }
Dylan McKayced2fe62018-02-19 09:56:22 +0000472 case 'P': { // Function address space.
Alex Zinenko874aef82020-08-17 13:34:07 +0200473 if (Error Err = getAddrSpace(Tok, ProgramAddrSpace))
474 return Err;
Dylan McKayced2fe62018-02-19 09:56:22 +0000475 break;
476 }
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000477 case 'A': { // Default stack/alloca address space.
Alex Zinenko874aef82020-08-17 13:34:07 +0200478 if (Error Err = getAddrSpace(Tok, AllocaAddrSpace))
479 return Err;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000480 break;
481 }
Rafael Espindola58873562014-01-03 19:21:54 +0000482 case 'm':
David Majnemer612f3122014-12-10 02:36:41 +0000483 if (!Tok.empty())
Alex Zinenko874aef82020-08-17 13:34:07 +0200484 return reportError("Unexpected trailing characters after mangling "
485 "specifier in datalayout string");
David Majnemer612f3122014-12-10 02:36:41 +0000486 if (Rest.empty())
Alex Zinenko874aef82020-08-17 13:34:07 +0200487 return reportError("Expected mangling specifier in datalayout string");
David Majnemer612f3122014-12-10 02:36:41 +0000488 if (Rest.size() > 1)
Alex Zinenko874aef82020-08-17 13:34:07 +0200489 return reportError("Unknown mangling specifier in datalayout string");
Rafael Espindola58873562014-01-03 19:21:54 +0000490 switch(Rest[0]) {
491 default:
Alex Zinenko874aef82020-08-17 13:34:07 +0200492 return reportError("Unknown mangling in datalayout string");
Rafael Espindola58873562014-01-03 19:21:54 +0000493 case 'e':
494 ManglingMode = MM_ELF;
495 break;
496 case 'o':
497 ManglingMode = MM_MachO;
498 break;
499 case 'm':
500 ManglingMode = MM_Mips;
501 break;
Rafael Espindolaaf77e122014-01-10 13:42:12 +0000502 case 'w':
David Majnemer7db449a2015-03-17 23:54:51 +0000503 ManglingMode = MM_WinCOFF;
504 break;
505 case 'x':
506 ManglingMode = MM_WinCOFFX86;
Rafael Espindola58873562014-01-03 19:21:54 +0000507 break;
jasonliu572dde52020-07-02 22:45:59 +0000508 case 'a':
509 ManglingMode = MM_XCOFF;
510 break;
Rafael Espindola58873562014-01-03 19:21:54 +0000511 }
512 break;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000513 default:
Alex Zinenko874aef82020-08-17 13:34:07 +0200514 return reportError("Unknown specifier in datalayout string");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000515 break;
516 }
517 }
Alex Zinenko874aef82020-08-17 13:34:07 +0200518
519 return Error::success();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000520}
521
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000522DataLayout::DataLayout(const Module *M) {
Rafael Espindolac435adc2014-09-10 21:27:43 +0000523 init(M);
524}
525
Mehdi Amini46a43552015-03-04 18:43:29 +0000526void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000527
Rafael Espindolaae593f12014-02-26 17:02:08 +0000528bool DataLayout::operator==(const DataLayout &Other) const {
Chandler Carruthf67321c2014-10-20 10:41:29 +0000529 bool Ret = BigEndian == Other.BigEndian &&
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000530 AllocaAddrSpace == Other.AllocaAddrSpace &&
Rafael Espindolaae593f12014-02-26 17:02:08 +0000531 StackNaturalAlign == Other.StackNaturalAlign &&
Dylan McKayced2fe62018-02-19 09:56:22 +0000532 ProgramAddrSpace == Other.ProgramAddrSpace &&
Michael Platings308e82e2019-03-08 10:44:06 +0000533 FunctionPtrAlign == Other.FunctionPtrAlign &&
534 TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
Rafael Espindolaae593f12014-02-26 17:02:08 +0000535 ManglingMode == Other.ManglingMode &&
536 LegalIntWidths == Other.LegalIntWidths &&
Rafael Espindola89992b02014-04-22 17:47:03 +0000537 Alignments == Other.Alignments && Pointers == Other.Pointers;
Mehdi Amini46a43552015-03-04 18:43:29 +0000538 // Note: getStringRepresentation() might differs, it is not canonicalized
Rafael Espindolaae593f12014-02-26 17:02:08 +0000539 return Ret;
540}
541
Craig Topper490889c2017-03-23 06:15:56 +0000542DataLayout::AlignmentsTy::iterator
543DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
544 uint32_t BitWidth) {
545 auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
Fangrui Song78ee2fb2019-06-30 11:19:56 +0000546 return partition_point(Alignments, [=](const LayoutAlignElem &E) {
547 return std::make_pair(E.AlignType, E.TypeBitWidth) < Pair;
Fangrui Songdc8de602019-06-21 05:40:31 +0000548 });
Craig Topper490889c2017-03-23 06:15:56 +0000549}
550
Alex Zinenko874aef82020-08-17 13:34:07 +0200551Error DataLayout::setAlignment(AlignTypeEnum align_type, Align abi_align,
552 Align pref_align, uint32_t bit_width) {
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000553 // AlignmentsTy::ABIAlign and AlignmentsTy::PrefAlign were once stored as
554 // uint16_t, it is unclear if there are requirements for alignment to be less
555 // than 2^16 other than storage. In the meantime we leave the restriction as
556 // an assert. See D67400 for context.
557 assert(Log2(abi_align) < 16 && Log2(pref_align) < 16 && "Alignment too big");
David Majnemer1b9fc3a2015-02-16 05:41:53 +0000558 if (!isUInt<24>(bit_width))
Alex Zinenko874aef82020-08-17 13:34:07 +0200559 return reportError("Invalid bit width, must be a 24bit integer");
David Majnemer1b9fc3a2015-02-16 05:41:53 +0000560 if (pref_align < abi_align)
Alex Zinenko874aef82020-08-17 13:34:07 +0200561 return reportError(
David Majnemer1b9fc3a2015-02-16 05:41:53 +0000562 "Preferred alignment cannot be less than the ABI alignment");
563
Craig Topper490889c2017-03-23 06:15:56 +0000564 AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
565 if (I != Alignments.end() &&
566 I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
567 // Update the abi, preferred alignments.
568 I->ABIAlign = abi_align;
569 I->PrefAlign = pref_align;
570 } else {
571 // Insert before I to keep the vector sorted.
572 Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
573 pref_align, bit_width));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000574 }
Alex Zinenko874aef82020-08-17 13:34:07 +0200575 return Error::success();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000576}
577
Rafael Espindola667fcb82014-02-26 16:58:35 +0000578DataLayout::PointersTy::iterator
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000579DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
Rafael Espindola667fcb82014-02-26 16:58:35 +0000580 return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000581 [](const PointerAlignElem &A, uint32_t AddressSpace) {
582 return A.AddressSpace < AddressSpace;
583 });
Rafael Espindola667fcb82014-02-26 16:58:35 +0000584}
585
Alex Zinenko874aef82020-08-17 13:34:07 +0200586Error DataLayout::setPointerAlignment(uint32_t AddrSpace, Align ABIAlign,
587 Align PrefAlign, uint32_t TypeByteWidth,
588 uint32_t IndexWidth) {
David Majnemer4b042922015-02-16 05:41:55 +0000589 if (PrefAlign < ABIAlign)
Alex Zinenko874aef82020-08-17 13:34:07 +0200590 return reportError(
David Majnemer4b042922015-02-16 05:41:55 +0000591 "Preferred alignment cannot be less than the ABI alignment");
592
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000593 PointersTy::iterator I = findPointerLowerBound(AddrSpace);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000594 if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
595 Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000596 TypeByteWidth, IndexWidth));
Micah Villmow89021e42012-10-09 16:06:12 +0000597 } else {
Rafael Espindola667fcb82014-02-26 16:58:35 +0000598 I->ABIAlign = ABIAlign;
599 I->PrefAlign = PrefAlign;
600 I->TypeByteWidth = TypeByteWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000601 I->IndexWidth = IndexWidth;
Micah Villmow89021e42012-10-09 16:06:12 +0000602 }
Alex Zinenko874aef82020-08-17 13:34:07 +0200603 return Error::success();
Micah Villmow89021e42012-10-09 16:06:12 +0000604}
605
Micah Villmowac34b5c2012-10-04 22:08:14 +0000606/// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
Micah Villmowb4faa152012-10-04 23:01:22 +0000607/// preferred if ABIInfo = false) the layout wants for the specified datatype.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000608Align DataLayout::getAlignmentInfo(AlignTypeEnum AlignType, uint32_t BitWidth,
609 bool ABIInfo, Type *Ty) const {
Craig Topper490889c2017-03-23 06:15:56 +0000610 AlignmentsTy::const_iterator I = findAlignmentLowerBound(AlignType, BitWidth);
611 // See if we found an exact match. Of if we are looking for an integer type,
612 // but don't have an exact match take the next largest integer. This is where
613 // the lower_bound will point to when it fails an exact match.
614 if (I != Alignments.end() && I->AlignType == (unsigned)AlignType &&
615 (I->TypeBitWidth == BitWidth || AlignType == INTEGER_ALIGN))
Guillaume Chatelet046a16b2019-09-23 08:38:36 +0000616 return ABIInfo ? I->ABIAlign : I->PrefAlign;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000617
Craig Topper490889c2017-03-23 06:15:56 +0000618 if (AlignType == INTEGER_ALIGN) {
619 // If we didn't have a larger value try the largest value we have.
620 if (I != Alignments.begin()) {
621 --I; // Go to the previous entry and see if its an integer.
622 if (I->AlignType == INTEGER_ALIGN)
Guillaume Chatelet046a16b2019-09-23 08:38:36 +0000623 return ABIInfo ? I->ABIAlign : I->PrefAlign;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000624 }
Craig Topper490889c2017-03-23 06:15:56 +0000625 } else if (AlignType == VECTOR_ALIGN) {
626 // By default, use natural alignment for vector types. This is consistent
627 // with what clang and llvm-gcc do.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000628 unsigned Alignment =
629 getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
David Sherwooda400aa52020-05-05 16:47:31 +0100630 // We're only calculating a natural alignment, so it doesn't have to be
631 // based on the full size for scalable vectors. Using the minimum element
632 // count should be enough here.
David Sherwoodf4257c52020-08-14 12:15:59 +0100633 Alignment *= cast<VectorType>(Ty)->getElementCount().getKnownMinValue();
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000634 Alignment = PowerOf2Ceil(Alignment);
635 return Align(Alignment);
Craig Topper490889c2017-03-23 06:15:56 +0000636 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000637
Owen Anderson7e621e92015-03-08 21:53:59 +0000638 // If we still couldn't find a reasonable default alignment, fall back
639 // to a simple heuristic that the alignment is the first power of two
640 // greater-or-equal to the store size of the type. This is a reasonable
641 // approximation of reality, and if the user wanted something less
642 // less conservative, they should have specified it explicitly in the data
643 // layout.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000644 unsigned Alignment = getTypeStoreSize(Ty);
645 Alignment = PowerOf2Ceil(Alignment);
646 return Align(Alignment);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000647}
648
649namespace {
650
651class StructLayoutMap {
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000652 using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000653 LayoutInfoTy LayoutInfo;
654
655public:
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000656 ~StructLayoutMap() {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000657 // Remove any layouts.
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000658 for (const auto &I : LayoutInfo) {
659 StructLayout *Value = I.second;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000660 Value->~StructLayout();
661 free(Value);
662 }
663 }
664
Pete Cooper0ae73932015-07-27 17:15:28 +0000665 StructLayout *&operator[](StructType *STy) {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000666 return LayoutInfo[STy];
667 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000668};
669
670} // end anonymous namespace
671
Rafael Espindola248ac132014-02-25 22:23:04 +0000672void DataLayout::clear() {
673 LegalIntWidths.clear();
674 Alignments.clear();
675 Pointers.clear();
676 delete static_cast<StructLayoutMap *>(LayoutMap);
Craig Topperc6207612014-04-09 06:08:46 +0000677 LayoutMap = nullptr;
Rafael Espindola248ac132014-02-25 22:23:04 +0000678}
679
Micah Villmowb4faa152012-10-04 23:01:22 +0000680DataLayout::~DataLayout() {
Rafael Espindola248ac132014-02-25 22:23:04 +0000681 clear();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000682}
683
Pete Cooper0ae73932015-07-27 17:15:28 +0000684const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000685 if (!LayoutMap)
686 LayoutMap = new StructLayoutMap();
687
688 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
689 StructLayout *&SL = (*STM)[Ty];
690 if (SL) return SL;
691
692 // Otherwise, create the struct layout. Because it is variable length, we
693 // malloc it, then use placement new.
694 int NumElts = Ty->getNumElements();
Serge Pavlov15681ad2018-06-09 05:19:45 +0000695 StructLayout *L = (StructLayout *)
696 safe_malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000697
698 // Set SL before calling StructLayout's ctor. The ctor could cause other
699 // entries to be added to TheMap, invalidating our reference.
700 SL = L;
701
702 new (L) StructLayout(Ty, *this);
703
704 return L;
705}
706
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000707Align DataLayout::getPointerABIAlignment(unsigned AS) const {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000708 PointersTy::const_iterator I = findPointerLowerBound(AS);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000709 if (I == Pointers.end() || I->AddressSpace != AS) {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000710 I = findPointerLowerBound(0);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000711 assert(I->AddressSpace == 0);
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000712 }
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000713 return I->ABIAlign;
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000714}
715
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000716Align DataLayout::getPointerPrefAlignment(unsigned AS) const {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000717 PointersTy::const_iterator I = findPointerLowerBound(AS);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000718 if (I == Pointers.end() || I->AddressSpace != AS) {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000719 I = findPointerLowerBound(0);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000720 assert(I->AddressSpace == 0);
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000721 }
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000722 return I->PrefAlign;
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000723}
724
725unsigned DataLayout::getPointerSize(unsigned AS) const {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000726 PointersTy::const_iterator I = findPointerLowerBound(AS);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000727 if (I == Pointers.end() || I->AddressSpace != AS) {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000728 I = findPointerLowerBound(0);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000729 assert(I->AddressSpace == 0);
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000730 }
Rafael Espindola667fcb82014-02-26 16:58:35 +0000731 return I->TypeByteWidth;
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000732}
733
Hal Finkel4f238142019-01-02 16:28:09 +0000734unsigned DataLayout::getMaxPointerSize() const {
735 unsigned MaxPointerSize = 0;
736 for (auto &P : Pointers)
737 MaxPointerSize = std::max(MaxPointerSize, P.TypeByteWidth);
738
739 return MaxPointerSize;
740}
741
Pete Cooper0ae73932015-07-27 17:15:28 +0000742unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
Matt Arsenault6f4be902013-07-26 17:37:20 +0000743 assert(Ty->isPtrOrPtrVectorTy() &&
744 "This should only be called with a pointer or pointer vector type");
Craig Topper5b4f5b02017-04-17 18:22:36 +0000745 Ty = Ty->getScalarType();
746 return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
Matt Arsenault6f4be902013-07-26 17:37:20 +0000747}
Micah Villmowac34b5c2012-10-04 22:08:14 +0000748
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000749unsigned DataLayout::getIndexSize(unsigned AS) const {
750 PointersTy::const_iterator I = findPointerLowerBound(AS);
751 if (I == Pointers.end() || I->AddressSpace != AS) {
752 I = findPointerLowerBound(0);
753 assert(I->AddressSpace == 0);
754 }
755 return I->IndexWidth;
756}
757
758unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const {
759 assert(Ty->isPtrOrPtrVectorTy() &&
760 "This should only be called with a pointer or pointer vector type");
761 Ty = Ty->getScalarType();
762 return getIndexSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
763}
764
Micah Villmowac34b5c2012-10-04 22:08:14 +0000765/*!
766 \param abi_or_pref Flag that determines which alignment is returned. true
767 returns the ABI alignment, false returns the preferred alignment.
768 \param Ty The underlying type for which alignment is determined.
769
770 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
771 == false) for the requested type \a Ty.
772 */
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000773Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
Craig Topperff6922a2017-04-19 00:31:38 +0000774 AlignTypeEnum AlignType;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000775
776 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
777 switch (Ty->getTypeID()) {
778 // Early escape for the non-numeric types.
779 case Type::LabelTyID:
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000780 return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
Micah Villmow89021e42012-10-09 16:06:12 +0000781 case Type::PointerTyID: {
Matt Arsenaultc1728972014-09-18 22:28:56 +0000782 unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000783 return abi_or_pref ? getPointerABIAlignment(AS)
784 : getPointerPrefAlignment(AS);
Micah Villmow89021e42012-10-09 16:06:12 +0000785 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000786 case Type::ArrayTyID:
787 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
788
789 case Type::StructTyID: {
790 // Packed structure types always have an ABI alignment of one.
791 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
Guillaume Chatelet805c1572020-01-21 15:00:04 +0100792 return Align(1);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000793
794 // Get the layout annotation... which is lazily created on demand.
795 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000796 const Align Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000797 return std::max(Align, Layout->getAlignment());
798 }
799 case Type::IntegerTyID:
Micah Villmowac34b5c2012-10-04 22:08:14 +0000800 AlignType = INTEGER_ALIGN;
801 break;
802 case Type::HalfTyID:
Ties Stuij8c24f332020-03-31 23:49:38 +0100803 case Type::BFloatTyID:
Micah Villmowac34b5c2012-10-04 22:08:14 +0000804 case Type::FloatTyID:
805 case Type::DoubleTyID:
806 // PPC_FP128TyID and FP128TyID have different data contents, but the
807 // same size and alignment, so they look the same here.
808 case Type::PPC_FP128TyID:
809 case Type::FP128TyID:
810 case Type::X86_FP80TyID:
811 AlignType = FLOAT_ALIGN;
812 break;
813 case Type::X86_MMXTyID:
Christopher Tetreault2dea3f12020-04-22 08:02:02 -0700814 case Type::FixedVectorTyID:
815 case Type::ScalableVectorTyID:
Micah Villmowac34b5c2012-10-04 22:08:14 +0000816 AlignType = VECTOR_ALIGN;
817 break;
818 default:
819 llvm_unreachable("Bad type for getAlignment!!!");
820 }
821
Graham Hunterb3025612019-10-08 12:53:54 +0000822 // If we're dealing with a scalable vector, we just need the known minimum
823 // size for determining alignment. If not, we'll get the exact size.
824 return getAlignmentInfo(AlignType, getTypeSizeInBits(Ty).getKnownMinSize(),
825 abi_or_pref, Ty);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000826}
827
Guillaume Chatelet59f95222020-01-23 16:18:34 +0100828/// TODO: Remove this function once the transition to Align is over.
Pete Cooper0ae73932015-07-27 17:15:28 +0000829unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
Guillaume Chatelet59f95222020-01-23 16:18:34 +0100830 return getABITypeAlign(Ty).value();
831}
832
833Align DataLayout::getABITypeAlign(Type *Ty) const {
834 return getAlignment(Ty, true);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000835}
836
837/// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
838/// an integer type of the specified bitwidth.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000839Align DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000840 return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, nullptr);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000841}
842
Guillaume Chatelet59f95222020-01-23 16:18:34 +0100843/// TODO: Remove this function once the transition to Align is over.
Pete Cooper0ae73932015-07-27 17:15:28 +0000844unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
Guillaume Chatelet59f95222020-01-23 16:18:34 +0100845 return getPrefTypeAlign(Ty).value();
846}
847
848Align DataLayout::getPrefTypeAlign(Type *Ty) const {
849 return getAlignment(Ty, false);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000850}
851
Micah Villmow89021e42012-10-09 16:06:12 +0000852IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
853 unsigned AddressSpace) const {
Nicola Zaghen97572772019-12-13 09:55:45 +0000854 return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000855}
856
Pete Cooper0ae73932015-07-27 17:15:28 +0000857Type *DataLayout::getIntPtrType(Type *Ty) const {
Chandler Carruth7ec50852012-11-01 08:07:29 +0000858 assert(Ty->isPtrOrPtrVectorTy() &&
859 "Expected a pointer or pointer vector type.");
Nicola Zaghen97572772019-12-13 09:55:45 +0000860 unsigned NumBits = getPointerTypeSizeInBits(Ty);
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000861 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
Pete Cooper0ae73932015-07-27 17:15:28 +0000862 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
David Sherwood7a834a02020-06-22 14:09:34 +0100863 return VectorType::get(IntTy, VecTy);
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000864 return IntTy;
Micah Villmow12d91272012-10-24 15:52:52 +0000865}
866
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000867Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000868 for (unsigned LegalIntWidth : LegalIntWidths)
869 if (Width <= LegalIntWidth)
870 return Type::getIntNTy(C, LegalIntWidth);
Craig Topperc6207612014-04-09 06:08:46 +0000871 return nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000872}
873
Jun Bum Limbe11bdc2016-05-13 18:38:35 +0000874unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000875 auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
876 return Max != LegalIntWidths.end() ? *Max : 0;
Matt Arsenault899f7d22013-09-16 22:43:16 +0000877}
878
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000879Type *DataLayout::getIndexType(Type *Ty) const {
880 assert(Ty->isPtrOrPtrVectorTy() &&
881 "Expected a pointer or pointer vector type.");
882 unsigned NumBits = getIndexTypeSizeInBits(Ty);
883 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
884 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
Eli Friedman90ad7862020-06-17 16:35:35 -0700885 return VectorType::get(IntTy, VecTy);
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000886 return IntTy;
887}
888
David Majnemer17bdf442016-07-13 03:42:38 +0000889int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy,
890 ArrayRef<Value *> Indices) const {
891 int64_t Result = 0;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000892
893 generic_gep_type_iterator<Value* const*>
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000894 GTI = gep_type_begin(ElemTy, Indices),
895 GTE = gep_type_end(ElemTy, Indices);
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000896 for (; GTI != GTE; ++GTI) {
897 Value *Idx = GTI.getOperand();
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000898 if (StructType *STy = GTI.getStructTypeOrNull()) {
Manuel Jacobcc13c2c2016-01-22 03:30:27 +0000899 assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000900 unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000901
902 // Get structure layout information...
903 const StructLayout *Layout = getStructLayout(STy);
904
905 // Add in the offset, as calculated by the structure layout info...
906 Result += Layout->getElementOffset(FieldNo);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000907 } else {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000908 // Get the array index and the size of each array element.
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000909 if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
David Majnemer17bdf442016-07-13 03:42:38 +0000910 Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
Micah Villmowac34b5c2012-10-04 22:08:14 +0000911 }
912 }
913
914 return Result;
915}
916
Guillaume Chatelet368a5e32020-06-29 11:24:36 +0000917/// getPreferredAlign - Return the preferred alignment of the specified global.
918/// This includes an explicitly requested alignment (if the global has one).
919Align DataLayout::getPreferredAlign(const GlobalVariable *GV) const {
920 MaybeAlign GVAlignment = GV->getAlign();
Eli Friedman37696392018-08-29 23:46:26 +0000921 // If a section is specified, always precisely honor explicit alignment,
922 // so we don't insert padding into a section we don't control.
923 if (GVAlignment && GV->hasSection())
Guillaume Chatelet368a5e32020-06-29 11:24:36 +0000924 return *GVAlignment;
Eli Friedman37696392018-08-29 23:46:26 +0000925
926 // If no explicit alignment is specified, compute the alignment based on
927 // the IR type. If an alignment is specified, increase it to match the ABI
928 // alignment of the IR type.
929 //
930 // FIXME: Not sure it makes sense to use the alignment of the type if
931 // there's already an explicit alignment specification.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000932 Type *ElemType = GV->getValueType();
Guillaume Chatelet368a5e32020-06-29 11:24:36 +0000933 Align Alignment = getPrefTypeAlign(ElemType);
934 if (GVAlignment) {
935 if (*GVAlignment >= Alignment)
936 Alignment = *GVAlignment;
937 else
938 Alignment = std::max(*GVAlignment, getABITypeAlign(ElemType));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000939 }
940
Eli Friedman37696392018-08-29 23:46:26 +0000941 // If no explicit alignment is specified, and the global is large, increase
942 // the alignment to 16.
943 // FIXME: Why 16, specifically?
Guillaume Chatelet368a5e32020-06-29 11:24:36 +0000944 if (GV->hasInitializer() && !GVAlignment) {
945 if (Alignment < Align(16)) {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000946 // If the global is not external, see if it is large. If so, give it a
947 // larger alignment.
948 if (getTypeSizeInBits(ElemType) > 128)
Guillaume Chatelet368a5e32020-06-29 11:24:36 +0000949 Alignment = Align(16); // 16-byte alignment.
Micah Villmowac34b5c2012-10-04 22:08:14 +0000950 }
951 }
952 return Alignment;
953}