1 //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "clang/AST/RecordLayout.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/AST/Attr.h" 13 #include "clang/AST/CXXInheritance.h" 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/DeclCXX.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "clang/Sema/SemaDiagnostic.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/Support/Format.h" 22 #include "llvm/Support/MathExtras.h" 23 24 using namespace clang; 25 26 namespace { 27 28 /// BaseSubobjectInfo - Represents a single base subobject in a complete class. 29 /// For a class hierarchy like 30 /// 31 /// class A { }; 32 /// class B : A { }; 33 /// class C : A, B { }; 34 /// 35 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo 36 /// instances, one for B and two for A. 37 /// 38 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated. 39 struct BaseSubobjectInfo { 40 /// Class - The class for this base info. 41 const CXXRecordDecl *Class; 42 43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not. 44 bool IsVirtual; 45 46 /// Bases - Information about the base subobjects. 47 SmallVector<BaseSubobjectInfo*, 4> Bases; 48 49 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base 50 /// of this base info (if one exists). 51 BaseSubobjectInfo *PrimaryVirtualBaseInfo; 52 53 // FIXME: Document. 54 const BaseSubobjectInfo *Derived; 55 }; 56 57 /// \brief Externally provided layout. Typically used when the AST source, such 58 /// as DWARF, lacks all the information that was available at compile time, such 59 /// as alignment attributes on fields and pragmas in effect. 60 struct ExternalLayout { 61 ExternalLayout() : Size(0), Align(0) {} 62 63 /// \brief Overall record size in bits. 64 uint64_t Size; 65 66 /// \brief Overall record alignment in bits. 67 uint64_t Align; 68 69 /// \brief Record field offsets in bits. 70 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets; 71 72 /// \brief Direct, non-virtual base offsets. 73 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets; 74 75 /// \brief Virtual base offsets. 76 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets; 77 78 /// Get the offset of the given field. The external source must provide 79 /// entries for all fields in the record. 80 uint64_t getExternalFieldOffset(const FieldDecl *FD) { 81 assert(FieldOffsets.count(FD) && 82 "Field does not have an external offset"); 83 return FieldOffsets[FD]; 84 } 85 86 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) { 87 auto Known = BaseOffsets.find(RD); 88 if (Known == BaseOffsets.end()) 89 return false; 90 BaseOffset = Known->second; 91 return true; 92 } 93 94 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) { 95 auto Known = VirtualBaseOffsets.find(RD); 96 if (Known == VirtualBaseOffsets.end()) 97 return false; 98 BaseOffset = Known->second; 99 return true; 100 } 101 }; 102 103 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different 104 /// offsets while laying out a C++ class. 105 class EmptySubobjectMap { 106 const ASTContext &Context; 107 uint64_t CharWidth; 108 109 /// Class - The class whose empty entries we're keeping track of. 110 const CXXRecordDecl *Class; 111 112 /// EmptyClassOffsets - A map from offsets to empty record decls. 113 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy; 114 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy; 115 EmptyClassOffsetsMapTy EmptyClassOffsets; 116 117 /// MaxEmptyClassOffset - The highest offset known to contain an empty 118 /// base subobject. 119 CharUnits MaxEmptyClassOffset; 120 121 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or 122 /// member subobject that is empty. 123 void ComputeEmptySubobjectSizes(); 124 125 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset); 126 127 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 128 CharUnits Offset, bool PlacingEmptyBase); 129 130 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 131 const CXXRecordDecl *Class, 132 CharUnits Offset); 133 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset); 134 135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty 136 /// subobjects beyond the given offset. 137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const { 138 return Offset <= MaxEmptyClassOffset; 139 } 140 141 CharUnits 142 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const { 143 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); 144 assert(FieldOffset % CharWidth == 0 && 145 "Field offset not at char boundary!"); 146 147 return Context.toCharUnitsFromBits(FieldOffset); 148 } 149 150 protected: 151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, 152 CharUnits Offset) const; 153 154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, 155 CharUnits Offset); 156 157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 158 const CXXRecordDecl *Class, 159 CharUnits Offset) const; 160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, 161 CharUnits Offset) const; 162 163 public: 164 /// This holds the size of the largest empty subobject (either a base 165 /// or a member). Will be zero if the record being built doesn't contain 166 /// any empty classes. 167 CharUnits SizeOfLargestEmptySubobject; 168 169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class) 170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) { 171 ComputeEmptySubobjectSizes(); 172 } 173 174 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed 175 /// at the given offset. 176 /// Returns false if placing the record will result in two components 177 /// (direct or indirect) of the same type having the same offset. 178 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, 179 CharUnits Offset); 180 181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given 182 /// offset. 183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset); 184 }; 185 186 void EmptySubobjectMap::ComputeEmptySubobjectSizes() { 187 // Check the bases. 188 for (const CXXBaseSpecifier &Base : Class->bases()) { 189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 190 191 CharUnits EmptySize; 192 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl); 193 if (BaseDecl->isEmpty()) { 194 // If the class decl is empty, get its size. 195 EmptySize = Layout.getSize(); 196 } else { 197 // Otherwise, we get the largest empty subobject for the decl. 198 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 199 } 200 201 if (EmptySize > SizeOfLargestEmptySubobject) 202 SizeOfLargestEmptySubobject = EmptySize; 203 } 204 205 // Check the fields. 206 for (const FieldDecl *FD : Class->fields()) { 207 const RecordType *RT = 208 Context.getBaseElementType(FD->getType())->getAs<RecordType>(); 209 210 // We only care about record types. 211 if (!RT) 212 continue; 213 214 CharUnits EmptySize; 215 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl(); 216 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl); 217 if (MemberDecl->isEmpty()) { 218 // If the class decl is empty, get its size. 219 EmptySize = Layout.getSize(); 220 } else { 221 // Otherwise, we get the largest empty subobject for the decl. 222 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 223 } 224 225 if (EmptySize > SizeOfLargestEmptySubobject) 226 SizeOfLargestEmptySubobject = EmptySize; 227 } 228 } 229 230 bool 231 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, 232 CharUnits Offset) const { 233 // We only need to check empty bases. 234 if (!RD->isEmpty()) 235 return true; 236 237 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset); 238 if (I == EmptyClassOffsets.end()) 239 return true; 240 241 const ClassVectorTy &Classes = I->second; 242 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end()) 243 return true; 244 245 // There is already an empty class of the same type at this offset. 246 return false; 247 } 248 249 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, 250 CharUnits Offset) { 251 // We only care about empty bases. 252 if (!RD->isEmpty()) 253 return; 254 255 // If we have empty structures inside a union, we can assign both 256 // the same offset. Just avoid pushing them twice in the list. 257 ClassVectorTy &Classes = EmptyClassOffsets[Offset]; 258 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end()) 259 return; 260 261 Classes.push_back(RD); 262 263 // Update the empty class offset. 264 if (Offset > MaxEmptyClassOffset) 265 MaxEmptyClassOffset = Offset; 266 } 267 268 bool 269 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, 270 CharUnits Offset) { 271 // We don't have to keep looking past the maximum offset that's known to 272 // contain an empty class. 273 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 274 return true; 275 276 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset)) 277 return false; 278 279 // Traverse all non-virtual bases. 280 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 281 for (const BaseSubobjectInfo *Base : Info->Bases) { 282 if (Base->IsVirtual) 283 continue; 284 285 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 286 287 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset)) 288 return false; 289 } 290 291 if (Info->PrimaryVirtualBaseInfo) { 292 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; 293 294 if (Info == PrimaryVirtualBaseInfo->Derived) { 295 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset)) 296 return false; 297 } 298 } 299 300 // Traverse all member variables. 301 unsigned FieldNo = 0; 302 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 303 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { 304 if (I->isBitField()) 305 continue; 306 307 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 308 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset)) 309 return false; 310 } 311 312 return true; 313 } 314 315 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 316 CharUnits Offset, 317 bool PlacingEmptyBase) { 318 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) { 319 // We know that the only empty subobjects that can conflict with empty 320 // subobject of non-empty bases, are empty bases that can be placed at 321 // offset zero. Because of this, we only need to keep track of empty base 322 // subobjects with offsets less than the size of the largest empty 323 // subobject for our class. 324 return; 325 } 326 327 AddSubobjectAtOffset(Info->Class, Offset); 328 329 // Traverse all non-virtual bases. 330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 331 for (const BaseSubobjectInfo *Base : Info->Bases) { 332 if (Base->IsVirtual) 333 continue; 334 335 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 336 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase); 337 } 338 339 if (Info->PrimaryVirtualBaseInfo) { 340 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; 341 342 if (Info == PrimaryVirtualBaseInfo->Derived) 343 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset, 344 PlacingEmptyBase); 345 } 346 347 // Traverse all member variables. 348 unsigned FieldNo = 0; 349 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 350 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { 351 if (I->isBitField()) 352 continue; 353 354 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 355 UpdateEmptyFieldSubobjects(*I, FieldOffset); 356 } 357 } 358 359 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, 360 CharUnits Offset) { 361 // If we know this class doesn't have any empty subobjects we don't need to 362 // bother checking. 363 if (SizeOfLargestEmptySubobject.isZero()) 364 return true; 365 366 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset)) 367 return false; 368 369 // We are able to place the base at this offset. Make sure to update the 370 // empty base subobject map. 371 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty()); 372 return true; 373 } 374 375 bool 376 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 377 const CXXRecordDecl *Class, 378 CharUnits Offset) const { 379 // We don't have to keep looking past the maximum offset that's known to 380 // contain an empty class. 381 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 382 return true; 383 384 if (!CanPlaceSubobjectAtOffset(RD, Offset)) 385 return false; 386 387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 388 389 // Traverse all non-virtual bases. 390 for (const CXXBaseSpecifier &Base : RD->bases()) { 391 if (Base.isVirtual()) 392 continue; 393 394 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 395 396 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 397 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset)) 398 return false; 399 } 400 401 if (RD == Class) { 402 // This is the most derived class, traverse virtual bases as well. 403 for (const CXXBaseSpecifier &Base : RD->vbases()) { 404 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl(); 405 406 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl); 407 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset)) 408 return false; 409 } 410 } 411 412 // Traverse all member variables. 413 unsigned FieldNo = 0; 414 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 415 I != E; ++I, ++FieldNo) { 416 if (I->isBitField()) 417 continue; 418 419 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 420 421 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset)) 422 return false; 423 } 424 425 return true; 426 } 427 428 bool 429 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, 430 CharUnits Offset) const { 431 // We don't have to keep looking past the maximum offset that's known to 432 // contain an empty class. 433 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 434 return true; 435 436 QualType T = FD->getType(); 437 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 438 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset); 439 440 // If we have an array type we need to look at every element. 441 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 442 QualType ElemTy = Context.getBaseElementType(AT); 443 const RecordType *RT = ElemTy->getAs<RecordType>(); 444 if (!RT) 445 return true; 446 447 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 448 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 449 450 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 451 CharUnits ElementOffset = Offset; 452 for (uint64_t I = 0; I != NumElements; ++I) { 453 // We don't have to keep looking past the maximum offset that's known to 454 // contain an empty class. 455 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset)) 456 return true; 457 458 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset)) 459 return false; 460 461 ElementOffset += Layout.getSize(); 462 } 463 } 464 465 return true; 466 } 467 468 bool 469 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, 470 CharUnits Offset) { 471 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset)) 472 return false; 473 474 // We are able to place the member variable at this offset. 475 // Make sure to update the empty base subobject map. 476 UpdateEmptyFieldSubobjects(FD, Offset); 477 return true; 478 } 479 480 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 481 const CXXRecordDecl *Class, 482 CharUnits Offset) { 483 // We know that the only empty subobjects that can conflict with empty 484 // field subobjects are subobjects of empty bases that can be placed at offset 485 // zero. Because of this, we only need to keep track of empty field 486 // subobjects with offsets less than the size of the largest empty 487 // subobject for our class. 488 if (Offset >= SizeOfLargestEmptySubobject) 489 return; 490 491 AddSubobjectAtOffset(RD, Offset); 492 493 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 494 495 // Traverse all non-virtual bases. 496 for (const CXXBaseSpecifier &Base : RD->bases()) { 497 if (Base.isVirtual()) 498 continue; 499 500 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 501 502 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 503 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset); 504 } 505 506 if (RD == Class) { 507 // This is the most derived class, traverse virtual bases as well. 508 for (const CXXBaseSpecifier &Base : RD->vbases()) { 509 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl(); 510 511 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl); 512 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset); 513 } 514 } 515 516 // Traverse all member variables. 517 unsigned FieldNo = 0; 518 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 519 I != E; ++I, ++FieldNo) { 520 if (I->isBitField()) 521 continue; 522 523 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 524 525 UpdateEmptyFieldSubobjects(*I, FieldOffset); 526 } 527 } 528 529 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, 530 CharUnits Offset) { 531 QualType T = FD->getType(); 532 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 533 UpdateEmptyFieldSubobjects(RD, RD, Offset); 534 return; 535 } 536 537 // If we have an array type we need to update every element. 538 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 539 QualType ElemTy = Context.getBaseElementType(AT); 540 const RecordType *RT = ElemTy->getAs<RecordType>(); 541 if (!RT) 542 return; 543 544 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 545 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 546 547 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 548 CharUnits ElementOffset = Offset; 549 550 for (uint64_t I = 0; I != NumElements; ++I) { 551 // We know that the only empty subobjects that can conflict with empty 552 // field subobjects are subobjects of empty bases that can be placed at 553 // offset zero. Because of this, we only need to keep track of empty field 554 // subobjects with offsets less than the size of the largest empty 555 // subobject for our class. 556 if (ElementOffset >= SizeOfLargestEmptySubobject) 557 return; 558 559 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset); 560 ElementOffset += Layout.getSize(); 561 } 562 } 563 } 564 565 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy; 566 567 class ItaniumRecordLayoutBuilder { 568 protected: 569 // FIXME: Remove this and make the appropriate fields public. 570 friend class clang::ASTContext; 571 572 const ASTContext &Context; 573 574 EmptySubobjectMap *EmptySubobjects; 575 576 /// Size - The current size of the record layout. 577 uint64_t Size; 578 579 /// Alignment - The current alignment of the record layout. 580 CharUnits Alignment; 581 582 /// \brief The alignment if attribute packed is not used. 583 CharUnits UnpackedAlignment; 584 585 SmallVector<uint64_t, 16> FieldOffsets; 586 587 /// \brief Whether the external AST source has provided a layout for this 588 /// record. 589 unsigned UseExternalLayout : 1; 590 591 /// \brief Whether we need to infer alignment, even when we have an 592 /// externally-provided layout. 593 unsigned InferAlignment : 1; 594 595 /// Packed - Whether the record is packed or not. 596 unsigned Packed : 1; 597 598 unsigned IsUnion : 1; 599 600 unsigned IsMac68kAlign : 1; 601 602 unsigned IsMsStruct : 1; 603 604 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield, 605 /// this contains the number of bits in the last unit that can be used for 606 /// an adjacent bitfield if necessary. The unit in question is usually 607 /// a byte, but larger units are used if IsMsStruct. 608 unsigned char UnfilledBitsInLastUnit; 609 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type 610 /// of the previous field if it was a bitfield. 611 unsigned char LastBitfieldTypeSize; 612 613 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by 614 /// #pragma pack. 615 CharUnits MaxFieldAlignment; 616 617 /// DataSize - The data size of the record being laid out. 618 uint64_t DataSize; 619 620 CharUnits NonVirtualSize; 621 CharUnits NonVirtualAlignment; 622 623 /// PrimaryBase - the primary base class (if one exists) of the class 624 /// we're laying out. 625 const CXXRecordDecl *PrimaryBase; 626 627 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying 628 /// out is virtual. 629 bool PrimaryBaseIsVirtual; 630 631 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl 632 /// pointer, as opposed to inheriting one from a primary base class. 633 bool HasOwnVFPtr; 634 635 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy; 636 637 /// Bases - base classes and their offsets in the record. 638 BaseOffsetsMapTy Bases; 639 640 // VBases - virtual base classes and their offsets in the record. 641 ASTRecordLayout::VBaseOffsetsMapTy VBases; 642 643 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are 644 /// primary base classes for some other direct or indirect base class. 645 CXXIndirectPrimaryBaseSet IndirectPrimaryBases; 646 647 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in 648 /// inheritance graph order. Used for determining the primary base class. 649 const CXXRecordDecl *FirstNearlyEmptyVBase; 650 651 /// VisitedVirtualBases - A set of all the visited virtual bases, used to 652 /// avoid visiting virtual bases more than once. 653 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; 654 655 /// Valid if UseExternalLayout is true. 656 ExternalLayout External; 657 658 ItaniumRecordLayoutBuilder(const ASTContext &Context, 659 EmptySubobjectMap *EmptySubobjects) 660 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), 661 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()), 662 UseExternalLayout(false), InferAlignment(false), Packed(false), 663 IsUnion(false), IsMac68kAlign(false), IsMsStruct(false), 664 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0), 665 MaxFieldAlignment(CharUnits::Zero()), DataSize(0), 666 NonVirtualSize(CharUnits::Zero()), 667 NonVirtualAlignment(CharUnits::One()), PrimaryBase(nullptr), 668 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false), 669 FirstNearlyEmptyVBase(nullptr) {} 670 671 void Layout(const RecordDecl *D); 672 void Layout(const CXXRecordDecl *D); 673 void Layout(const ObjCInterfaceDecl *D); 674 675 void LayoutFields(const RecordDecl *D); 676 void LayoutField(const FieldDecl *D, bool InsertExtraPadding); 677 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize, 678 bool FieldPacked, const FieldDecl *D); 679 void LayoutBitField(const FieldDecl *D); 680 681 TargetCXXABI getCXXABI() const { 682 return Context.getTargetInfo().getCXXABI(); 683 } 684 685 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects. 686 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator; 687 688 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *> 689 BaseSubobjectInfoMapTy; 690 691 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases 692 /// of the class we're laying out to their base subobject info. 693 BaseSubobjectInfoMapTy VirtualBaseInfo; 694 695 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the 696 /// class we're laying out to their base subobject info. 697 BaseSubobjectInfoMapTy NonVirtualBaseInfo; 698 699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the 700 /// bases of the given class. 701 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD); 702 703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a 704 /// single class and all of its base classes. 705 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 706 bool IsVirtual, 707 BaseSubobjectInfo *Derived); 708 709 /// DeterminePrimaryBase - Determine the primary base of the given class. 710 void DeterminePrimaryBase(const CXXRecordDecl *RD); 711 712 void SelectPrimaryVBase(const CXXRecordDecl *RD); 713 714 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign); 715 716 /// LayoutNonVirtualBases - Determines the primary base class (if any) and 717 /// lays it out. Will then proceed to lay out all non-virtual base clasess. 718 void LayoutNonVirtualBases(const CXXRecordDecl *RD); 719 720 /// LayoutNonVirtualBase - Lays out a single non-virtual base. 721 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base); 722 723 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info, 724 CharUnits Offset); 725 726 /// LayoutVirtualBases - Lays out all the virtual bases. 727 void LayoutVirtualBases(const CXXRecordDecl *RD, 728 const CXXRecordDecl *MostDerivedClass); 729 730 /// LayoutVirtualBase - Lays out a single virtual base. 731 void LayoutVirtualBase(const BaseSubobjectInfo *Base); 732 733 /// LayoutBase - Will lay out a base and return the offset where it was 734 /// placed, in chars. 735 CharUnits LayoutBase(const BaseSubobjectInfo *Base); 736 737 /// InitializeLayout - Initialize record layout for the given record decl. 738 void InitializeLayout(const Decl *D); 739 740 /// FinishLayout - Finalize record layout. Adjust record size based on the 741 /// alignment. 742 void FinishLayout(const NamedDecl *D); 743 744 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment); 745 void UpdateAlignment(CharUnits NewAlignment) { 746 UpdateAlignment(NewAlignment, NewAlignment); 747 } 748 749 /// \brief Retrieve the externally-supplied field offset for the given 750 /// field. 751 /// 752 /// \param Field The field whose offset is being queried. 753 /// \param ComputedOffset The offset that we've computed for this field. 754 uint64_t updateExternalFieldOffset(const FieldDecl *Field, 755 uint64_t ComputedOffset); 756 757 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset, 758 uint64_t UnpackedOffset, unsigned UnpackedAlign, 759 bool isPacked, const FieldDecl *D); 760 761 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 762 763 CharUnits getSize() const { 764 assert(Size % Context.getCharWidth() == 0); 765 return Context.toCharUnitsFromBits(Size); 766 } 767 uint64_t getSizeInBits() const { return Size; } 768 769 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); } 770 void setSize(uint64_t NewSize) { Size = NewSize; } 771 772 CharUnits getAligment() const { return Alignment; } 773 774 CharUnits getDataSize() const { 775 assert(DataSize % Context.getCharWidth() == 0); 776 return Context.toCharUnitsFromBits(DataSize); 777 } 778 uint64_t getDataSizeInBits() const { return DataSize; } 779 780 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); } 781 void setDataSize(uint64_t NewSize) { DataSize = NewSize; } 782 783 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete; 784 void operator=(const ItaniumRecordLayoutBuilder &) = delete; 785 }; 786 } // end anonymous namespace 787 788 void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) { 789 for (const auto &I : RD->bases()) { 790 assert(!I.getType()->isDependentType() && 791 "Cannot layout class with dependent bases."); 792 793 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 794 795 // Check if this is a nearly empty virtual base. 796 if (I.isVirtual() && Context.isNearlyEmpty(Base)) { 797 // If it's not an indirect primary base, then we've found our primary 798 // base. 799 if (!IndirectPrimaryBases.count(Base)) { 800 PrimaryBase = Base; 801 PrimaryBaseIsVirtual = true; 802 return; 803 } 804 805 // Is this the first nearly empty virtual base? 806 if (!FirstNearlyEmptyVBase) 807 FirstNearlyEmptyVBase = Base; 808 } 809 810 SelectPrimaryVBase(Base); 811 if (PrimaryBase) 812 return; 813 } 814 } 815 816 /// DeterminePrimaryBase - Determine the primary base of the given class. 817 void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) { 818 // If the class isn't dynamic, it won't have a primary base. 819 if (!RD->isDynamicClass()) 820 return; 821 822 // Compute all the primary virtual bases for all of our direct and 823 // indirect bases, and record all their primary virtual base classes. 824 RD->getIndirectPrimaryBases(IndirectPrimaryBases); 825 826 // If the record has a dynamic base class, attempt to choose a primary base 827 // class. It is the first (in direct base class order) non-virtual dynamic 828 // base class, if one exists. 829 for (const auto &I : RD->bases()) { 830 // Ignore virtual bases. 831 if (I.isVirtual()) 832 continue; 833 834 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 835 836 if (Base->isDynamicClass()) { 837 // We found it. 838 PrimaryBase = Base; 839 PrimaryBaseIsVirtual = false; 840 return; 841 } 842 } 843 844 // Under the Itanium ABI, if there is no non-virtual primary base class, 845 // try to compute the primary virtual base. The primary virtual base is 846 // the first nearly empty virtual base that is not an indirect primary 847 // virtual base class, if one exists. 848 if (RD->getNumVBases() != 0) { 849 SelectPrimaryVBase(RD); 850 if (PrimaryBase) 851 return; 852 } 853 854 // Otherwise, it is the first indirect primary base class, if one exists. 855 if (FirstNearlyEmptyVBase) { 856 PrimaryBase = FirstNearlyEmptyVBase; 857 PrimaryBaseIsVirtual = true; 858 return; 859 } 860 861 assert(!PrimaryBase && "Should not get here with a primary base!"); 862 } 863 864 BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( 865 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) { 866 BaseSubobjectInfo *Info; 867 868 if (IsVirtual) { 869 // Check if we already have info about this virtual base. 870 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD]; 871 if (InfoSlot) { 872 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!"); 873 return InfoSlot; 874 } 875 876 // We don't, create it. 877 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; 878 Info = InfoSlot; 879 } else { 880 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; 881 } 882 883 Info->Class = RD; 884 Info->IsVirtual = IsVirtual; 885 Info->Derived = nullptr; 886 Info->PrimaryVirtualBaseInfo = nullptr; 887 888 const CXXRecordDecl *PrimaryVirtualBase = nullptr; 889 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr; 890 891 // Check if this base has a primary virtual base. 892 if (RD->getNumVBases()) { 893 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 894 if (Layout.isPrimaryBaseVirtual()) { 895 // This base does have a primary virtual base. 896 PrimaryVirtualBase = Layout.getPrimaryBase(); 897 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!"); 898 899 // Now check if we have base subobject info about this primary base. 900 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); 901 902 if (PrimaryVirtualBaseInfo) { 903 if (PrimaryVirtualBaseInfo->Derived) { 904 // We did have info about this primary base, and it turns out that it 905 // has already been claimed as a primary virtual base for another 906 // base. 907 PrimaryVirtualBase = nullptr; 908 } else { 909 // We can claim this base as our primary base. 910 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; 911 PrimaryVirtualBaseInfo->Derived = Info; 912 } 913 } 914 } 915 } 916 917 // Now go through all direct bases. 918 for (const auto &I : RD->bases()) { 919 bool IsVirtual = I.isVirtual(); 920 921 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl(); 922 923 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info)); 924 } 925 926 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) { 927 // Traversing the bases must have created the base info for our primary 928 // virtual base. 929 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); 930 assert(PrimaryVirtualBaseInfo && 931 "Did not create a primary virtual base!"); 932 933 // Claim the primary virtual base as our primary virtual base. 934 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; 935 PrimaryVirtualBaseInfo->Derived = Info; 936 } 937 938 return Info; 939 } 940 941 void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( 942 const CXXRecordDecl *RD) { 943 for (const auto &I : RD->bases()) { 944 bool IsVirtual = I.isVirtual(); 945 946 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl(); 947 948 // Compute the base subobject info for this base. 949 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 950 nullptr); 951 952 if (IsVirtual) { 953 // ComputeBaseInfo has already added this base for us. 954 assert(VirtualBaseInfo.count(BaseDecl) && 955 "Did not add virtual base!"); 956 } else { 957 // Add the base info to the map of non-virtual bases. 958 assert(!NonVirtualBaseInfo.count(BaseDecl) && 959 "Non-virtual base already exists!"); 960 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info)); 961 } 962 } 963 } 964 965 void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment( 966 CharUnits UnpackedBaseAlign) { 967 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign; 968 969 // The maximum field alignment overrides base align. 970 if (!MaxFieldAlignment.isZero()) { 971 BaseAlign = std::min(BaseAlign, MaxFieldAlignment); 972 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment); 973 } 974 975 // Round up the current record size to pointer alignment. 976 setSize(getSize().RoundUpToAlignment(BaseAlign)); 977 setDataSize(getSize()); 978 979 // Update the alignment. 980 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 981 } 982 983 void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( 984 const CXXRecordDecl *RD) { 985 // Then, determine the primary base class. 986 DeterminePrimaryBase(RD); 987 988 // Compute base subobject info. 989 ComputeBaseSubobjectInfo(RD); 990 991 // If we have a primary base class, lay it out. 992 if (PrimaryBase) { 993 if (PrimaryBaseIsVirtual) { 994 // If the primary virtual base was a primary virtual base of some other 995 // base class we'll have to steal it. 996 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase); 997 PrimaryBaseInfo->Derived = nullptr; 998 999 // We have a virtual primary base, insert it as an indirect primary base. 1000 IndirectPrimaryBases.insert(PrimaryBase); 1001 1002 assert(!VisitedVirtualBases.count(PrimaryBase) && 1003 "vbase already visited!"); 1004 VisitedVirtualBases.insert(PrimaryBase); 1005 1006 LayoutVirtualBase(PrimaryBaseInfo); 1007 } else { 1008 BaseSubobjectInfo *PrimaryBaseInfo = 1009 NonVirtualBaseInfo.lookup(PrimaryBase); 1010 assert(PrimaryBaseInfo && 1011 "Did not find base info for non-virtual primary base!"); 1012 1013 LayoutNonVirtualBase(PrimaryBaseInfo); 1014 } 1015 1016 // If this class needs a vtable/vf-table and didn't get one from a 1017 // primary base, add it in now. 1018 } else if (RD->isDynamicClass()) { 1019 assert(DataSize == 0 && "Vtable pointer must be at offset zero!"); 1020 CharUnits PtrWidth = 1021 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 1022 CharUnits PtrAlign = 1023 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); 1024 EnsureVTablePointerAlignment(PtrAlign); 1025 HasOwnVFPtr = true; 1026 setSize(getSize() + PtrWidth); 1027 setDataSize(getSize()); 1028 } 1029 1030 // Now lay out the non-virtual bases. 1031 for (const auto &I : RD->bases()) { 1032 1033 // Ignore virtual bases. 1034 if (I.isVirtual()) 1035 continue; 1036 1037 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl(); 1038 1039 // Skip the primary base, because we've already laid it out. The 1040 // !PrimaryBaseIsVirtual check is required because we might have a 1041 // non-virtual base of the same type as a primary virtual base. 1042 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual) 1043 continue; 1044 1045 // Lay out the base. 1046 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl); 1047 assert(BaseInfo && "Did not find base info for non-virtual base!"); 1048 1049 LayoutNonVirtualBase(BaseInfo); 1050 } 1051 } 1052 1053 void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase( 1054 const BaseSubobjectInfo *Base) { 1055 // Layout the base. 1056 CharUnits Offset = LayoutBase(Base); 1057 1058 // Add its base class offset. 1059 assert(!Bases.count(Base->Class) && "base offset already exists!"); 1060 Bases.insert(std::make_pair(Base->Class, Offset)); 1061 1062 AddPrimaryVirtualBaseOffsets(Base, Offset); 1063 } 1064 1065 void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets( 1066 const BaseSubobjectInfo *Info, CharUnits Offset) { 1067 // This base isn't interesting, it has no virtual bases. 1068 if (!Info->Class->getNumVBases()) 1069 return; 1070 1071 // First, check if we have a virtual primary base to add offsets for. 1072 if (Info->PrimaryVirtualBaseInfo) { 1073 assert(Info->PrimaryVirtualBaseInfo->IsVirtual && 1074 "Primary virtual base is not virtual!"); 1075 if (Info->PrimaryVirtualBaseInfo->Derived == Info) { 1076 // Add the offset. 1077 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && 1078 "primary vbase offset already exists!"); 1079 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class, 1080 ASTRecordLayout::VBaseInfo(Offset, false))); 1081 1082 // Traverse the primary virtual base. 1083 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset); 1084 } 1085 } 1086 1087 // Now go through all direct non-virtual bases. 1088 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 1089 for (const BaseSubobjectInfo *Base : Info->Bases) { 1090 if (Base->IsVirtual) 1091 continue; 1092 1093 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 1094 AddPrimaryVirtualBaseOffsets(Base, BaseOffset); 1095 } 1096 } 1097 1098 void ItaniumRecordLayoutBuilder::LayoutVirtualBases( 1099 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) { 1100 const CXXRecordDecl *PrimaryBase; 1101 bool PrimaryBaseIsVirtual; 1102 1103 if (MostDerivedClass == RD) { 1104 PrimaryBase = this->PrimaryBase; 1105 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual; 1106 } else { 1107 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1108 PrimaryBase = Layout.getPrimaryBase(); 1109 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual(); 1110 } 1111 1112 for (const CXXBaseSpecifier &Base : RD->bases()) { 1113 assert(!Base.getType()->isDependentType() && 1114 "Cannot layout class with dependent bases."); 1115 1116 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 1117 1118 if (Base.isVirtual()) { 1119 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) { 1120 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl); 1121 1122 // Only lay out the virtual base if it's not an indirect primary base. 1123 if (!IndirectPrimaryBase) { 1124 // Only visit virtual bases once. 1125 if (!VisitedVirtualBases.insert(BaseDecl).second) 1126 continue; 1127 1128 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl); 1129 assert(BaseInfo && "Did not find virtual base info!"); 1130 LayoutVirtualBase(BaseInfo); 1131 } 1132 } 1133 } 1134 1135 if (!BaseDecl->getNumVBases()) { 1136 // This base isn't interesting since it doesn't have any virtual bases. 1137 continue; 1138 } 1139 1140 LayoutVirtualBases(BaseDecl, MostDerivedClass); 1141 } 1142 } 1143 1144 void ItaniumRecordLayoutBuilder::LayoutVirtualBase( 1145 const BaseSubobjectInfo *Base) { 1146 assert(!Base->Derived && "Trying to lay out a primary virtual base!"); 1147 1148 // Layout the base. 1149 CharUnits Offset = LayoutBase(Base); 1150 1151 // Add its base class offset. 1152 assert(!VBases.count(Base->Class) && "vbase offset already exists!"); 1153 VBases.insert(std::make_pair(Base->Class, 1154 ASTRecordLayout::VBaseInfo(Offset, false))); 1155 1156 AddPrimaryVirtualBaseOffsets(Base, Offset); 1157 } 1158 1159 CharUnits 1160 ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { 1161 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class); 1162 1163 1164 CharUnits Offset; 1165 1166 // Query the external layout to see if it provides an offset. 1167 bool HasExternalLayout = false; 1168 if (UseExternalLayout) { 1169 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known; 1170 if (Base->IsVirtual) 1171 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset); 1172 else 1173 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset); 1174 } 1175 1176 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment(); 1177 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign; 1178 1179 // If we have an empty base class, try to place it at offset 0. 1180 if (Base->Class->isEmpty() && 1181 (!HasExternalLayout || Offset == CharUnits::Zero()) && 1182 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) { 1183 setSize(std::max(getSize(), Layout.getSize())); 1184 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 1185 1186 return CharUnits::Zero(); 1187 } 1188 1189 // The maximum field alignment overrides base align. 1190 if (!MaxFieldAlignment.isZero()) { 1191 BaseAlign = std::min(BaseAlign, MaxFieldAlignment); 1192 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment); 1193 } 1194 1195 if (!HasExternalLayout) { 1196 // Round up the current record size to the base's alignment boundary. 1197 Offset = getDataSize().RoundUpToAlignment(BaseAlign); 1198 1199 // Try to place the base. 1200 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset)) 1201 Offset += BaseAlign; 1202 } else { 1203 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset); 1204 (void)Allowed; 1205 assert(Allowed && "Base subobject externally placed at overlapping offset"); 1206 1207 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){ 1208 // The externally-supplied base offset is before the base offset we 1209 // computed. Assume that the structure is packed. 1210 Alignment = CharUnits::One(); 1211 InferAlignment = false; 1212 } 1213 } 1214 1215 if (!Base->Class->isEmpty()) { 1216 // Update the data size. 1217 setDataSize(Offset + Layout.getNonVirtualSize()); 1218 1219 setSize(std::max(getSize(), getDataSize())); 1220 } else 1221 setSize(std::max(getSize(), Offset + Layout.getSize())); 1222 1223 // Remember max struct/class alignment. 1224 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 1225 1226 return Offset; 1227 } 1228 1229 void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) { 1230 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) { 1231 IsUnion = RD->isUnion(); 1232 IsMsStruct = RD->isMsStruct(Context); 1233 } 1234 1235 Packed = D->hasAttr<PackedAttr>(); 1236 1237 // Honor the default struct packing maximum alignment flag. 1238 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) { 1239 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment); 1240 } 1241 1242 // mac68k alignment supersedes maximum field alignment and attribute aligned, 1243 // and forces all structures to have 2-byte alignment. The IBM docs on it 1244 // allude to additional (more complicated) semantics, especially with regard 1245 // to bit-fields, but gcc appears not to follow that. 1246 if (D->hasAttr<AlignMac68kAttr>()) { 1247 IsMac68kAlign = true; 1248 MaxFieldAlignment = CharUnits::fromQuantity(2); 1249 Alignment = CharUnits::fromQuantity(2); 1250 } else { 1251 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>()) 1252 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment()); 1253 1254 if (unsigned MaxAlign = D->getMaxAlignment()) 1255 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign)); 1256 } 1257 1258 // If there is an external AST source, ask it for the various offsets. 1259 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 1260 if (ExternalASTSource *Source = Context.getExternalSource()) { 1261 UseExternalLayout = Source->layoutRecordType( 1262 RD, External.Size, External.Align, External.FieldOffsets, 1263 External.BaseOffsets, External.VirtualBaseOffsets); 1264 1265 // Update based on external alignment. 1266 if (UseExternalLayout) { 1267 if (External.Align > 0) { 1268 Alignment = Context.toCharUnitsFromBits(External.Align); 1269 } else { 1270 // The external source didn't have alignment information; infer it. 1271 InferAlignment = true; 1272 } 1273 } 1274 } 1275 } 1276 1277 void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) { 1278 InitializeLayout(D); 1279 LayoutFields(D); 1280 1281 // Finally, round the size of the total struct up to the alignment of the 1282 // struct itself. 1283 FinishLayout(D); 1284 } 1285 1286 void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) { 1287 InitializeLayout(RD); 1288 1289 // Lay out the vtable and the non-virtual bases. 1290 LayoutNonVirtualBases(RD); 1291 1292 LayoutFields(RD); 1293 1294 NonVirtualSize = Context.toCharUnitsFromBits( 1295 llvm::RoundUpToAlignment(getSizeInBits(), 1296 Context.getTargetInfo().getCharAlign())); 1297 NonVirtualAlignment = Alignment; 1298 1299 // Lay out the virtual bases and add the primary virtual base offsets. 1300 LayoutVirtualBases(RD, RD); 1301 1302 // Finally, round the size of the total struct up to the alignment 1303 // of the struct itself. 1304 FinishLayout(RD); 1305 1306 #ifndef NDEBUG 1307 // Check that we have base offsets for all bases. 1308 for (const CXXBaseSpecifier &Base : RD->bases()) { 1309 if (Base.isVirtual()) 1310 continue; 1311 1312 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 1313 1314 assert(Bases.count(BaseDecl) && "Did not find base offset!"); 1315 } 1316 1317 // And all virtual bases. 1318 for (const CXXBaseSpecifier &Base : RD->vbases()) { 1319 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 1320 1321 assert(VBases.count(BaseDecl) && "Did not find base offset!"); 1322 } 1323 #endif 1324 } 1325 1326 void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) { 1327 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 1328 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD); 1329 1330 UpdateAlignment(SL.getAlignment()); 1331 1332 // We start laying out ivars not at the end of the superclass 1333 // structure, but at the next byte following the last field. 1334 setSize(SL.getDataSize()); 1335 setDataSize(getSize()); 1336 } 1337 1338 InitializeLayout(D); 1339 // Layout each ivar sequentially. 1340 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD; 1341 IVD = IVD->getNextIvar()) 1342 LayoutField(IVD, false); 1343 1344 // Finally, round the size of the total struct up to the alignment of the 1345 // struct itself. 1346 FinishLayout(D); 1347 } 1348 1349 void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) { 1350 // Layout each field, for now, just sequentially, respecting alignment. In 1351 // the future, this will need to be tweakable by targets. 1352 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true); 1353 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember(); 1354 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) { 1355 auto Next(I); 1356 ++Next; 1357 LayoutField(*I, 1358 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember)); 1359 } 1360 } 1361 1362 // Rounds the specified size to have it a multiple of the char size. 1363 static uint64_t 1364 roundUpSizeToCharAlignment(uint64_t Size, 1365 const ASTContext &Context) { 1366 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign(); 1367 return llvm::RoundUpToAlignment(Size, CharAlignment); 1368 } 1369 1370 void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize, 1371 uint64_t TypeSize, 1372 bool FieldPacked, 1373 const FieldDecl *D) { 1374 assert(Context.getLangOpts().CPlusPlus && 1375 "Can only have wide bit-fields in C++!"); 1376 1377 // Itanium C++ ABI 2.4: 1378 // If sizeof(T)*8 < n, let T' be the largest integral POD type with 1379 // sizeof(T')*8 <= n. 1380 1381 QualType IntegralPODTypes[] = { 1382 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy, 1383 Context.UnsignedLongTy, Context.UnsignedLongLongTy 1384 }; 1385 1386 QualType Type; 1387 for (const QualType &QT : IntegralPODTypes) { 1388 uint64_t Size = Context.getTypeSize(QT); 1389 1390 if (Size > FieldSize) 1391 break; 1392 1393 Type = QT; 1394 } 1395 assert(!Type.isNull() && "Did not find a type!"); 1396 1397 CharUnits TypeAlign = Context.getTypeAlignInChars(Type); 1398 1399 // We're not going to use any of the unfilled bits in the last byte. 1400 UnfilledBitsInLastUnit = 0; 1401 LastBitfieldTypeSize = 0; 1402 1403 uint64_t FieldOffset; 1404 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit; 1405 1406 if (IsUnion) { 1407 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, 1408 Context); 1409 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize)); 1410 FieldOffset = 0; 1411 } else { 1412 // The bitfield is allocated starting at the next offset aligned 1413 // appropriately for T', with length n bits. 1414 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(), 1415 Context.toBits(TypeAlign)); 1416 1417 uint64_t NewSizeInBits = FieldOffset + FieldSize; 1418 1419 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1420 Context.getTargetInfo().getCharAlign())); 1421 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits; 1422 } 1423 1424 // Place this field at the current location. 1425 FieldOffsets.push_back(FieldOffset); 1426 1427 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset, 1428 Context.toBits(TypeAlign), FieldPacked, D); 1429 1430 // Update the size. 1431 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1432 1433 // Remember max struct/class alignment. 1434 UpdateAlignment(TypeAlign); 1435 } 1436 1437 void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { 1438 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 1439 uint64_t FieldSize = D->getBitWidthValue(Context); 1440 TypeInfo FieldInfo = Context.getTypeInfo(D->getType()); 1441 uint64_t TypeSize = FieldInfo.Width; 1442 unsigned FieldAlign = FieldInfo.Align; 1443 1444 // UnfilledBitsInLastUnit is the difference between the end of the 1445 // last allocated bitfield (i.e. the first bit offset available for 1446 // bitfields) and the end of the current data size in bits (i.e. the 1447 // first bit offset available for non-bitfields). The current data 1448 // size in bits is always a multiple of the char size; additionally, 1449 // for ms_struct records it's also a multiple of the 1450 // LastBitfieldTypeSize (if set). 1451 1452 // The struct-layout algorithm is dictated by the platform ABI, 1453 // which in principle could use almost any rules it likes. In 1454 // practice, UNIXy targets tend to inherit the algorithm described 1455 // in the System V generic ABI. The basic bitfield layout rule in 1456 // System V is to place bitfields at the next available bit offset 1457 // where the entire bitfield would fit in an aligned storage unit of 1458 // the declared type; it's okay if an earlier or later non-bitfield 1459 // is allocated in the same storage unit. However, some targets 1460 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't 1461 // require this storage unit to be aligned, and therefore always put 1462 // the bitfield at the next available bit offset. 1463 1464 // ms_struct basically requests a complete replacement of the 1465 // platform ABI's struct-layout algorithm, with the high-level goal 1466 // of duplicating MSVC's layout. For non-bitfields, this follows 1467 // the standard algorithm. The basic bitfield layout rule is to 1468 // allocate an entire unit of the bitfield's declared type 1469 // (e.g. 'unsigned long'), then parcel it up among successive 1470 // bitfields whose declared types have the same size, making a new 1471 // unit as soon as the last can no longer store the whole value. 1472 // Since it completely replaces the platform ABI's algorithm, 1473 // settings like !useBitFieldTypeAlignment() do not apply. 1474 1475 // A zero-width bitfield forces the use of a new storage unit for 1476 // later bitfields. In general, this occurs by rounding up the 1477 // current size of the struct as if the algorithm were about to 1478 // place a non-bitfield of the field's formal type. Usually this 1479 // does not change the alignment of the struct itself, but it does 1480 // on some targets (those that useZeroLengthBitfieldAlignment(), 1481 // e.g. ARM). In ms_struct layout, zero-width bitfields are 1482 // ignored unless they follow a non-zero-width bitfield. 1483 1484 // A field alignment restriction (e.g. from #pragma pack) or 1485 // specification (e.g. from __attribute__((aligned))) changes the 1486 // formal alignment of the field. For System V, this alters the 1487 // required alignment of the notional storage unit that must contain 1488 // the bitfield. For ms_struct, this only affects the placement of 1489 // new storage units. In both cases, the effect of #pragma pack is 1490 // ignored on zero-width bitfields. 1491 1492 // On System V, a packed field (e.g. from #pragma pack or 1493 // __attribute__((packed))) always uses the next available bit 1494 // offset. 1495 1496 // In an ms_struct struct, the alignment of a fundamental type is 1497 // always equal to its size. This is necessary in order to mimic 1498 // the i386 alignment rules on targets which might not fully align 1499 // all types (e.g. Darwin PPC32, where alignof(long long) == 4). 1500 1501 // First, some simple bookkeeping to perform for ms_struct structs. 1502 if (IsMsStruct) { 1503 // The field alignment for integer types is always the size. 1504 FieldAlign = TypeSize; 1505 1506 // If the previous field was not a bitfield, or was a bitfield 1507 // with a different storage unit size, we're done with that 1508 // storage unit. 1509 if (LastBitfieldTypeSize != TypeSize) { 1510 // Also, ignore zero-length bitfields after non-bitfields. 1511 if (!LastBitfieldTypeSize && !FieldSize) 1512 FieldAlign = 1; 1513 1514 UnfilledBitsInLastUnit = 0; 1515 LastBitfieldTypeSize = 0; 1516 } 1517 } 1518 1519 // If the field is wider than its declared type, it follows 1520 // different rules in all cases. 1521 if (FieldSize > TypeSize) { 1522 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D); 1523 return; 1524 } 1525 1526 // Compute the next available bit offset. 1527 uint64_t FieldOffset = 1528 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit); 1529 1530 // Handle targets that don't honor bitfield type alignment. 1531 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) { 1532 // Some such targets do honor it on zero-width bitfields. 1533 if (FieldSize == 0 && 1534 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) { 1535 // The alignment to round up to is the max of the field's natural 1536 // alignment and a target-specific fixed value (sometimes zero). 1537 unsigned ZeroLengthBitfieldBoundary = 1538 Context.getTargetInfo().getZeroLengthBitfieldBoundary(); 1539 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary); 1540 1541 // If that doesn't apply, just ignore the field alignment. 1542 } else { 1543 FieldAlign = 1; 1544 } 1545 } 1546 1547 // Remember the alignment we would have used if the field were not packed. 1548 unsigned UnpackedFieldAlign = FieldAlign; 1549 1550 // Ignore the field alignment if the field is packed unless it has zero-size. 1551 if (!IsMsStruct && FieldPacked && FieldSize != 0) 1552 FieldAlign = 1; 1553 1554 // But, if there's an 'aligned' attribute on the field, honor that. 1555 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) { 1556 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign); 1557 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign); 1558 } 1559 1560 // But, if there's a #pragma pack in play, that takes precedent over 1561 // even the 'aligned' attribute, for non-zero-width bitfields. 1562 if (!MaxFieldAlignment.isZero() && FieldSize) { 1563 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment); 1564 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits); 1565 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits); 1566 } 1567 1568 // But, ms_struct just ignores all of that in unions, even explicit 1569 // alignment attributes. 1570 if (IsMsStruct && IsUnion) { 1571 FieldAlign = UnpackedFieldAlign = 1; 1572 } 1573 1574 // For purposes of diagnostics, we're going to simultaneously 1575 // compute the field offsets that we would have used if we weren't 1576 // adding any alignment padding or if the field weren't packed. 1577 uint64_t UnpaddedFieldOffset = FieldOffset; 1578 uint64_t UnpackedFieldOffset = FieldOffset; 1579 1580 // Check if we need to add padding to fit the bitfield within an 1581 // allocation unit with the right size and alignment. The rules are 1582 // somewhat different here for ms_struct structs. 1583 if (IsMsStruct) { 1584 // If it's not a zero-width bitfield, and we can fit the bitfield 1585 // into the active storage unit (and we haven't already decided to 1586 // start a new storage unit), just do so, regardless of any other 1587 // other consideration. Otherwise, round up to the right alignment. 1588 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) { 1589 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign); 1590 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset, 1591 UnpackedFieldAlign); 1592 UnfilledBitsInLastUnit = 0; 1593 } 1594 1595 } else { 1596 // #pragma pack, with any value, suppresses the insertion of padding. 1597 bool AllowPadding = MaxFieldAlignment.isZero(); 1598 1599 // Compute the real offset. 1600 if (FieldSize == 0 || 1601 (AllowPadding && 1602 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) { 1603 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign); 1604 } 1605 1606 // Repeat the computation for diagnostic purposes. 1607 if (FieldSize == 0 || 1608 (AllowPadding && 1609 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize)) 1610 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset, 1611 UnpackedFieldAlign); 1612 } 1613 1614 // If we're using external layout, give the external layout a chance 1615 // to override this information. 1616 if (UseExternalLayout) 1617 FieldOffset = updateExternalFieldOffset(D, FieldOffset); 1618 1619 // Okay, place the bitfield at the calculated offset. 1620 FieldOffsets.push_back(FieldOffset); 1621 1622 // Bookkeeping: 1623 1624 // Anonymous members don't affect the overall record alignment, 1625 // except on targets where they do. 1626 if (!IsMsStruct && 1627 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() && 1628 !D->getIdentifier()) 1629 FieldAlign = UnpackedFieldAlign = 1; 1630 1631 // Diagnose differences in layout due to padding or packing. 1632 if (!UseExternalLayout) 1633 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset, 1634 UnpackedFieldAlign, FieldPacked, D); 1635 1636 // Update DataSize to include the last byte containing (part of) the bitfield. 1637 1638 // For unions, this is just a max operation, as usual. 1639 if (IsUnion) { 1640 // For ms_struct, allocate the entire storage unit --- unless this 1641 // is a zero-width bitfield, in which case just use a size of 1. 1642 uint64_t RoundedFieldSize; 1643 if (IsMsStruct) { 1644 RoundedFieldSize = 1645 (FieldSize ? TypeSize : Context.getTargetInfo().getCharWidth()); 1646 1647 // Otherwise, allocate just the number of bytes required to store 1648 // the bitfield. 1649 } else { 1650 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context); 1651 } 1652 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize)); 1653 1654 // For non-zero-width bitfields in ms_struct structs, allocate a new 1655 // storage unit if necessary. 1656 } else if (IsMsStruct && FieldSize) { 1657 // We should have cleared UnfilledBitsInLastUnit in every case 1658 // where we changed storage units. 1659 if (!UnfilledBitsInLastUnit) { 1660 setDataSize(FieldOffset + TypeSize); 1661 UnfilledBitsInLastUnit = TypeSize; 1662 } 1663 UnfilledBitsInLastUnit -= FieldSize; 1664 LastBitfieldTypeSize = TypeSize; 1665 1666 // Otherwise, bump the data size up to include the bitfield, 1667 // including padding up to char alignment, and then remember how 1668 // bits we didn't use. 1669 } else { 1670 uint64_t NewSizeInBits = FieldOffset + FieldSize; 1671 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign(); 1672 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment)); 1673 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits; 1674 1675 // The only time we can get here for an ms_struct is if this is a 1676 // zero-width bitfield, which doesn't count as anything for the 1677 // purposes of unfilled bits. 1678 LastBitfieldTypeSize = 0; 1679 } 1680 1681 // Update the size. 1682 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1683 1684 // Remember max struct/class alignment. 1685 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), 1686 Context.toCharUnitsFromBits(UnpackedFieldAlign)); 1687 } 1688 1689 void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, 1690 bool InsertExtraPadding) { 1691 if (D->isBitField()) { 1692 LayoutBitField(D); 1693 return; 1694 } 1695 1696 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit; 1697 1698 // Reset the unfilled bits. 1699 UnfilledBitsInLastUnit = 0; 1700 LastBitfieldTypeSize = 0; 1701 1702 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 1703 CharUnits FieldOffset = 1704 IsUnion ? CharUnits::Zero() : getDataSize(); 1705 CharUnits FieldSize; 1706 CharUnits FieldAlign; 1707 1708 if (D->getType()->isIncompleteArrayType()) { 1709 // This is a flexible array member; we can't directly 1710 // query getTypeInfo about these, so we figure it out here. 1711 // Flexible array members don't have any size, but they 1712 // have to be aligned appropriately for their element type. 1713 FieldSize = CharUnits::Zero(); 1714 const ArrayType* ATy = Context.getAsArrayType(D->getType()); 1715 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType()); 1716 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) { 1717 unsigned AS = RT->getPointeeType().getAddressSpace(); 1718 FieldSize = 1719 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS)); 1720 FieldAlign = 1721 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS)); 1722 } else { 1723 std::pair<CharUnits, CharUnits> FieldInfo = 1724 Context.getTypeInfoInChars(D->getType()); 1725 FieldSize = FieldInfo.first; 1726 FieldAlign = FieldInfo.second; 1727 1728 if (IsMsStruct) { 1729 // If MS bitfield layout is required, figure out what type is being 1730 // laid out and align the field to the width of that type. 1731 1732 // Resolve all typedefs down to their base type and round up the field 1733 // alignment if necessary. 1734 QualType T = Context.getBaseElementType(D->getType()); 1735 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) { 1736 CharUnits TypeSize = Context.getTypeSizeInChars(BTy); 1737 if (TypeSize > FieldAlign) 1738 FieldAlign = TypeSize; 1739 } 1740 } 1741 } 1742 1743 // The align if the field is not packed. This is to check if the attribute 1744 // was unnecessary (-Wpacked). 1745 CharUnits UnpackedFieldAlign = FieldAlign; 1746 CharUnits UnpackedFieldOffset = FieldOffset; 1747 1748 if (FieldPacked) 1749 FieldAlign = CharUnits::One(); 1750 CharUnits MaxAlignmentInChars = 1751 Context.toCharUnitsFromBits(D->getMaxAlignment()); 1752 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars); 1753 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars); 1754 1755 // The maximum field alignment overrides the aligned attribute. 1756 if (!MaxFieldAlignment.isZero()) { 1757 FieldAlign = std::min(FieldAlign, MaxFieldAlignment); 1758 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment); 1759 } 1760 1761 // Round up the current record size to the field's alignment boundary. 1762 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign); 1763 UnpackedFieldOffset = 1764 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign); 1765 1766 if (UseExternalLayout) { 1767 FieldOffset = Context.toCharUnitsFromBits( 1768 updateExternalFieldOffset(D, Context.toBits(FieldOffset))); 1769 1770 if (!IsUnion && EmptySubobjects) { 1771 // Record the fact that we're placing a field at this offset. 1772 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset); 1773 (void)Allowed; 1774 assert(Allowed && "Externally-placed field cannot be placed here"); 1775 } 1776 } else { 1777 if (!IsUnion && EmptySubobjects) { 1778 // Check if we can place the field at this offset. 1779 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) { 1780 // We couldn't place the field at the offset. Try again at a new offset. 1781 FieldOffset += FieldAlign; 1782 } 1783 } 1784 } 1785 1786 // Place this field at the current location. 1787 FieldOffsets.push_back(Context.toBits(FieldOffset)); 1788 1789 if (!UseExternalLayout) 1790 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, 1791 Context.toBits(UnpackedFieldOffset), 1792 Context.toBits(UnpackedFieldAlign), FieldPacked, D); 1793 1794 if (InsertExtraPadding) { 1795 CharUnits ASanAlignment = CharUnits::fromQuantity(8); 1796 CharUnits ExtraSizeForAsan = ASanAlignment; 1797 if (FieldSize % ASanAlignment) 1798 ExtraSizeForAsan += 1799 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment); 1800 FieldSize += ExtraSizeForAsan; 1801 } 1802 1803 // Reserve space for this field. 1804 uint64_t FieldSizeInBits = Context.toBits(FieldSize); 1805 if (IsUnion) 1806 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits)); 1807 else 1808 setDataSize(FieldOffset + FieldSize); 1809 1810 // Update the size. 1811 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1812 1813 // Remember max struct/class alignment. 1814 UpdateAlignment(FieldAlign, UnpackedFieldAlign); 1815 } 1816 1817 void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) { 1818 // In C++, records cannot be of size 0. 1819 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) { 1820 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 1821 // Compatibility with gcc requires a class (pod or non-pod) 1822 // which is not empty but of size 0; such as having fields of 1823 // array of zero-length, remains of Size 0 1824 if (RD->isEmpty()) 1825 setSize(CharUnits::One()); 1826 } 1827 else 1828 setSize(CharUnits::One()); 1829 } 1830 1831 // Finally, round the size of the record up to the alignment of the 1832 // record itself. 1833 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit; 1834 uint64_t UnpackedSizeInBits = 1835 llvm::RoundUpToAlignment(getSizeInBits(), 1836 Context.toBits(UnpackedAlignment)); 1837 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits); 1838 uint64_t RoundedSize 1839 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment)); 1840 1841 if (UseExternalLayout) { 1842 // If we're inferring alignment, and the external size is smaller than 1843 // our size after we've rounded up to alignment, conservatively set the 1844 // alignment to 1. 1845 if (InferAlignment && External.Size < RoundedSize) { 1846 Alignment = CharUnits::One(); 1847 InferAlignment = false; 1848 } 1849 setSize(External.Size); 1850 return; 1851 } 1852 1853 // Set the size to the final size. 1854 setSize(RoundedSize); 1855 1856 unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); 1857 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) { 1858 // Warn if padding was introduced to the struct/class/union. 1859 if (getSizeInBits() > UnpaddedSize) { 1860 unsigned PadSize = getSizeInBits() - UnpaddedSize; 1861 bool InBits = true; 1862 if (PadSize % CharBitNum == 0) { 1863 PadSize = PadSize / CharBitNum; 1864 InBits = false; 1865 } 1866 Diag(RD->getLocation(), diag::warn_padded_struct_size) 1867 << Context.getTypeDeclType(RD) 1868 << PadSize 1869 << (InBits ? 1 : 0); // (byte|bit) 1870 } 1871 1872 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't 1873 // bother since there won't be alignment issues. 1874 if (Packed && UnpackedAlignment > CharUnits::One() && 1875 getSize() == UnpackedSize) 1876 Diag(D->getLocation(), diag::warn_unnecessary_packed) 1877 << Context.getTypeDeclType(RD); 1878 } 1879 } 1880 1881 void ItaniumRecordLayoutBuilder::UpdateAlignment( 1882 CharUnits NewAlignment, CharUnits UnpackedNewAlignment) { 1883 // The alignment is not modified when using 'mac68k' alignment or when 1884 // we have an externally-supplied layout that also provides overall alignment. 1885 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment)) 1886 return; 1887 1888 if (NewAlignment > Alignment) { 1889 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) && 1890 "Alignment not a power of 2"); 1891 Alignment = NewAlignment; 1892 } 1893 1894 if (UnpackedNewAlignment > UnpackedAlignment) { 1895 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) && 1896 "Alignment not a power of 2"); 1897 UnpackedAlignment = UnpackedNewAlignment; 1898 } 1899 } 1900 1901 uint64_t 1902 ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, 1903 uint64_t ComputedOffset) { 1904 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field); 1905 1906 if (InferAlignment && ExternalFieldOffset < ComputedOffset) { 1907 // The externally-supplied field offset is before the field offset we 1908 // computed. Assume that the structure is packed. 1909 Alignment = CharUnits::One(); 1910 InferAlignment = false; 1911 } 1912 1913 // Use the externally-supplied field offset. 1914 return ExternalFieldOffset; 1915 } 1916 1917 /// \brief Get diagnostic %select index for tag kind for 1918 /// field padding diagnostic message. 1919 /// WARNING: Indexes apply to particular diagnostics only! 1920 /// 1921 /// \returns diagnostic %select index. 1922 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) { 1923 switch (Tag) { 1924 case TTK_Struct: return 0; 1925 case TTK_Interface: return 1; 1926 case TTK_Class: return 2; 1927 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!"); 1928 } 1929 } 1930 1931 void ItaniumRecordLayoutBuilder::CheckFieldPadding( 1932 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset, 1933 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) { 1934 // We let objc ivars without warning, objc interfaces generally are not used 1935 // for padding tricks. 1936 if (isa<ObjCIvarDecl>(D)) 1937 return; 1938 1939 // Don't warn about structs created without a SourceLocation. This can 1940 // be done by clients of the AST, such as codegen. 1941 if (D->getLocation().isInvalid()) 1942 return; 1943 1944 unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); 1945 1946 // Warn if padding was introduced to the struct/class. 1947 if (!IsUnion && Offset > UnpaddedOffset) { 1948 unsigned PadSize = Offset - UnpaddedOffset; 1949 bool InBits = true; 1950 if (PadSize % CharBitNum == 0) { 1951 PadSize = PadSize / CharBitNum; 1952 InBits = false; 1953 } 1954 if (D->getIdentifier()) 1955 Diag(D->getLocation(), diag::warn_padded_struct_field) 1956 << getPaddingDiagFromTagKind(D->getParent()->getTagKind()) 1957 << Context.getTypeDeclType(D->getParent()) 1958 << PadSize 1959 << (InBits ? 1 : 0) // (byte|bit) 1960 << D->getIdentifier(); 1961 else 1962 Diag(D->getLocation(), diag::warn_padded_struct_anon_field) 1963 << getPaddingDiagFromTagKind(D->getParent()->getTagKind()) 1964 << Context.getTypeDeclType(D->getParent()) 1965 << PadSize 1966 << (InBits ? 1 : 0); // (byte|bit) 1967 } 1968 1969 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't 1970 // bother since there won't be alignment issues. 1971 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset) 1972 Diag(D->getLocation(), diag::warn_unnecessary_packed) 1973 << D->getIdentifier(); 1974 } 1975 1976 static const CXXMethodDecl *computeKeyFunction(ASTContext &Context, 1977 const CXXRecordDecl *RD) { 1978 // If a class isn't polymorphic it doesn't have a key function. 1979 if (!RD->isPolymorphic()) 1980 return nullptr; 1981 1982 // A class that is not externally visible doesn't have a key function. (Or 1983 // at least, there's no point to assigning a key function to such a class; 1984 // this doesn't affect the ABI.) 1985 if (!RD->isExternallyVisible()) 1986 return nullptr; 1987 1988 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6. 1989 // Same behavior as GCC. 1990 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind(); 1991 if (TSK == TSK_ImplicitInstantiation || 1992 TSK == TSK_ExplicitInstantiationDeclaration || 1993 TSK == TSK_ExplicitInstantiationDefinition) 1994 return nullptr; 1995 1996 bool allowInlineFunctions = 1997 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline(); 1998 1999 for (const CXXMethodDecl *MD : RD->methods()) { 2000 if (!MD->isVirtual()) 2001 continue; 2002 2003 if (MD->isPure()) 2004 continue; 2005 2006 // Ignore implicit member functions, they are always marked as inline, but 2007 // they don't have a body until they're defined. 2008 if (MD->isImplicit()) 2009 continue; 2010 2011 if (MD->isInlineSpecified()) 2012 continue; 2013 2014 if (MD->hasInlineBody()) 2015 continue; 2016 2017 // Ignore inline deleted or defaulted functions. 2018 if (!MD->isUserProvided()) 2019 continue; 2020 2021 // In certain ABIs, ignore functions with out-of-line inline definitions. 2022 if (!allowInlineFunctions) { 2023 const FunctionDecl *Def; 2024 if (MD->hasBody(Def) && Def->isInlineSpecified()) 2025 continue; 2026 } 2027 2028 if (Context.getLangOpts().CUDA) { 2029 // While compiler may see key method in this TU, during CUDA 2030 // compilation we should ignore methods that are not accessible 2031 // on this side of compilation. 2032 if (Context.getLangOpts().CUDAIsDevice) { 2033 // In device mode ignore methods without __device__ attribute. 2034 if (!MD->hasAttr<CUDADeviceAttr>()) 2035 continue; 2036 } else { 2037 // In host mode ignore __device__-only methods. 2038 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>()) 2039 continue; 2040 } 2041 } 2042 2043 // If the key function is dllimport but the class isn't, then the class has 2044 // no key function. The DLL that exports the key function won't export the 2045 // vtable in this case. 2046 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>()) 2047 return nullptr; 2048 2049 // We found it. 2050 return MD; 2051 } 2052 2053 return nullptr; 2054 } 2055 2056 DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc, 2057 unsigned DiagID) { 2058 return Context.getDiagnostics().Report(Loc, DiagID); 2059 } 2060 2061 /// Does the target C++ ABI require us to skip over the tail-padding 2062 /// of the given class (considering it as a base class) when allocating 2063 /// objects? 2064 static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) { 2065 switch (ABI.getTailPaddingUseRules()) { 2066 case TargetCXXABI::AlwaysUseTailPadding: 2067 return false; 2068 2069 case TargetCXXABI::UseTailPaddingUnlessPOD03: 2070 // FIXME: To the extent that this is meant to cover the Itanium ABI 2071 // rules, we should implement the restrictions about over-sized 2072 // bitfields: 2073 // 2074 // http://mentorembedded.github.com/cxx-abi/abi.html#POD : 2075 // In general, a type is considered a POD for the purposes of 2076 // layout if it is a POD type (in the sense of ISO C++ 2077 // [basic.types]). However, a POD-struct or POD-union (in the 2078 // sense of ISO C++ [class]) with a bitfield member whose 2079 // declared width is wider than the declared type of the 2080 // bitfield is not a POD for the purpose of layout. Similarly, 2081 // an array type is not a POD for the purpose of layout if the 2082 // element type of the array is not a POD for the purpose of 2083 // layout. 2084 // 2085 // Where references to the ISO C++ are made in this paragraph, 2086 // the Technical Corrigendum 1 version of the standard is 2087 // intended. 2088 return RD->isPOD(); 2089 2090 case TargetCXXABI::UseTailPaddingUnlessPOD11: 2091 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(), 2092 // but with a lot of abstraction penalty stripped off. This does 2093 // assume that these properties are set correctly even in C++98 2094 // mode; fortunately, that is true because we want to assign 2095 // consistently semantics to the type-traits intrinsics (or at 2096 // least as many of them as possible). 2097 return RD->isTrivial() && RD->isStandardLayout(); 2098 } 2099 2100 llvm_unreachable("bad tail-padding use kind"); 2101 } 2102 2103 static bool isMsLayout(const ASTContext &Context) { 2104 return Context.getTargetInfo().getCXXABI().isMicrosoft(); 2105 } 2106 2107 // This section contains an implementation of struct layout that is, up to the 2108 // included tests, compatible with cl.exe (2013). The layout produced is 2109 // significantly different than those produced by the Itanium ABI. Here we note 2110 // the most important differences. 2111 // 2112 // * The alignment of bitfields in unions is ignored when computing the 2113 // alignment of the union. 2114 // * The existence of zero-width bitfield that occurs after anything other than 2115 // a non-zero length bitfield is ignored. 2116 // * There is no explicit primary base for the purposes of layout. All bases 2117 // with vfptrs are laid out first, followed by all bases without vfptrs. 2118 // * The Itanium equivalent vtable pointers are split into a vfptr (virtual 2119 // function pointer) and a vbptr (virtual base pointer). They can each be 2120 // shared with a, non-virtual bases. These bases need not be the same. vfptrs 2121 // always occur at offset 0. vbptrs can occur at an arbitrary offset and are 2122 // placed after the lexiographically last non-virtual base. This placement 2123 // is always before fields but can be in the middle of the non-virtual bases 2124 // due to the two-pass layout scheme for non-virtual-bases. 2125 // * Virtual bases sometimes require a 'vtordisp' field that is laid out before 2126 // the virtual base and is used in conjunction with virtual overrides during 2127 // construction and destruction. This is always a 4 byte value and is used as 2128 // an alternative to constructor vtables. 2129 // * vtordisps are allocated in a block of memory with size and alignment equal 2130 // to the alignment of the completed structure (before applying __declspec( 2131 // align())). The vtordisp always occur at the end of the allocation block, 2132 // immediately prior to the virtual base. 2133 // * vfptrs are injected after all bases and fields have been laid out. In 2134 // order to guarantee proper alignment of all fields, the vfptr injection 2135 // pushes all bases and fields back by the alignment imposed by those bases 2136 // and fields. This can potentially add a significant amount of padding. 2137 // vfptrs are always injected at offset 0. 2138 // * vbptrs are injected after all bases and fields have been laid out. In 2139 // order to guarantee proper alignment of all fields, the vfptr injection 2140 // pushes all bases and fields back by the alignment imposed by those bases 2141 // and fields. This can potentially add a significant amount of padding. 2142 // vbptrs are injected immediately after the last non-virtual base as 2143 // lexiographically ordered in the code. If this site isn't pointer aligned 2144 // the vbptr is placed at the next properly aligned location. Enough padding 2145 // is added to guarantee a fit. 2146 // * The last zero sized non-virtual base can be placed at the end of the 2147 // struct (potentially aliasing another object), or may alias with the first 2148 // field, even if they are of the same type. 2149 // * The last zero size virtual base may be placed at the end of the struct 2150 // potentially aliasing another object. 2151 // * The ABI attempts to avoid aliasing of zero sized bases by adding padding 2152 // between bases or vbases with specific properties. The criteria for 2153 // additional padding between two bases is that the first base is zero sized 2154 // or ends with a zero sized subobject and the second base is zero sized or 2155 // trails with a zero sized base or field (sharing of vfptrs can reorder the 2156 // layout of the so the leading base is not always the first one declared). 2157 // This rule does take into account fields that are not records, so padding 2158 // will occur even if the last field is, e.g. an int. The padding added for 2159 // bases is 1 byte. The padding added between vbases depends on the alignment 2160 // of the object but is at least 4 bytes (in both 32 and 64 bit modes). 2161 // * There is no concept of non-virtual alignment, non-virtual alignment and 2162 // alignment are always identical. 2163 // * There is a distinction between alignment and required alignment. 2164 // __declspec(align) changes the required alignment of a struct. This 2165 // alignment is _always_ obeyed, even in the presence of #pragma pack. A 2166 // record inherits required alignment from all of its fields and bases. 2167 // * __declspec(align) on bitfields has the effect of changing the bitfield's 2168 // alignment instead of its required alignment. This is the only known way 2169 // to make the alignment of a struct bigger than 8. Interestingly enough 2170 // this alignment is also immune to the effects of #pragma pack and can be 2171 // used to create structures with large alignment under #pragma pack. 2172 // However, because it does not impact required alignment, such a structure, 2173 // when used as a field or base, will not be aligned if #pragma pack is 2174 // still active at the time of use. 2175 // 2176 // Known incompatibilities: 2177 // * all: #pragma pack between fields in a record 2178 // * 2010 and back: If the last field in a record is a bitfield, every object 2179 // laid out after the record will have extra padding inserted before it. The 2180 // extra padding will have size equal to the size of the storage class of the 2181 // bitfield. 0 sized bitfields don't exhibit this behavior and the extra 2182 // padding can be avoided by adding a 0 sized bitfield after the non-zero- 2183 // sized bitfield. 2184 // * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or 2185 // greater due to __declspec(align()) then a second layout phase occurs after 2186 // The locations of the vf and vb pointers are known. This layout phase 2187 // suffers from the "last field is a bitfield" bug in 2010 and results in 2188 // _every_ field getting padding put in front of it, potentially including the 2189 // vfptr, leaving the vfprt at a non-zero location which results in a fault if 2190 // anything tries to read the vftbl. The second layout phase also treats 2191 // bitfields as separate entities and gives them each storage rather than 2192 // packing them. Additionally, because this phase appears to perform a 2193 // (an unstable) sort on the members before laying them out and because merged 2194 // bitfields have the same address, the bitfields end up in whatever order 2195 // the sort left them in, a behavior we could never hope to replicate. 2196 2197 namespace { 2198 struct MicrosoftRecordLayoutBuilder { 2199 struct ElementInfo { 2200 CharUnits Size; 2201 CharUnits Alignment; 2202 }; 2203 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy; 2204 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {} 2205 private: 2206 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete; 2207 void operator=(const MicrosoftRecordLayoutBuilder &) = delete; 2208 public: 2209 void layout(const RecordDecl *RD); 2210 void cxxLayout(const CXXRecordDecl *RD); 2211 /// \brief Initializes size and alignment and honors some flags. 2212 void initializeLayout(const RecordDecl *RD); 2213 /// \brief Initialized C++ layout, compute alignment and virtual alignment and 2214 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is 2215 /// laid out. 2216 void initializeCXXLayout(const CXXRecordDecl *RD); 2217 void layoutNonVirtualBases(const CXXRecordDecl *RD); 2218 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl, 2219 const ASTRecordLayout &BaseLayout, 2220 const ASTRecordLayout *&PreviousBaseLayout); 2221 void injectVFPtr(const CXXRecordDecl *RD); 2222 void injectVBPtr(const CXXRecordDecl *RD); 2223 /// \brief Lays out the fields of the record. Also rounds size up to 2224 /// alignment. 2225 void layoutFields(const RecordDecl *RD); 2226 void layoutField(const FieldDecl *FD); 2227 void layoutBitField(const FieldDecl *FD); 2228 /// \brief Lays out a single zero-width bit-field in the record and handles 2229 /// special cases associated with zero-width bit-fields. 2230 void layoutZeroWidthBitField(const FieldDecl *FD); 2231 void layoutVirtualBases(const CXXRecordDecl *RD); 2232 void finalizeLayout(const RecordDecl *RD); 2233 /// \brief Gets the size and alignment of a base taking pragma pack and 2234 /// __declspec(align) into account. 2235 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout); 2236 /// \brief Gets the size and alignment of a field taking pragma pack and 2237 /// __declspec(align) into account. It also updates RequiredAlignment as a 2238 /// side effect because it is most convenient to do so here. 2239 ElementInfo getAdjustedElementInfo(const FieldDecl *FD); 2240 /// \brief Places a field at an offset in CharUnits. 2241 void placeFieldAtOffset(CharUnits FieldOffset) { 2242 FieldOffsets.push_back(Context.toBits(FieldOffset)); 2243 } 2244 /// \brief Places a bitfield at a bit offset. 2245 void placeFieldAtBitOffset(uint64_t FieldOffset) { 2246 FieldOffsets.push_back(FieldOffset); 2247 } 2248 /// \brief Compute the set of virtual bases for which vtordisps are required. 2249 void computeVtorDispSet( 2250 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet, 2251 const CXXRecordDecl *RD) const; 2252 const ASTContext &Context; 2253 /// \brief The size of the record being laid out. 2254 CharUnits Size; 2255 /// \brief The non-virtual size of the record layout. 2256 CharUnits NonVirtualSize; 2257 /// \brief The data size of the record layout. 2258 CharUnits DataSize; 2259 /// \brief The current alignment of the record layout. 2260 CharUnits Alignment; 2261 /// \brief The maximum allowed field alignment. This is set by #pragma pack. 2262 CharUnits MaxFieldAlignment; 2263 /// \brief The alignment that this record must obey. This is imposed by 2264 /// __declspec(align()) on the record itself or one of its fields or bases. 2265 CharUnits RequiredAlignment; 2266 /// \brief The size of the allocation of the currently active bitfield. 2267 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield 2268 /// is true. 2269 CharUnits CurrentBitfieldSize; 2270 /// \brief Offset to the virtual base table pointer (if one exists). 2271 CharUnits VBPtrOffset; 2272 /// \brief Minimum record size possible. 2273 CharUnits MinEmptyStructSize; 2274 /// \brief The size and alignment info of a pointer. 2275 ElementInfo PointerInfo; 2276 /// \brief The primary base class (if one exists). 2277 const CXXRecordDecl *PrimaryBase; 2278 /// \brief The class we share our vb-pointer with. 2279 const CXXRecordDecl *SharedVBPtrBase; 2280 /// \brief The collection of field offsets. 2281 SmallVector<uint64_t, 16> FieldOffsets; 2282 /// \brief Base classes and their offsets in the record. 2283 BaseOffsetsMapTy Bases; 2284 /// \brief virtual base classes and their offsets in the record. 2285 ASTRecordLayout::VBaseOffsetsMapTy VBases; 2286 /// \brief The number of remaining bits in our last bitfield allocation. 2287 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is 2288 /// true. 2289 unsigned RemainingBitsInField; 2290 bool IsUnion : 1; 2291 /// \brief True if the last field laid out was a bitfield and was not 0 2292 /// width. 2293 bool LastFieldIsNonZeroWidthBitfield : 1; 2294 /// \brief True if the class has its own vftable pointer. 2295 bool HasOwnVFPtr : 1; 2296 /// \brief True if the class has a vbtable pointer. 2297 bool HasVBPtr : 1; 2298 /// \brief True if the last sub-object within the type is zero sized or the 2299 /// object itself is zero sized. This *does not* count members that are not 2300 /// records. Only used for MS-ABI. 2301 bool EndsWithZeroSizedObject : 1; 2302 /// \brief True if this class is zero sized or first base is zero sized or 2303 /// has this property. Only used for MS-ABI. 2304 bool LeadsWithZeroSizedBase : 1; 2305 2306 /// \brief True if the external AST source provided a layout for this record. 2307 bool UseExternalLayout : 1; 2308 2309 /// \brief The layout provided by the external AST source. Only active if 2310 /// UseExternalLayout is true. 2311 ExternalLayout External; 2312 }; 2313 } // namespace 2314 2315 MicrosoftRecordLayoutBuilder::ElementInfo 2316 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo( 2317 const ASTRecordLayout &Layout) { 2318 ElementInfo Info; 2319 Info.Alignment = Layout.getAlignment(); 2320 // Respect pragma pack. 2321 if (!MaxFieldAlignment.isZero()) 2322 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment); 2323 // Track zero-sized subobjects here where it's already available. 2324 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject(); 2325 // Respect required alignment, this is necessary because we may have adjusted 2326 // the alignment in the case of pragam pack. Note that the required alignment 2327 // doesn't actually apply to the struct alignment at this point. 2328 Alignment = std::max(Alignment, Info.Alignment); 2329 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment()); 2330 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment()); 2331 Info.Size = Layout.getNonVirtualSize(); 2332 return Info; 2333 } 2334 2335 MicrosoftRecordLayoutBuilder::ElementInfo 2336 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo( 2337 const FieldDecl *FD) { 2338 // Get the alignment of the field type's natural alignment, ignore any 2339 // alignment attributes. 2340 ElementInfo Info; 2341 std::tie(Info.Size, Info.Alignment) = 2342 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType()); 2343 // Respect align attributes on the field. 2344 CharUnits FieldRequiredAlignment = 2345 Context.toCharUnitsFromBits(FD->getMaxAlignment()); 2346 // Respect align attributes on the type. 2347 if (Context.isAlignmentRequired(FD->getType())) 2348 FieldRequiredAlignment = std::max( 2349 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment); 2350 // Respect attributes applied to subobjects of the field. 2351 if (FD->isBitField()) 2352 // For some reason __declspec align impacts alignment rather than required 2353 // alignment when it is applied to bitfields. 2354 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment); 2355 else { 2356 if (auto RT = 2357 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 2358 auto const &Layout = Context.getASTRecordLayout(RT->getDecl()); 2359 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject(); 2360 FieldRequiredAlignment = std::max(FieldRequiredAlignment, 2361 Layout.getRequiredAlignment()); 2362 } 2363 // Capture required alignment as a side-effect. 2364 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment); 2365 } 2366 // Respect pragma pack, attribute pack and declspec align 2367 if (!MaxFieldAlignment.isZero()) 2368 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment); 2369 if (FD->hasAttr<PackedAttr>()) 2370 Info.Alignment = CharUnits::One(); 2371 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment); 2372 return Info; 2373 } 2374 2375 void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) { 2376 // For C record layout, zero-sized records always have size 4. 2377 MinEmptyStructSize = CharUnits::fromQuantity(4); 2378 initializeLayout(RD); 2379 layoutFields(RD); 2380 DataSize = Size = Size.RoundUpToAlignment(Alignment); 2381 RequiredAlignment = std::max( 2382 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment())); 2383 finalizeLayout(RD); 2384 } 2385 2386 void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) { 2387 // The C++ standard says that empty structs have size 1. 2388 MinEmptyStructSize = CharUnits::One(); 2389 initializeLayout(RD); 2390 initializeCXXLayout(RD); 2391 layoutNonVirtualBases(RD); 2392 layoutFields(RD); 2393 injectVBPtr(RD); 2394 injectVFPtr(RD); 2395 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase)) 2396 Alignment = std::max(Alignment, PointerInfo.Alignment); 2397 auto RoundingAlignment = Alignment; 2398 if (!MaxFieldAlignment.isZero()) 2399 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment); 2400 NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment); 2401 RequiredAlignment = std::max( 2402 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment())); 2403 layoutVirtualBases(RD); 2404 finalizeLayout(RD); 2405 } 2406 2407 void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) { 2408 IsUnion = RD->isUnion(); 2409 Size = CharUnits::Zero(); 2410 Alignment = CharUnits::One(); 2411 // In 64-bit mode we always perform an alignment step after laying out vbases. 2412 // In 32-bit mode we do not. The check to see if we need to perform alignment 2413 // checks the RequiredAlignment field and performs alignment if it isn't 0. 2414 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit() 2415 ? CharUnits::One() 2416 : CharUnits::Zero(); 2417 // Compute the maximum field alignment. 2418 MaxFieldAlignment = CharUnits::Zero(); 2419 // Honor the default struct packing maximum alignment flag. 2420 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) 2421 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment); 2422 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger 2423 // than the pointer size. 2424 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){ 2425 unsigned PackedAlignment = MFAA->getAlignment(); 2426 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0)) 2427 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment); 2428 } 2429 // Packed attribute forces max field alignment to be 1. 2430 if (RD->hasAttr<PackedAttr>()) 2431 MaxFieldAlignment = CharUnits::One(); 2432 2433 // Try to respect the external layout if present. 2434 UseExternalLayout = false; 2435 if (ExternalASTSource *Source = Context.getExternalSource()) 2436 UseExternalLayout = Source->layoutRecordType( 2437 RD, External.Size, External.Align, External.FieldOffsets, 2438 External.BaseOffsets, External.VirtualBaseOffsets); 2439 } 2440 2441 void 2442 MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) { 2443 EndsWithZeroSizedObject = false; 2444 LeadsWithZeroSizedBase = false; 2445 HasOwnVFPtr = false; 2446 HasVBPtr = false; 2447 PrimaryBase = nullptr; 2448 SharedVBPtrBase = nullptr; 2449 // Calculate pointer size and alignment. These are used for vfptr and vbprt 2450 // injection. 2451 PointerInfo.Size = 2452 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 2453 PointerInfo.Alignment = 2454 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); 2455 // Respect pragma pack. 2456 if (!MaxFieldAlignment.isZero()) 2457 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment); 2458 } 2459 2460 void 2461 MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) { 2462 // The MS-ABI lays out all bases that contain leading vfptrs before it lays 2463 // out any bases that do not contain vfptrs. We implement this as two passes 2464 // over the bases. This approach guarantees that the primary base is laid out 2465 // first. We use these passes to calculate some additional aggregated 2466 // information about the bases, such as reqruied alignment and the presence of 2467 // zero sized members. 2468 const ASTRecordLayout *PreviousBaseLayout = nullptr; 2469 // Iterate through the bases and lay out the non-virtual ones. 2470 for (const CXXBaseSpecifier &Base : RD->bases()) { 2471 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 2472 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl); 2473 // Mark and skip virtual bases. 2474 if (Base.isVirtual()) { 2475 HasVBPtr = true; 2476 continue; 2477 } 2478 // Check fo a base to share a VBPtr with. 2479 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) { 2480 SharedVBPtrBase = BaseDecl; 2481 HasVBPtr = true; 2482 } 2483 // Only lay out bases with extendable VFPtrs on the first pass. 2484 if (!BaseLayout.hasExtendableVFPtr()) 2485 continue; 2486 // If we don't have a primary base, this one qualifies. 2487 if (!PrimaryBase) { 2488 PrimaryBase = BaseDecl; 2489 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase(); 2490 } 2491 // Lay out the base. 2492 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout); 2493 } 2494 // Figure out if we need a fresh VFPtr for this class. 2495 if (!PrimaryBase && RD->isDynamicClass()) 2496 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 2497 e = RD->method_end(); 2498 !HasOwnVFPtr && i != e; ++i) 2499 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0; 2500 // If we don't have a primary base then we have a leading object that could 2501 // itself lead with a zero-sized object, something we track. 2502 bool CheckLeadingLayout = !PrimaryBase; 2503 // Iterate through the bases and lay out the non-virtual ones. 2504 for (const CXXBaseSpecifier &Base : RD->bases()) { 2505 if (Base.isVirtual()) 2506 continue; 2507 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 2508 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl); 2509 // Only lay out bases without extendable VFPtrs on the second pass. 2510 if (BaseLayout.hasExtendableVFPtr()) { 2511 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize(); 2512 continue; 2513 } 2514 // If this is the first layout, check to see if it leads with a zero sized 2515 // object. If it does, so do we. 2516 if (CheckLeadingLayout) { 2517 CheckLeadingLayout = false; 2518 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase(); 2519 } 2520 // Lay out the base. 2521 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout); 2522 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize(); 2523 } 2524 // Set our VBPtroffset if we know it at this point. 2525 if (!HasVBPtr) 2526 VBPtrOffset = CharUnits::fromQuantity(-1); 2527 else if (SharedVBPtrBase) { 2528 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase); 2529 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset(); 2530 } 2531 } 2532 2533 void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase( 2534 const CXXRecordDecl *BaseDecl, 2535 const ASTRecordLayout &BaseLayout, 2536 const ASTRecordLayout *&PreviousBaseLayout) { 2537 // Insert padding between two bases if the left first one is zero sized or 2538 // contains a zero sized subobject and the right is zero sized or one leads 2539 // with a zero sized base. 2540 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() && 2541 BaseLayout.leadsWithZeroSizedBase()) 2542 Size++; 2543 ElementInfo Info = getAdjustedElementInfo(BaseLayout); 2544 CharUnits BaseOffset; 2545 2546 // Respect the external AST source base offset, if present. 2547 bool FoundBase = false; 2548 if (UseExternalLayout) { 2549 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset); 2550 if (FoundBase) 2551 assert(BaseOffset >= Size && "base offset already allocated"); 2552 } 2553 2554 if (!FoundBase) 2555 BaseOffset = Size.RoundUpToAlignment(Info.Alignment); 2556 Bases.insert(std::make_pair(BaseDecl, BaseOffset)); 2557 Size = BaseOffset + BaseLayout.getNonVirtualSize(); 2558 PreviousBaseLayout = &BaseLayout; 2559 } 2560 2561 void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) { 2562 LastFieldIsNonZeroWidthBitfield = false; 2563 for (const FieldDecl *Field : RD->fields()) 2564 layoutField(Field); 2565 } 2566 2567 void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) { 2568 if (FD->isBitField()) { 2569 layoutBitField(FD); 2570 return; 2571 } 2572 LastFieldIsNonZeroWidthBitfield = false; 2573 ElementInfo Info = getAdjustedElementInfo(FD); 2574 Alignment = std::max(Alignment, Info.Alignment); 2575 if (IsUnion) { 2576 placeFieldAtOffset(CharUnits::Zero()); 2577 Size = std::max(Size, Info.Size); 2578 } else { 2579 CharUnits FieldOffset; 2580 if (UseExternalLayout) { 2581 FieldOffset = 2582 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD)); 2583 assert(FieldOffset >= Size && "field offset already allocated"); 2584 } else { 2585 FieldOffset = Size.RoundUpToAlignment(Info.Alignment); 2586 } 2587 placeFieldAtOffset(FieldOffset); 2588 Size = FieldOffset + Info.Size; 2589 } 2590 } 2591 2592 void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) { 2593 unsigned Width = FD->getBitWidthValue(Context); 2594 if (Width == 0) { 2595 layoutZeroWidthBitField(FD); 2596 return; 2597 } 2598 ElementInfo Info = getAdjustedElementInfo(FD); 2599 // Clamp the bitfield to a containable size for the sake of being able 2600 // to lay them out. Sema will throw an error. 2601 if (Width > Context.toBits(Info.Size)) 2602 Width = Context.toBits(Info.Size); 2603 // Check to see if this bitfield fits into an existing allocation. Note: 2604 // MSVC refuses to pack bitfields of formal types with different sizes 2605 // into the same allocation. 2606 if (!IsUnion && LastFieldIsNonZeroWidthBitfield && 2607 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) { 2608 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField); 2609 RemainingBitsInField -= Width; 2610 return; 2611 } 2612 LastFieldIsNonZeroWidthBitfield = true; 2613 CurrentBitfieldSize = Info.Size; 2614 if (IsUnion) { 2615 placeFieldAtOffset(CharUnits::Zero()); 2616 Size = std::max(Size, Info.Size); 2617 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions. 2618 } else { 2619 // Allocate a new block of memory and place the bitfield in it. 2620 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment); 2621 placeFieldAtOffset(FieldOffset); 2622 Size = FieldOffset + Info.Size; 2623 Alignment = std::max(Alignment, Info.Alignment); 2624 RemainingBitsInField = Context.toBits(Info.Size) - Width; 2625 } 2626 } 2627 2628 void 2629 MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) { 2630 // Zero-width bitfields are ignored unless they follow a non-zero-width 2631 // bitfield. 2632 if (!LastFieldIsNonZeroWidthBitfield) { 2633 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size); 2634 // TODO: Add a Sema warning that MS ignores alignment for zero 2635 // sized bitfields that occur after zero-size bitfields or non-bitfields. 2636 return; 2637 } 2638 LastFieldIsNonZeroWidthBitfield = false; 2639 ElementInfo Info = getAdjustedElementInfo(FD); 2640 if (IsUnion) { 2641 placeFieldAtOffset(CharUnits::Zero()); 2642 Size = std::max(Size, Info.Size); 2643 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions. 2644 } else { 2645 // Round up the current record size to the field's alignment boundary. 2646 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment); 2647 placeFieldAtOffset(FieldOffset); 2648 Size = FieldOffset; 2649 Alignment = std::max(Alignment, Info.Alignment); 2650 } 2651 } 2652 2653 void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) { 2654 if (!HasVBPtr || SharedVBPtrBase) 2655 return; 2656 // Inject the VBPointer at the injection site. 2657 CharUnits InjectionSite = VBPtrOffset; 2658 // But before we do, make sure it's properly aligned. 2659 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment); 2660 // Shift everything after the vbptr down, unless we're using an external 2661 // layout. 2662 if (UseExternalLayout) 2663 return; 2664 // Determine where the first field should be laid out after the vbptr. 2665 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size; 2666 // Make sure that the amount we push the fields back by is a multiple of the 2667 // alignment. 2668 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment( 2669 std::max(RequiredAlignment, Alignment)); 2670 Size += Offset; 2671 for (uint64_t &FieldOffset : FieldOffsets) 2672 FieldOffset += Context.toBits(Offset); 2673 for (BaseOffsetsMapTy::value_type &Base : Bases) 2674 if (Base.second >= InjectionSite) 2675 Base.second += Offset; 2676 } 2677 2678 void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) { 2679 if (!HasOwnVFPtr) 2680 return; 2681 // Make sure that the amount we push the struct back by is a multiple of the 2682 // alignment. 2683 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment( 2684 std::max(RequiredAlignment, Alignment)); 2685 // Push back the vbptr, but increase the size of the object and push back 2686 // regular fields by the offset only if not using external record layout. 2687 if (HasVBPtr) 2688 VBPtrOffset += Offset; 2689 2690 if (UseExternalLayout) 2691 return; 2692 2693 Size += Offset; 2694 2695 // If we're using an external layout, the fields offsets have already 2696 // accounted for this adjustment. 2697 for (uint64_t &FieldOffset : FieldOffsets) 2698 FieldOffset += Context.toBits(Offset); 2699 for (BaseOffsetsMapTy::value_type &Base : Bases) 2700 Base.second += Offset; 2701 } 2702 2703 void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) { 2704 if (!HasVBPtr) 2705 return; 2706 // Vtordisps are always 4 bytes (even in 64-bit mode) 2707 CharUnits VtorDispSize = CharUnits::fromQuantity(4); 2708 CharUnits VtorDispAlignment = VtorDispSize; 2709 // vtordisps respect pragma pack. 2710 if (!MaxFieldAlignment.isZero()) 2711 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment); 2712 // The alignment of the vtordisp is at least the required alignment of the 2713 // entire record. This requirement may be present to support vtordisp 2714 // injection. 2715 for (const CXXBaseSpecifier &VBase : RD->vbases()) { 2716 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl(); 2717 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl); 2718 RequiredAlignment = 2719 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment()); 2720 } 2721 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment); 2722 // Compute the vtordisp set. 2723 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet; 2724 computeVtorDispSet(HasVtorDispSet, RD); 2725 // Iterate through the virtual bases and lay them out. 2726 const ASTRecordLayout *PreviousBaseLayout = nullptr; 2727 for (const CXXBaseSpecifier &VBase : RD->vbases()) { 2728 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl(); 2729 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl); 2730 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0; 2731 // Insert padding between two bases if the left first one is zero sized or 2732 // contains a zero sized subobject and the right is zero sized or one leads 2733 // with a zero sized base. The padding between virtual bases is 4 2734 // bytes (in both 32 and 64 bits modes) and always involves rounding up to 2735 // the required alignment, we don't know why. 2736 if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() && 2737 BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp) { 2738 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize; 2739 Alignment = std::max(VtorDispAlignment, Alignment); 2740 } 2741 // Insert the virtual base. 2742 ElementInfo Info = getAdjustedElementInfo(BaseLayout); 2743 CharUnits BaseOffset; 2744 2745 // Respect the external AST source base offset, if present. 2746 bool FoundBase = false; 2747 if (UseExternalLayout) { 2748 FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset); 2749 if (FoundBase) 2750 assert(BaseOffset >= Size && "base offset already allocated"); 2751 } 2752 if (!FoundBase) 2753 BaseOffset = Size.RoundUpToAlignment(Info.Alignment); 2754 2755 VBases.insert(std::make_pair(BaseDecl, 2756 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp))); 2757 Size = BaseOffset + BaseLayout.getNonVirtualSize(); 2758 PreviousBaseLayout = &BaseLayout; 2759 } 2760 } 2761 2762 void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) { 2763 // Respect required alignment. Note that in 32-bit mode Required alignment 2764 // may be 0 and cause size not to be updated. 2765 DataSize = Size; 2766 if (!RequiredAlignment.isZero()) { 2767 Alignment = std::max(Alignment, RequiredAlignment); 2768 auto RoundingAlignment = Alignment; 2769 if (!MaxFieldAlignment.isZero()) 2770 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment); 2771 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment); 2772 Size = Size.RoundUpToAlignment(RoundingAlignment); 2773 } 2774 if (Size.isZero()) { 2775 EndsWithZeroSizedObject = true; 2776 LeadsWithZeroSizedBase = true; 2777 // Zero-sized structures have size equal to their alignment if a 2778 // __declspec(align) came into play. 2779 if (RequiredAlignment >= MinEmptyStructSize) 2780 Size = Alignment; 2781 else 2782 Size = MinEmptyStructSize; 2783 } 2784 2785 if (UseExternalLayout) { 2786 Size = Context.toCharUnitsFromBits(External.Size); 2787 if (External.Align) 2788 Alignment = Context.toCharUnitsFromBits(External.Align); 2789 } 2790 } 2791 2792 // Recursively walks the non-virtual bases of a class and determines if any of 2793 // them are in the bases with overridden methods set. 2794 static bool 2795 RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> & 2796 BasesWithOverriddenMethods, 2797 const CXXRecordDecl *RD) { 2798 if (BasesWithOverriddenMethods.count(RD)) 2799 return true; 2800 // If any of a virtual bases non-virtual bases (recursively) requires a 2801 // vtordisp than so does this virtual base. 2802 for (const CXXBaseSpecifier &Base : RD->bases()) 2803 if (!Base.isVirtual() && 2804 RequiresVtordisp(BasesWithOverriddenMethods, 2805 Base.getType()->getAsCXXRecordDecl())) 2806 return true; 2807 return false; 2808 } 2809 2810 void MicrosoftRecordLayoutBuilder::computeVtorDispSet( 2811 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet, 2812 const CXXRecordDecl *RD) const { 2813 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with 2814 // vftables. 2815 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) { 2816 for (const CXXBaseSpecifier &Base : RD->vbases()) { 2817 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 2818 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl); 2819 if (Layout.hasExtendableVFPtr()) 2820 HasVtordispSet.insert(BaseDecl); 2821 } 2822 return; 2823 } 2824 2825 // If any of our bases need a vtordisp for this type, so do we. Check our 2826 // direct bases for vtordisp requirements. 2827 for (const CXXBaseSpecifier &Base : RD->bases()) { 2828 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 2829 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl); 2830 for (const auto &bi : Layout.getVBaseOffsetsMap()) 2831 if (bi.second.hasVtorDisp()) 2832 HasVtordispSet.insert(bi.first); 2833 } 2834 // We don't introduce any additional vtordisps if either: 2835 // * A user declared constructor or destructor aren't declared. 2836 // * #pragma vtordisp(0) or the /vd0 flag are in use. 2837 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) || 2838 RD->getMSVtorDispMode() == MSVtorDispAttr::Never) 2839 return; 2840 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's 2841 // possible for a partially constructed object with virtual base overrides to 2842 // escape a non-trivial constructor. 2843 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride); 2844 // Compute a set of base classes which define methods we override. A virtual 2845 // base in this set will require a vtordisp. A virtual base that transitively 2846 // contains one of these bases as a non-virtual base will also require a 2847 // vtordisp. 2848 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work; 2849 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods; 2850 // Seed the working set with our non-destructor, non-pure virtual methods. 2851 for (const CXXMethodDecl *MD : RD->methods()) 2852 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure()) 2853 Work.insert(MD); 2854 while (!Work.empty()) { 2855 const CXXMethodDecl *MD = *Work.begin(); 2856 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(), 2857 e = MD->end_overridden_methods(); 2858 // If a virtual method has no-overrides it lives in its parent's vtable. 2859 if (i == e) 2860 BasesWithOverriddenMethods.insert(MD->getParent()); 2861 else 2862 Work.insert(i, e); 2863 // We've finished processing this element, remove it from the working set. 2864 Work.erase(MD); 2865 } 2866 // For each of our virtual bases, check if it is in the set of overridden 2867 // bases or if it transitively contains a non-virtual base that is. 2868 for (const CXXBaseSpecifier &Base : RD->vbases()) { 2869 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 2870 if (!HasVtordispSet.count(BaseDecl) && 2871 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl)) 2872 HasVtordispSet.insert(BaseDecl); 2873 } 2874 } 2875 2876 /// getASTRecordLayout - Get or compute information about the layout of the 2877 /// specified record (struct/union/class), which indicates its size and field 2878 /// position information. 2879 const ASTRecordLayout & 2880 ASTContext::getASTRecordLayout(const RecordDecl *D) const { 2881 // These asserts test different things. A record has a definition 2882 // as soon as we begin to parse the definition. That definition is 2883 // not a complete definition (which is what isDefinition() tests) 2884 // until we *finish* parsing the definition. 2885 2886 if (D->hasExternalLexicalStorage() && !D->getDefinition()) 2887 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D)); 2888 2889 D = D->getDefinition(); 2890 assert(D && "Cannot get layout of forward declarations!"); 2891 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!"); 2892 assert(D->isCompleteDefinition() && "Cannot layout type before complete!"); 2893 2894 // Look up this layout, if already laid out, return what we have. 2895 // Note that we can't save a reference to the entry because this function 2896 // is recursive. 2897 const ASTRecordLayout *Entry = ASTRecordLayouts[D]; 2898 if (Entry) return *Entry; 2899 2900 const ASTRecordLayout *NewEntry = nullptr; 2901 2902 if (isMsLayout(*this)) { 2903 MicrosoftRecordLayoutBuilder Builder(*this); 2904 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 2905 Builder.cxxLayout(RD); 2906 NewEntry = new (*this) ASTRecordLayout( 2907 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment, 2908 Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase, 2909 Builder.VBPtrOffset, Builder.NonVirtualSize, 2910 Builder.FieldOffsets.data(), Builder.FieldOffsets.size(), 2911 Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(), 2912 Builder.PrimaryBase, false, Builder.SharedVBPtrBase, 2913 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase, 2914 Builder.Bases, Builder.VBases); 2915 } else { 2916 Builder.layout(D); 2917 NewEntry = new (*this) ASTRecordLayout( 2918 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment, 2919 Builder.Size, Builder.FieldOffsets.data(), 2920 Builder.FieldOffsets.size()); 2921 } 2922 } else { 2923 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 2924 EmptySubobjectMap EmptySubobjects(*this, RD); 2925 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects); 2926 Builder.Layout(RD); 2927 2928 // In certain situations, we are allowed to lay out objects in the 2929 // tail-padding of base classes. This is ABI-dependent. 2930 // FIXME: this should be stored in the record layout. 2931 bool skipTailPadding = 2932 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD); 2933 2934 // FIXME: This should be done in FinalizeLayout. 2935 CharUnits DataSize = 2936 skipTailPadding ? Builder.getSize() : Builder.getDataSize(); 2937 CharUnits NonVirtualSize = 2938 skipTailPadding ? DataSize : Builder.NonVirtualSize; 2939 NewEntry = new (*this) ASTRecordLayout( 2940 *this, Builder.getSize(), Builder.Alignment, 2941 /*RequiredAlignment : used by MS-ABI)*/ 2942 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(), 2943 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets.data(), 2944 Builder.FieldOffsets.size(), NonVirtualSize, 2945 Builder.NonVirtualAlignment, 2946 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase, 2947 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases, 2948 Builder.VBases); 2949 } else { 2950 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr); 2951 Builder.Layout(D); 2952 2953 NewEntry = new (*this) ASTRecordLayout( 2954 *this, Builder.getSize(), Builder.Alignment, 2955 /*RequiredAlignment : used by MS-ABI)*/ 2956 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets.data(), 2957 Builder.FieldOffsets.size()); 2958 } 2959 } 2960 2961 ASTRecordLayouts[D] = NewEntry; 2962 2963 if (getLangOpts().DumpRecordLayouts) { 2964 llvm::outs() << "\n*** Dumping AST Record Layout\n"; 2965 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple); 2966 } 2967 2968 return *NewEntry; 2969 } 2970 2971 const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) { 2972 if (!getTargetInfo().getCXXABI().hasKeyFunctions()) 2973 return nullptr; 2974 2975 assert(RD->getDefinition() && "Cannot get key function for forward decl!"); 2976 RD = cast<CXXRecordDecl>(RD->getDefinition()); 2977 2978 // Beware: 2979 // 1) computing the key function might trigger deserialization, which might 2980 // invalidate iterators into KeyFunctions 2981 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and 2982 // invalidate the LazyDeclPtr within the map itself 2983 LazyDeclPtr Entry = KeyFunctions[RD]; 2984 const Decl *Result = 2985 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD); 2986 2987 // Store it back if it changed. 2988 if (Entry.isOffset() || Entry.isValid() != bool(Result)) 2989 KeyFunctions[RD] = const_cast<Decl*>(Result); 2990 2991 return cast_or_null<CXXMethodDecl>(Result); 2992 } 2993 2994 void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) { 2995 assert(Method == Method->getFirstDecl() && 2996 "not working with method declaration from class definition"); 2997 2998 // Look up the cache entry. Since we're working with the first 2999 // declaration, its parent must be the class definition, which is 3000 // the correct key for the KeyFunctions hash. 3001 const auto &Map = KeyFunctions; 3002 auto I = Map.find(Method->getParent()); 3003 3004 // If it's not cached, there's nothing to do. 3005 if (I == Map.end()) return; 3006 3007 // If it is cached, check whether it's the target method, and if so, 3008 // remove it from the cache. Note, the call to 'get' might invalidate 3009 // the iterator and the LazyDeclPtr object within the map. 3010 LazyDeclPtr Ptr = I->second; 3011 if (Ptr.get(getExternalSource()) == Method) { 3012 // FIXME: remember that we did this for module / chained PCH state? 3013 KeyFunctions.erase(Method->getParent()); 3014 } 3015 } 3016 3017 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) { 3018 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent()); 3019 return Layout.getFieldOffset(FD->getFieldIndex()); 3020 } 3021 3022 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const { 3023 uint64_t OffsetInBits; 3024 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 3025 OffsetInBits = ::getFieldOffset(*this, FD); 3026 } else { 3027 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD); 3028 3029 OffsetInBits = 0; 3030 for (const NamedDecl *ND : IFD->chain()) 3031 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND)); 3032 } 3033 3034 return OffsetInBits; 3035 } 3036 3037 /// getObjCLayout - Get or compute information about the layout of the 3038 /// given interface. 3039 /// 3040 /// \param Impl - If given, also include the layout of the interface's 3041 /// implementation. This may differ by including synthesized ivars. 3042 const ASTRecordLayout & 3043 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 3044 const ObjCImplementationDecl *Impl) const { 3045 // Retrieve the definition 3046 if (D->hasExternalLexicalStorage() && !D->getDefinition()) 3047 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D)); 3048 D = D->getDefinition(); 3049 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!"); 3050 3051 // Look up this layout, if already laid out, return what we have. 3052 const ObjCContainerDecl *Key = 3053 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D; 3054 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 3055 return *Entry; 3056 3057 // Add in synthesized ivar count if laying out an implementation. 3058 if (Impl) { 3059 unsigned SynthCount = CountNonClassIvars(D); 3060 // If there aren't any sythesized ivars then reuse the interface 3061 // entry. Note we can't cache this because we simply free all 3062 // entries later; however we shouldn't look up implementations 3063 // frequently. 3064 if (SynthCount == 0) 3065 return getObjCLayout(D, nullptr); 3066 } 3067 3068 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr); 3069 Builder.Layout(D); 3070 3071 const ASTRecordLayout *NewEntry = 3072 new (*this) ASTRecordLayout(*this, Builder.getSize(), 3073 Builder.Alignment, 3074 /*RequiredAlignment : used by MS-ABI)*/ 3075 Builder.Alignment, 3076 Builder.getDataSize(), 3077 Builder.FieldOffsets.data(), 3078 Builder.FieldOffsets.size()); 3079 3080 ObjCLayouts[Key] = NewEntry; 3081 3082 return *NewEntry; 3083 } 3084 3085 static void PrintOffset(raw_ostream &OS, 3086 CharUnits Offset, unsigned IndentLevel) { 3087 OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity()); 3088 OS.indent(IndentLevel * 2); 3089 } 3090 3091 static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset, 3092 unsigned Begin, unsigned Width, 3093 unsigned IndentLevel) { 3094 llvm::SmallString<10> Buffer; 3095 { 3096 llvm::raw_svector_ostream BufferOS(Buffer); 3097 BufferOS << Offset.getQuantity() << ':'; 3098 if (Width == 0) { 3099 BufferOS << '-'; 3100 } else { 3101 BufferOS << Begin << '-' << (Begin + Width - 1); 3102 } 3103 } 3104 3105 OS << llvm::right_justify(Buffer, 10) << " | "; 3106 OS.indent(IndentLevel * 2); 3107 } 3108 3109 static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) { 3110 OS << " | "; 3111 OS.indent(IndentLevel * 2); 3112 } 3113 3114 static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD, 3115 const ASTContext &C, 3116 CharUnits Offset, 3117 unsigned IndentLevel, 3118 const char* Description, 3119 bool PrintSizeInfo, 3120 bool IncludeVirtualBases) { 3121 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD); 3122 auto CXXRD = dyn_cast<CXXRecordDecl>(RD); 3123 3124 PrintOffset(OS, Offset, IndentLevel); 3125 OS << C.getTypeDeclType(const_cast<RecordDecl*>(RD)).getAsString(); 3126 if (Description) 3127 OS << ' ' << Description; 3128 if (CXXRD && CXXRD->isEmpty()) 3129 OS << " (empty)"; 3130 OS << '\n'; 3131 3132 IndentLevel++; 3133 3134 // Dump bases. 3135 if (CXXRD) { 3136 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 3137 bool HasOwnVFPtr = Layout.hasOwnVFPtr(); 3138 bool HasOwnVBPtr = Layout.hasOwnVBPtr(); 3139 3140 // Vtable pointer. 3141 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) { 3142 PrintOffset(OS, Offset, IndentLevel); 3143 OS << '(' << *RD << " vtable pointer)\n"; 3144 } else if (HasOwnVFPtr) { 3145 PrintOffset(OS, Offset, IndentLevel); 3146 // vfptr (for Microsoft C++ ABI) 3147 OS << '(' << *RD << " vftable pointer)\n"; 3148 } 3149 3150 // Collect nvbases. 3151 SmallVector<const CXXRecordDecl *, 4> Bases; 3152 for (const CXXBaseSpecifier &Base : CXXRD->bases()) { 3153 assert(!Base.getType()->isDependentType() && 3154 "Cannot layout class with dependent bases."); 3155 if (!Base.isVirtual()) 3156 Bases.push_back(Base.getType()->getAsCXXRecordDecl()); 3157 } 3158 3159 // Sort nvbases by offset. 3160 std::stable_sort(Bases.begin(), Bases.end(), 3161 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 3162 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 3163 }); 3164 3165 // Dump (non-virtual) bases 3166 for (const CXXRecordDecl *Base : Bases) { 3167 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base); 3168 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel, 3169 Base == PrimaryBase ? "(primary base)" : "(base)", 3170 /*PrintSizeInfo=*/false, 3171 /*IncludeVirtualBases=*/false); 3172 } 3173 3174 // vbptr (for Microsoft C++ ABI) 3175 if (HasOwnVBPtr) { 3176 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel); 3177 OS << '(' << *RD << " vbtable pointer)\n"; 3178 } 3179 } 3180 3181 // Dump fields. 3182 uint64_t FieldNo = 0; 3183 for (RecordDecl::field_iterator I = RD->field_begin(), 3184 E = RD->field_end(); I != E; ++I, ++FieldNo) { 3185 const FieldDecl &Field = **I; 3186 uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo); 3187 CharUnits FieldOffset = 3188 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits); 3189 3190 // Recursively dump fields of record type. 3191 if (auto RT = Field.getType()->getAs<RecordType>()) { 3192 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel, 3193 Field.getName().data(), 3194 /*PrintSizeInfo=*/false, 3195 /*IncludeVirtualBases=*/true); 3196 continue; 3197 } 3198 3199 if (Field.isBitField()) { 3200 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset); 3201 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits; 3202 unsigned Width = Field.getBitWidthValue(C); 3203 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel); 3204 } else { 3205 PrintOffset(OS, FieldOffset, IndentLevel); 3206 } 3207 OS << Field.getType().getAsString() << ' ' << Field << '\n'; 3208 } 3209 3210 // Dump virtual bases. 3211 if (CXXRD && IncludeVirtualBases) { 3212 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps = 3213 Layout.getVBaseOffsetsMap(); 3214 3215 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) { 3216 assert(Base.isVirtual() && "Found non-virtual class!"); 3217 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl(); 3218 3219 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase); 3220 3221 if (VtorDisps.find(VBase)->second.hasVtorDisp()) { 3222 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel); 3223 OS << "(vtordisp for vbase " << *VBase << ")\n"; 3224 } 3225 3226 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel, 3227 VBase == Layout.getPrimaryBase() ? 3228 "(primary virtual base)" : "(virtual base)", 3229 /*PrintSizeInfo=*/false, 3230 /*IncludeVirtualBases=*/false); 3231 } 3232 } 3233 3234 if (!PrintSizeInfo) return; 3235 3236 PrintIndentNoOffset(OS, IndentLevel - 1); 3237 OS << "[sizeof=" << Layout.getSize().getQuantity(); 3238 if (CXXRD && !isMsLayout(C)) 3239 OS << ", dsize=" << Layout.getDataSize().getQuantity(); 3240 OS << ", align=" << Layout.getAlignment().getQuantity(); 3241 3242 if (CXXRD) { 3243 OS << ",\n"; 3244 PrintIndentNoOffset(OS, IndentLevel - 1); 3245 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity(); 3246 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity(); 3247 } 3248 OS << "]\n"; 3249 } 3250 3251 void ASTContext::DumpRecordLayout(const RecordDecl *RD, 3252 raw_ostream &OS, 3253 bool Simple) const { 3254 if (!Simple) { 3255 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr, 3256 /*PrintSizeInfo*/true, 3257 /*IncludeVirtualBases=*/true); 3258 return; 3259 } 3260 3261 // The "simple" format is designed to be parsed by the 3262 // layout-override testing code. There shouldn't be any external 3263 // uses of this format --- when LLDB overrides a layout, it sets up 3264 // the data structures directly --- so feel free to adjust this as 3265 // you like as long as you also update the rudimentary parser for it 3266 // in libFrontend. 3267 3268 const ASTRecordLayout &Info = getASTRecordLayout(RD); 3269 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n"; 3270 OS << "\nLayout: "; 3271 OS << "<ASTRecordLayout\n"; 3272 OS << " Size:" << toBits(Info.getSize()) << "\n"; 3273 if (!isMsLayout(*this)) 3274 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n"; 3275 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n"; 3276 OS << " FieldOffsets: ["; 3277 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) { 3278 if (i) OS << ", "; 3279 OS << Info.getFieldOffset(i); 3280 } 3281 OS << "]>\n"; 3282 } 3283