blob: 94d78fef3b1b745ab2b46ef42fd688249f9a2452 [file] [log] [blame]
Daniel Dunbar23ee4b72010-03-31 00:11:27 +00001//===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder ----*- C++ -*-===//
Anders Carlsson307846f2009-07-23 03:17:50 +00002//
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//
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000010// Builder implementation for CGRecordLayout objects.
Anders Carlsson307846f2009-07-23 03:17:50 +000011//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000014#include "CGRecordLayout.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGCXXABI.h"
16#include "CodeGenTypes.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Attr.h"
Anders Carlsson4131f002010-11-24 22:50:27 +000019#include "clang/AST/CXXInheritance.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000020#include "clang/AST/DeclCXX.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/RecordLayout.h"
Daniel Dunbard3f3d932011-06-21 18:54:46 +000023#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar2ba67442010-04-21 19:10:49 +000027#include "llvm/Support/Debug.h"
Warren Huntfb00c882014-02-21 23:49:50 +000028#include "llvm/Support/MathExtras.h"
Daniel Dunbarb97bff92010-04-12 18:14:18 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000030using namespace clang;
31using namespace CodeGen;
32
John McCallbcd38212010-11-30 23:17:27 +000033namespace {
Warren Huntfb00c882014-02-21 23:49:50 +000034/// The CGRecordLowering is responsible for lowering an ASTRecordLayout to an
35/// llvm::Type. Some of the lowering is straightforward, some is not. Here we
36/// detail some of the complexities and weirdnesses here.
37/// * LLVM does not have unions - Unions can, in theory be represented by any
38/// llvm::Type with correct size. We choose a field via a specific heuristic
39/// and add padding if necessary.
40/// * LLVM does not have bitfields - Bitfields are collected into contiguous
41/// runs and allocated as a single storage type for the run. ASTRecordLayout
42/// contains enough information to determine where the runs break. Microsoft
43/// and Itanium follow different rules and use different codepaths.
44/// * It is desired that, when possible, bitfields use the appropriate iN type
45/// when lowered to llvm types. For example unsigned x : 24 gets lowered to
46/// i24. This isn't always possible because i24 has storage size of 32 bit
47/// and if it is possible to use that extra byte of padding we must use
48/// [i8 x 3] instead of i24. The function clipTailPadding does this.
49/// C++ examples that require clipping:
50/// struct { int a : 24; char b; }; // a must be clipped, b goes at offset 3
51/// struct A { int a : 24; }; // a must be clipped because a struct like B
52// could exist: struct B : A { char b; }; // b goes at offset 3
53/// * Clang ignores 0 sized bitfields and 0 sized bases but *not* zero sized
54/// fields. The existing asserts suggest that LLVM assumes that *every* field
55/// has an underlying storage type. Therefore empty structures containing
56/// zero sized subobjects such as empty records or zero sized arrays still get
57/// a zero sized (empty struct) storage type.
58/// * Clang reads the complete type rather than the base type when generating
59/// code to access fields. Bitfields in tail position with tail padding may
60/// be clipped in the base class but not the complete class (we may discover
61/// that the tail padding is not used in the complete class.) However,
62/// because LLVM reads from the complete type it can generate incorrect code
63/// if we do not clip the tail padding off of the bitfield in the complete
64/// layout. This introduces a somewhat awkward extra unnecessary clip stage.
65/// The location of the clip is stored internally as a sentinal of type
66/// SCISSOR. If LLVM were updated to read base types (which it probably
67/// should because locations of things such as VBases are bogus in the llvm
68/// type anyway) then we could eliminate the SCISSOR.
69/// * Itanium allows nearly empty primary virtual bases. These bases don't get
70/// get their own storage because they're laid out as part of another base
71/// or at the beginning of the structure. Determining if a VBase actually
72/// gets storage awkwardly involves a walk of all bases.
73/// * VFPtrs and VBPtrs do *not* make a record NotZeroInitializable.
74struct CGRecordLowering {
75 // MemberInfo is a helper structure that contains information about a record
76 // member. In additional to the standard member types, there exists a
77 // sentinal member type that ensures correct rounding.
78 struct MemberInfo {
79 CharUnits Offset;
80 enum InfoKind { VFPtr, VBPtr, Field, Base, VBase, Scissor } Kind;
81 llvm::Type *Data;
82 union {
83 const FieldDecl *FD;
84 const CXXRecordDecl *RD;
85 };
86 MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
87 const FieldDecl *FD = 0)
88 : Offset(Offset), Kind(Kind), Data(Data), FD(FD) {}
89 MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
90 const CXXRecordDecl *RD)
91 : Offset(Offset), Kind(Kind), Data(Data), RD(RD) {}
92 // MemberInfos are sorted so we define a < operator.
93 bool operator <(const MemberInfo& a) const { return Offset < a.Offset; }
94 };
95 // The constructor.
96 CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D);
97 // Short helper routines.
98 /// \brief Constructs a MemberInfo instance from an offset and llvm::Type *.
99 MemberInfo StorageInfo(CharUnits Offset, llvm::Type *Data) {
100 return MemberInfo(Offset, MemberInfo::Field, Data);
101 }
102 bool useMSABI() {
103 return Context.getTargetInfo().getCXXABI().isMicrosoft() ||
104 D->isMsStruct(Context);
105 }
106 /// \brief Wraps llvm::Type::getIntNTy with some implicit arguments.
107 llvm::Type *getIntNType(uint64_t NumBits) {
108 return llvm::Type::getIntNTy(Types.getLLVMContext(),
109 (unsigned)llvm::RoundUpToAlignment(NumBits, 8));
110 }
111 /// \brief Gets an llvm type of size NumBytes and alignment 1.
David Majnemer7a726012014-02-22 00:41:07 +0000112 llvm::Type *getByteArrayType(CharUnits NumBytes) {
Warren Huntfb00c882014-02-21 23:49:50 +0000113 assert(!NumBytes.isZero() && "Empty byte arrays aren't allowed.");
114 llvm::Type *Type = llvm::Type::getInt8Ty(Types.getLLVMContext());
115 return NumBytes == CharUnits::One() ? Type :
116 (llvm::Type *)llvm::ArrayType::get(Type, NumBytes.getQuantity());
117 }
118 /// \brief Gets the storage type for a field decl and handles storage
119 /// for itanium bitfields that are smaller than their declared type.
120 llvm::Type *getStorageType(const FieldDecl *FD) {
121 llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
122 return useMSABI() || !FD->isBitField() ? Type :
123 getIntNType(std::min(FD->getBitWidthValue(Context),
124 (unsigned)Context.toBits(getSize(Type))));
125 }
126 /// \brief Gets the llvm Basesubobject type from a CXXRecordDecl.
127 llvm::Type *getStorageType(const CXXRecordDecl *RD) {
128 return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
129 }
130 CharUnits bitsToCharUnits(uint64_t BitOffset) {
131 return Context.toCharUnitsFromBits(BitOffset);
132 }
133 CharUnits getSize(llvm::Type *Type) {
134 return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
135 }
136 CharUnits getAlignment(llvm::Type *Type) {
137 return CharUnits::fromQuantity(DataLayout.getABITypeAlignment(Type));
138 }
139 bool isZeroInitializable(const FieldDecl *FD) {
140 const Type *Type = FD->getType()->getBaseElementTypeUnsafe();
141 if (const MemberPointerType *MPT = Type->getAs<MemberPointerType>())
142 return Types.getCXXABI().isZeroInitializable(MPT);
143 if (const RecordType *RT = Type->getAs<RecordType>())
144 return isZeroInitializable(RT->getDecl());
145 return true;
146 }
147 bool isZeroInitializable(const RecordDecl *RD) {
148 return Types.getCGRecordLayout(RD).isZeroInitializable();
149 }
150 void appendPaddingBytes(CharUnits Size) {
151 if (!Size.isZero())
152 FieldTypes.push_back(getByteArrayType(Size));
153 }
154 uint64_t getFieldBitOffset(const FieldDecl *FD) {
155 return Layout.getFieldOffset(FD->getFieldIndex());
156 }
157 // Layout routines.
158 void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
159 llvm::Type *StorageType);
160 /// \brief Lowers an ASTRecordLayout to a llvm type.
161 void lower(bool NonVirtualBaseType);
162 void lowerUnion();
163 void accumulateFields();
164 void accumulateBitFields(RecordDecl::field_iterator Field,
165 RecordDecl::field_iterator FieldEnd);
166 void accumulateBases();
167 void accumulateVPtrs();
168 void accumulateVBases();
169 /// \brief Recursively searches all of the bases to find out if a vbase is
170 /// not the primary vbase of some base class.
171 bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
172 void calculateZeroInit();
173 /// \brief Lowers bitfield storage types to I8 arrays for bitfields with tail
174 /// padding that is or can potentially be used.
175 void clipTailPadding();
176 /// \brief Determines if we need a packed llvm struct.
177 void determinePacked();
178 /// \brief Inserts padding everwhere it's needed.
179 void insertPadding();
180 /// \brief Fills out the structures that are ultimately consumed.
181 void fillOutputFields();
182 // Input memoization fields.
183 CodeGenTypes &Types;
184 const ASTContext &Context;
185 const RecordDecl *D;
186 const CXXRecordDecl *RD;
187 const ASTRecordLayout &Layout;
188 const llvm::DataLayout &DataLayout;
189 // Helpful intermediate data-structures.
190 std::vector<MemberInfo> Members;
191 // Output fields, consumed by CodeGenTypes::ComputeRecordLayout.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000192 SmallVector<llvm::Type *, 16> FieldTypes;
John McCall0217dfc22011-02-15 06:40:56 +0000193 llvm::DenseMap<const FieldDecl *, unsigned> Fields;
John McCall0217dfc22011-02-15 06:40:56 +0000194 llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
John McCall0217dfc22011-02-15 06:40:56 +0000195 llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
196 llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
Warren Huntfb00c882014-02-21 23:49:50 +0000197 bool IsZeroInitializable : 1;
198 bool IsZeroInitializableAsBase : 1;
199 bool Packed : 1;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000200private:
Warren Huntfb00c882014-02-21 23:49:50 +0000201 CGRecordLowering(const CGRecordLowering &) LLVM_DELETED_FUNCTION;
202 void operator =(const CGRecordLowering &) LLVM_DELETED_FUNCTION;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000203};
Warren Huntfb00c882014-02-21 23:49:50 +0000204} // namespace {
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000205
Warren Huntfb00c882014-02-21 23:49:50 +0000206CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D)
Warren Hunt0afa2d22014-02-22 00:22:15 +0000207 : Types(Types), Context(Types.getContext()), D(D),
208 RD(dyn_cast<CXXRecordDecl>(D)),
Warren Huntfb00c882014-02-21 23:49:50 +0000209 Layout(Types.getContext().getASTRecordLayout(D)),
Warren Hunt0afa2d22014-02-22 00:22:15 +0000210 DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
211 IsZeroInitializableAsBase(true), Packed(false) {}
Warren Huntfb00c882014-02-21 23:49:50 +0000212
213void CGRecordLowering::setBitFieldInfo(
214 const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
215 CGBitFieldInfo &Info = BitFields[FD];
216 Info.IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
217 Info.Offset = (unsigned)(getFieldBitOffset(FD) - Context.toBits(StartOffset));
218 Info.Size = FD->getBitWidthValue(Context);
219 Info.StorageSize = (unsigned)DataLayout.getTypeAllocSizeInBits(StorageType);
220 // Here we calculate the actual storage alignment of the bits. E.g if we've
221 // got an alignment >= 2 and the bitfield starts at offset 6 we've got an
222 // alignment of 2.
David Majnemere385d892014-02-25 01:20:15 +0000223 Info.StorageAlignment =
224 Layout.getAlignment().alignmentAtOffset(StartOffset).getQuantity();
Warren Huntfb00c882014-02-21 23:49:50 +0000225 if (Info.Size > Info.StorageSize)
226 Info.Size = Info.StorageSize;
227 // Reverse the bit offsets for big endian machines. Because we represent
228 // a bitfield as a single large integer load, we can imagine the bits
229 // counting from the most-significant-bit instead of the
230 // least-significant-bit.
231 if (DataLayout.isBigEndian())
232 Info.Offset = Info.StorageSize - (Info.Offset + Info.Size);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000233}
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000234
Warren Huntfb00c882014-02-21 23:49:50 +0000235void CGRecordLowering::lower(bool NVBaseType) {
236 // The lowering process implemented in this function takes a variety of
237 // carefully ordered phases.
238 // 1) Store all members (fields and bases) in a list and sort them by offset.
239 // 2) Add a 1-byte capstone member at the Size of the structure.
240 // 3) Clip bitfield storages members if their tail padding is or might be
241 // used by another field or base. The clipping process uses the capstone
242 // by treating it as another object that occurs after the record.
243 // 4) Determine if the llvm-struct requires packing. It's important that this
244 // phase occur after clipping, because clipping changes the llvm type.
245 // This phase reads the offset of the capstone when determining packedness
246 // and updates the alignment of the capstone to be equal of the alignment
247 // of the record after doing so.
248 // 5) Insert padding everywhere it is needed. This phase requires 'Packed' to
249 // have been computed and needs to know the alignment of the record in
250 // order to understand if explicit tail padding is needed.
251 // 6) Remove the capstone, we don't need it anymore.
252 // 7) Determine if this record can be zero-initialized. This phase could have
253 // been placed anywhere after phase 1.
254 // 8) Format the complete list of members in a way that can be consumed by
255 // CodeGenTypes::ComputeRecordLayout.
256 CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
257 if (D->isUnion())
258 return lowerUnion();
259 accumulateFields();
260 // RD implies C++.
261 if (RD) {
262 accumulateVPtrs();
263 accumulateBases();
264 if (Members.empty())
265 return appendPaddingBytes(Size);
266 if (!NVBaseType)
267 accumulateVBases();
268 }
269 std::stable_sort(Members.begin(), Members.end());
270 Members.push_back(StorageInfo(Size, getIntNType(8)));
271 clipTailPadding();
272 determinePacked();
273 insertPadding();
274 Members.pop_back();
275 calculateZeroInit();
276 fillOutputFields();
277}
Anders Carlsson28a5fa22009-08-08 19:38:24 +0000278
Warren Huntfb00c882014-02-21 23:49:50 +0000279void CGRecordLowering::lowerUnion() {
280 llvm::Type *StorageType = 0;
281 // Compute zero-initializable status.
282 if (!D->field_empty() && !isZeroInitializable(*D->field_begin()))
283 IsZeroInitializable = IsZeroInitializableAsBase = false;
284 // Iterate through the fields setting bitFieldInfo and the Fields array. Also
285 // locate the "most appropriate" storage type. The heuristic for finding the
286 // storage type isn't necessary, the first (non-0-length-bitfield) field's
287 // type would work fine and be simpler but would be differen than what we've
288 // been doing and cause lit tests to change.
289 for (RecordDecl::field_iterator Field = D->field_begin(),
290 FieldEnd = D->field_end();
291 Field != FieldEnd; ++Field) {
292 if (Field->isBitField()) {
293 // Skip 0 sized bitfields.
294 if (Field->getBitWidthValue(Context) == 0)
295 continue;
296 setBitFieldInfo(*Field, CharUnits::Zero(), getStorageType(*Field));
297 }
298 Fields[*Field] = 0;
299 llvm::Type *FieldType = getStorageType(*Field);
300 // Conditionally update our storage type if we've got a new "better" one.
301 if (!StorageType ||
302 getAlignment(FieldType) > getAlignment(StorageType) ||
303 (getAlignment(FieldType) == getAlignment(StorageType) &&
304 getSize(FieldType) > getSize(StorageType)))
305 StorageType = FieldType;
306 }
307 CharUnits LayoutSize = Layout.getSize();
308 // If we have no storage type just pad to the appropriate size and return.
309 if (!StorageType)
310 return appendPaddingBytes(LayoutSize);
311 // If our storage size was bigger than our required size (can happen in the
312 // case of packed bitfields on Itanium) then just use an I8 array.
313 if (LayoutSize < getSize(StorageType))
314 StorageType = getByteArrayType(LayoutSize);
315 FieldTypes.push_back(StorageType);
316 appendPaddingBytes(LayoutSize - getSize(StorageType));
317 // Set packed if we need it.
318 if (LayoutSize % getAlignment(StorageType))
319 Packed = true;
320}
321
322void CGRecordLowering::accumulateFields() {
323 for (RecordDecl::field_iterator Field = D->field_begin(),
324 FieldEnd = D->field_end();
325 Field != FieldEnd;)
326 if (Field->isBitField()) {
327 RecordDecl::field_iterator Start = Field;
328 // Iterate to gather the list of bitfields.
329 for (++Field; Field != FieldEnd && Field->isBitField(); ++Field);
330 accumulateBitFields(Start, Field);
331 } else {
332 Members.push_back(MemberInfo(
333 bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
334 getStorageType(*Field), *Field));
335 ++Field;
336 }
337}
338
339void
340CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
341 RecordDecl::field_iterator FieldEnd) {
342 // Run stores the first element of the current run of bitfields. FieldEnd is
343 // used as a special value to note that we don't have a current run. A
344 // bitfield run is a contiguous collection of bitfields that can be stored in
345 // the same storage block. Zero-sized bitfields and bitfields that would
346 // cross an alignment boundary break a run and start a new one.
347 RecordDecl::field_iterator Run = FieldEnd;
348 // Tail is the offset of the first bit off the end of the current run. It's
349 // used to determine if the ASTRecordLayout is treating these two bitfields as
350 // contiguous. StartBitOffset is offset of the beginning of the Run.
351 uint64_t StartBitOffset, Tail = 0;
352 if (useMSABI()) {
353 for (; Field != FieldEnd; ++Field) {
354 uint64_t BitOffset = getFieldBitOffset(*Field);
355 // Zero-width bitfields end runs.
356 if (Field->getBitWidthValue(Context) == 0) {
357 Run = FieldEnd;
358 continue;
359 }
360 llvm::Type *Type = Types.ConvertTypeForMem(Field->getType());
361 // If we don't have a run yet, or don't live within the previous run's
362 // allocated storage then we allocate some storage and start a new run.
363 if (Run == FieldEnd || BitOffset >= Tail) {
364 Run = Field;
365 StartBitOffset = BitOffset;
366 Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
367 // Add the storage member to the record. This must be added to the
368 // record before the bitfield members so that it gets laid out before
369 // the bitfields it contains get laid out.
370 Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
371 }
372 // Bitfields get the offset of their storage but come afterward and remain
373 // there after a stable sort.
374 Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
375 MemberInfo::Field, 0, *Field));
376 }
Anders Carlsson697f6592009-07-23 03:43:54 +0000377 return;
378 }
Warren Huntfb00c882014-02-21 23:49:50 +0000379 for (;;) {
380 // Check to see if we need to start a new run.
381 if (Run == FieldEnd) {
382 // If we're out of fields, return.
383 if (Field == FieldEnd)
384 break;
385 // Any non-zero-length bitfield can start a new run.
386 if (Field->getBitWidthValue(Context) != 0) {
387 Run = Field;
388 StartBitOffset = getFieldBitOffset(*Field);
389 Tail = StartBitOffset + Field->getBitWidthValue(Context);
390 }
391 ++Field;
392 continue;
393 }
394 // Add bitfields to the run as long as they qualify.
395 if (Field != FieldEnd && Field->getBitWidthValue(Context) != 0 &&
396 Tail == getFieldBitOffset(*Field)) {
397 Tail += Field->getBitWidthValue(Context);
398 ++Field;
399 continue;
400 }
401 // We've hit a break-point in the run and need to emit a storage field.
402 llvm::Type *Type = getIntNType(Tail - StartBitOffset);
403 // Add the storage member to the record and set the bitfield info for all of
404 // the bitfields in the run. Bitfields get the offset of their storage but
405 // come afterward and remain there after a stable sort.
406 Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
407 for (; Run != Field; ++Run)
408 Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
409 MemberInfo::Field, 0, *Run));
410 Run = FieldEnd;
411 }
412}
Anders Carlsson68e0b682009-08-08 18:23:56 +0000413
Warren Huntfb00c882014-02-21 23:49:50 +0000414void CGRecordLowering::accumulateBases() {
415 // If we've got a primary virtual base, we need to add it with the bases.
416 if (Layout.isPrimaryBaseVirtual())
417 Members.push_back(StorageInfo(
418 CharUnits::Zero(),
419 getStorageType(Layout.getPrimaryBase())));
420 // Accumulate the non-virtual bases.
421 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
422 BaseEnd = RD->bases_end();
423 Base != BaseEnd; ++Base) {
424 if (Base->isVirtual())
425 continue;
426 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
427 if (!BaseDecl->isEmpty())
428 Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
429 MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
430 }
431}
432
433void CGRecordLowering::accumulateVPtrs() {
434 if (Layout.hasOwnVFPtr())
435 Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr,
436 llvm::FunctionType::get(getIntNType(32), /*isVarArg=*/true)->
437 getPointerTo()->getPointerTo()));
438 if (Layout.hasOwnVBPtr())
439 Members.push_back(MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr,
440 llvm::Type::getInt32PtrTy(Types.getLLVMContext())));
441}
442
443void CGRecordLowering::accumulateVBases() {
444 Members.push_back(MemberInfo(Layout.getNonVirtualSize(),
445 MemberInfo::Scissor, 0, RD));
446 for (CXXRecordDecl::base_class_const_iterator Base = RD->vbases_begin(),
447 BaseEnd = RD->vbases_end();
448 Base != BaseEnd; ++Base) {
449 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
450 if (BaseDecl->isEmpty())
451 continue;
452 CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
453 // If the vbase is a primary virtual base of some base, then it doesn't
454 // get its own storage location but instead lives inside of that base.
455 if (!useMSABI() && Context.isNearlyEmpty(BaseDecl) &&
456 !hasOwnStorage(RD, BaseDecl)) {
457 Members.push_back(MemberInfo(Offset, MemberInfo::VBase, 0, BaseDecl));
458 continue;
459 }
460 // If we've got a vtordisp, add it as a storage type.
461 if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
462 Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
463 getIntNType(32)));
464 Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
465 getStorageType(BaseDecl), BaseDecl));
466 }
467}
468
469bool CGRecordLowering::hasOwnStorage(const CXXRecordDecl *Decl,
470 const CXXRecordDecl *Query) {
471 const ASTRecordLayout &DeclLayout = Context.getASTRecordLayout(Decl);
472 if (DeclLayout.isPrimaryBaseVirtual() && DeclLayout.getPrimaryBase() == Query)
473 return false;
474 for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin(),
475 BaseEnd = Decl->bases_end();
476 Base != BaseEnd; ++Base)
477 if (!hasOwnStorage(Base->getType()->getAsCXXRecordDecl(), Query))
478 return false;
479 return true;
480}
481
482void CGRecordLowering::calculateZeroInit() {
483 for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
484 MemberEnd = Members.end();
485 IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
486 if (Member->Kind == MemberInfo::Field) {
487 if (!Member->FD || isZeroInitializable(Member->FD))
488 continue;
489 IsZeroInitializable = IsZeroInitializableAsBase = false;
490 } else if (Member->Kind == MemberInfo::Base ||
491 Member->Kind == MemberInfo::VBase) {
492 if (isZeroInitializable(Member->RD))
493 continue;
494 IsZeroInitializable = false;
495 if (Member->Kind == MemberInfo::Base)
496 IsZeroInitializableAsBase = false;
497 }
498 }
499}
500
501void CGRecordLowering::clipTailPadding() {
502 std::vector<MemberInfo>::iterator Prior = Members.begin();
503 CharUnits Tail = getSize(Prior->Data);
504 for (std::vector<MemberInfo>::iterator Member = Prior + 1,
505 MemberEnd = Members.end();
506 Member != MemberEnd; ++Member) {
507 // Only members with data and the scissor can cut into tail padding.
508 if (!Member->Data && Member->Kind != MemberInfo::Scissor)
509 continue;
510 if (Member->Offset < Tail) {
511 assert(Prior->Kind == MemberInfo::Field && !Prior->FD &&
512 "Only storage fields have tail padding!");
513 Prior->Data = getByteArrayType(bitsToCharUnits(llvm::RoundUpToAlignment(
514 cast<llvm::IntegerType>(Prior->Data)->getIntegerBitWidth(), 8)));
515 }
516 if (Member->Data)
517 Prior = Member;
518 Tail = Prior->Offset + getSize(Prior->Data);
519 }
520}
521
522void CGRecordLowering::determinePacked() {
523 CharUnits Alignment = CharUnits::One();
524 for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
525 MemberEnd = Members.end();
526 Member != MemberEnd; ++Member) {
527 if (!Member->Data)
528 continue;
529 // If any member falls at an offset that it not a multiple of its alignment,
530 // then the entire record must be packed.
531 if (Member->Offset % getAlignment(Member->Data))
532 Packed = true;
533 Alignment = std::max(Alignment, getAlignment(Member->Data));
534 }
535 // If the size of the record (the capstone's offset) is not a multiple of the
536 // record's alignment, it must be packed.
537 if (Members.back().Offset % Alignment)
538 Packed = true;
539 // Update the alignment of the sentinal.
540 if (!Packed)
541 Members.back().Data = getIntNType(Context.toBits(Alignment));
542}
543
544void CGRecordLowering::insertPadding() {
545 std::vector<std::pair<CharUnits, CharUnits> > Padding;
546 CharUnits Size = CharUnits::Zero();
547 for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
548 MemberEnd = Members.end();
549 Member != MemberEnd; ++Member) {
550 if (!Member->Data)
551 continue;
552 CharUnits Offset = Member->Offset;
553 assert(Offset >= Size);
554 // Insert padding if we need to.
555 if (Offset != Size.RoundUpToAlignment(Packed ? CharUnits::One() :
556 getAlignment(Member->Data)))
557 Padding.push_back(std::make_pair(Size, Offset - Size));
558 Size = Offset + getSize(Member->Data);
559 }
560 if (Padding.empty())
Anders Carlsson307846f2009-07-23 03:17:50 +0000561 return;
Warren Huntfb00c882014-02-21 23:49:50 +0000562 // Add the padding to the Members list and sort it.
563 for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
564 Pad = Padding.begin(), PadEnd = Padding.end();
565 Pad != PadEnd; ++Pad)
566 Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
567 std::stable_sort(Members.begin(), Members.end());
568}
Mike Stump11289f42009-09-09 15:08:12 +0000569
Warren Huntfb00c882014-02-21 23:49:50 +0000570void CGRecordLowering::fillOutputFields() {
571 for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
572 MemberEnd = Members.end();
573 Member != MemberEnd; ++Member) {
574 if (Member->Data)
575 FieldTypes.push_back(Member->Data);
576 if (Member->Kind == MemberInfo::Field) {
577 if (Member->FD)
578 Fields[Member->FD] = FieldTypes.size() - 1;
579 // A field without storage must be a bitfield.
580 if (!Member->Data)
581 setBitFieldInfo(Member->FD, Member->Offset, FieldTypes.back());
582 } else if (Member->Kind == MemberInfo::Base)
583 NonVirtualBases[Member->RD] = FieldTypes.size() - 1;
584 else if (Member->Kind == MemberInfo::VBase)
585 VirtualBases[Member->RD] = FieldTypes.size() - 1;
586 }
Anders Carlsson307846f2009-07-23 03:17:50 +0000587}
588
Daniel Dunbarc7f9bba2010-09-02 23:53:28 +0000589CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000590 const FieldDecl *FD,
591 uint64_t Offset, uint64_t Size,
592 uint64_t StorageSize,
593 uint64_t StorageAlignment) {
Warren Huntfb00c882014-02-21 23:49:50 +0000594 // This function is vestigial from CGRecordLayoutBuilder days but is still
595 // used in GCObjCRuntime.cpp. That usage has a "fixme" attached to it that
596 // when addressed will allow for the removal of this function.
Chris Lattner2192fe52011-07-18 04:24:23 +0000597 llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
John McCall8a3c5552011-02-26 08:41:59 +0000598 CharUnits TypeSizeInBytes =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000599 CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
John McCall8a3c5552011-02-26 08:41:59 +0000600 uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000601
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000602 bool IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000603
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000604 if (Size > TypeSizeInBits) {
Anders Carlssond5f27b02010-04-17 22:54:57 +0000605 // We have a wide bit-field. The extra bits are only used for padding, so
606 // if we have a bitfield of type T, with size N:
607 //
608 // T t : N;
609 //
610 // We can just assume that it's:
611 //
612 // T t : sizeof(T);
613 //
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000614 Size = TypeSizeInBits;
Anders Carlssonbe6f3182010-04-16 16:23:02 +0000615 }
616
Chandler Carruthfd8eca22012-12-09 07:26:04 +0000617 // Reverse the bit offsets for big endian machines. Because we represent
618 // a bitfield as a single large integer load, we can imagine the bits
619 // counting from the most-significant-bit instead of the
620 // least-significant-bit.
621 if (Types.getDataLayout().isBigEndian()) {
622 Offset = StorageSize - (Offset + Size);
623 }
Chris Lattnerfb59c7c2011-02-17 22:09:58 +0000624
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000625 return CGBitFieldInfo(Offset, Size, IsSigned, StorageSize, StorageAlignment);
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000626}
627
Chris Lattnera5f58b02011-07-09 17:41:47 +0000628CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D,
629 llvm::StructType *Ty) {
Warren Huntfb00c882014-02-21 23:49:50 +0000630 CGRecordLowering Builder(*this, D);
Mike Stump11289f42009-09-09 15:08:12 +0000631
Warren Huntfb00c882014-02-21 23:49:50 +0000632 Builder.lower(false);
Anders Carlssone1d5ca52009-07-24 15:20:52 +0000633
Chris Lattnera5f58b02011-07-09 17:41:47 +0000634 Ty->setBody(Builder.FieldTypes, Builder.Packed);
Mike Stump11289f42009-09-09 15:08:12 +0000635
John McCall0217dfc22011-02-15 06:40:56 +0000636 // If we're in C++, compute the base subobject type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000637 llvm::StructType *BaseTy = 0;
Warren Huntfb00c882014-02-21 23:49:50 +0000638 if (isa<CXXRecordDecl>(D) && !D->isUnion() && !D->hasAttr<FinalAttr>()) {
639 BaseTy = Ty;
640 if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
641 CGRecordLowering BaseBuilder(*this, D);
642 BaseBuilder.lower(true);
643 BaseTy = llvm::StructType::create(
644 getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
645 addRecordTypeName(D, BaseTy, ".base");
646 }
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000647 }
648
Daniel Dunbar034299e2010-03-31 01:09:11 +0000649 CGRecordLayout *RL =
John McCall0217dfc22011-02-15 06:40:56 +0000650 new CGRecordLayout(Ty, BaseTy, Builder.IsZeroInitializable,
Warren Huntfb00c882014-02-21 23:49:50 +0000651 Builder.IsZeroInitializableAsBase);
Daniel Dunbar034299e2010-03-31 01:09:11 +0000652
John McCall0217dfc22011-02-15 06:40:56 +0000653 RL->NonVirtualBases.swap(Builder.NonVirtualBases);
654 RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
Anders Carlsson061ca522010-05-18 05:22:06 +0000655
Anders Carlsson307846f2009-07-23 03:17:50 +0000656 // Add all the field numbers.
John McCall0217dfc22011-02-15 06:40:56 +0000657 RL->FieldInfo.swap(Builder.Fields);
Anders Carlsson307846f2009-07-23 03:17:50 +0000658
659 // Add bitfield info.
John McCall0217dfc22011-02-15 06:40:56 +0000660 RL->BitFields.swap(Builder.BitFields);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000662 // Dump the layout, if requested.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000663 if (getContext().getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +0000664 llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
665 llvm::outs() << "Record: ";
666 D->dump(llvm::outs());
667 llvm::outs() << "\nLayout: ";
668 RL->print(llvm::outs());
Daniel Dunbarb935b932010-04-13 20:58:55 +0000669 }
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000670
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000671#ifndef NDEBUG
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000672 // Verify that the computed LLVM struct size matches the AST layout size.
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000673 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
674
Ken Dyckb0fcc592011-02-11 01:54:29 +0000675 uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
Micah Villmowdd31ca12012-10-08 16:25:52 +0000676 assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000677 "Type size mismatch!");
678
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000679 if (BaseTy) {
Ken Dyckbec02852011-02-08 02:02:47 +0000680 CharUnits NonVirtualSize = Layout.getNonVirtualSize();
Ken Dyckbec02852011-02-08 02:02:47 +0000681
682 uint64_t AlignedNonVirtualTypeSizeInBits =
Warren Huntfb00c882014-02-21 23:49:50 +0000683 getContext().toBits(NonVirtualSize);
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000684
685 assert(AlignedNonVirtualTypeSizeInBits ==
Micah Villmowdd31ca12012-10-08 16:25:52 +0000686 getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000687 "Type size mismatch!");
688 }
689
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000690 // Verify that the LLVM and AST field offsets agree.
Chris Lattner2192fe52011-07-18 04:24:23 +0000691 llvm::StructType *ST =
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000692 dyn_cast<llvm::StructType>(RL->getLLVMType());
Micah Villmowdd31ca12012-10-08 16:25:52 +0000693 const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000694
695 const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
696 RecordDecl::field_iterator it = D->field_begin();
697 for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
David Blaikie40ed2972012-06-06 20:45:41 +0000698 const FieldDecl *FD = *it;
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000699
700 // For non-bit-fields, just check that the LLVM struct offset matches the
701 // AST offset.
702 if (!FD->isBitField()) {
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000703 unsigned FieldNo = RL->getLLVMFieldNo(FD);
704 assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
705 "Invalid field offset!");
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000706 continue;
707 }
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000708
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000709 // Ignore unnamed bit-fields.
Eli Friedman2782dac2013-06-26 20:50:34 +0000710 if (!FD->getDeclName())
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000711 continue;
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000712
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000713 // Don't inspect zero-length bitfields.
714 if (FD->getBitWidthValue(getContext()) == 0)
715 continue;
716
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000717 const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
Chandler Carruthed72cdc2012-12-09 10:33:27 +0000718 llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
719
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000720 // Unions have overlapping elements dictating their layout, but for
721 // non-unions we can verify that this section of the layout is the exact
Chandler Carruthed72cdc2012-12-09 10:33:27 +0000722 // expected size.
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000723 if (D->isUnion()) {
Chandler Carruthed72cdc2012-12-09 10:33:27 +0000724 // For unions we verify that the start is zero and the size
725 // is in-bounds. However, on BE systems, the offset may be non-zero, but
726 // the size + offset should match the storage size in that case as it
727 // "starts" at the back.
728 if (getDataLayout().isBigEndian())
David Greene464d2192013-01-15 23:13:49 +0000729 assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
730 Info.StorageSize &&
Chandler Carruthed72cdc2012-12-09 10:33:27 +0000731 "Big endian union bitfield does not end at the back");
732 else
733 assert(Info.Offset == 0 &&
734 "Little endian union bitfield with a non-zero offset");
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000735 assert(Info.StorageSize <= SL->getSizeInBits() &&
736 "Union not large enough for bitfield storage");
737 } else {
738 assert(Info.StorageSize ==
739 getDataLayout().getTypeAllocSizeInBits(ElementTy) &&
740 "Storage size does not match the element type size");
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000741 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000742 assert(Info.Size > 0 && "Empty bitfield!");
Eli Bendersky76bd3d82012-12-18 18:53:14 +0000743 assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000744 "Bitfield outside of its allocated storage");
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000745 }
746#endif
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000747
Daniel Dunbar034299e2010-03-31 01:09:11 +0000748 return RL;
Anders Carlsson307846f2009-07-23 03:17:50 +0000749}
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000750
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000751void CGRecordLayout::print(raw_ostream &OS) const {
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000752 OS << "<CGRecordLayout\n";
John McCall0217dfc22011-02-15 06:40:56 +0000753 OS << " LLVMType:" << *CompleteObjectType << "\n";
754 if (BaseSubobjectType)
755 OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
John McCall614dbdc2010-08-22 21:01:12 +0000756 OS << " IsZeroInitializable:" << IsZeroInitializable << "\n";
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000757 OS << " BitFields:[\n";
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000758
759 // Print bit-field infos in declaration order.
760 std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000761 for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
762 it = BitFields.begin(), ie = BitFields.end();
763 it != ie; ++it) {
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000764 const RecordDecl *RD = it->first->getParent();
765 unsigned Index = 0;
766 for (RecordDecl::field_iterator
David Blaikie40ed2972012-06-06 20:45:41 +0000767 it2 = RD->field_begin(); *it2 != it->first; ++it2)
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000768 ++Index;
769 BFIs.push_back(std::make_pair(Index, &it->second));
770 }
771 llvm::array_pod_sort(BFIs.begin(), BFIs.end());
772 for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
Daniel Dunbarb935b932010-04-13 20:58:55 +0000773 OS.indent(4);
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000774 BFIs[i].second->print(OS);
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000775 OS << "\n";
776 }
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000777
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000778 OS << "]>\n";
779}
780
781void CGRecordLayout::dump() const {
782 print(llvm::errs());
783}
784
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000785void CGBitFieldInfo::print(raw_ostream &OS) const {
Chandler Carruthff0e3a12012-12-06 11:14:44 +0000786 OS << "<CGBitFieldInfo"
787 << " Offset:" << Offset
788 << " Size:" << Size
789 << " IsSigned:" << IsSigned
790 << " StorageSize:" << StorageSize
791 << " StorageAlignment:" << StorageAlignment << ">";
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000792}
793
794void CGBitFieldInfo::dump() const {
795 print(llvm::errs());
796}