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