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/Attr.h" 11 #include "clang/AST/CXXInheritance.h" 12 #include "clang/AST/Decl.h" 13 #include "clang/AST/DeclCXX.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/Expr.h" 16 #include "clang/AST/RecordLayout.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Sema/SemaDiagnostic.h" 19 #include "llvm/Support/Format.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/Support/MathExtras.h" 22 #include "llvm/Support/CrashRecoveryContext.h" 23 24 using namespace clang; 25 26 namespace { 27 28 /// BaseSubobjectInfo - Represents a single base subobject in a complete class. 29 /// For a class hierarchy like 30 /// 31 /// class A { }; 32 /// class B : A { }; 33 /// class C : A, B { }; 34 /// 35 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo 36 /// instances, one for B and two for A. 37 /// 38 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated. 39 struct BaseSubobjectInfo { 40 /// Class - The class for this base info. 41 const CXXRecordDecl *Class; 42 43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not. 44 bool IsVirtual; 45 46 /// Bases - Information about the base subobjects. 47 SmallVector<BaseSubobjectInfo*, 4> Bases; 48 49 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base 50 /// of this base info (if one exists). 51 BaseSubobjectInfo *PrimaryVirtualBaseInfo; 52 53 // FIXME: Document. 54 const BaseSubobjectInfo *Derived; 55 }; 56 57 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different 58 /// offsets while laying out a C++ class. 59 class EmptySubobjectMap { 60 const ASTContext &Context; 61 uint64_t CharWidth; 62 63 /// Class - The class whose empty entries we're keeping track of. 64 const CXXRecordDecl *Class; 65 66 /// EmptyClassOffsets - A map from offsets to empty record decls. 67 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy; 68 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy; 69 EmptyClassOffsetsMapTy EmptyClassOffsets; 70 71 /// MaxEmptyClassOffset - The highest offset known to contain an empty 72 /// base subobject. 73 CharUnits MaxEmptyClassOffset; 74 75 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or 76 /// member subobject that is empty. 77 void ComputeEmptySubobjectSizes(); 78 79 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset); 80 81 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 82 CharUnits Offset, bool PlacingEmptyBase); 83 84 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 85 const CXXRecordDecl *Class, 86 CharUnits Offset); 87 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset); 88 89 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty 90 /// subobjects beyond the given offset. 91 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const { 92 return Offset <= MaxEmptyClassOffset; 93 } 94 95 CharUnits 96 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const { 97 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); 98 assert(FieldOffset % CharWidth == 0 && 99 "Field offset not at char boundary!"); 100 101 return Context.toCharUnitsFromBits(FieldOffset); 102 } 103 104 protected: 105 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, 106 CharUnits Offset) const; 107 108 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, 109 CharUnits Offset); 110 111 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 112 const CXXRecordDecl *Class, 113 CharUnits Offset) const; 114 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, 115 CharUnits Offset) const; 116 117 public: 118 /// This holds the size of the largest empty subobject (either a base 119 /// or a member). Will be zero if the record being built doesn't contain 120 /// any empty classes. 121 CharUnits SizeOfLargestEmptySubobject; 122 123 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class) 124 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) { 125 ComputeEmptySubobjectSizes(); 126 } 127 128 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed 129 /// at the given offset. 130 /// Returns false if placing the record will result in two components 131 /// (direct or indirect) of the same type having the same offset. 132 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, 133 CharUnits Offset); 134 135 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given 136 /// offset. 137 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset); 138 }; 139 140 void EmptySubobjectMap::ComputeEmptySubobjectSizes() { 141 // Check the bases. 142 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(), 143 E = Class->bases_end(); I != E; ++I) { 144 const CXXRecordDecl *BaseDecl = 145 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 146 147 CharUnits EmptySize; 148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl); 149 if (BaseDecl->isEmpty()) { 150 // If the class decl is empty, get its size. 151 EmptySize = Layout.getSize(); 152 } else { 153 // Otherwise, we get the largest empty subobject for the decl. 154 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 155 } 156 157 if (EmptySize > SizeOfLargestEmptySubobject) 158 SizeOfLargestEmptySubobject = EmptySize; 159 } 160 161 // Check the fields. 162 for (CXXRecordDecl::field_iterator I = Class->field_begin(), 163 E = Class->field_end(); I != E; ++I) { 164 165 const RecordType *RT = 166 Context.getBaseElementType(I->getType())->getAs<RecordType>(); 167 168 // We only care about record types. 169 if (!RT) 170 continue; 171 172 CharUnits EmptySize; 173 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl()); 174 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl); 175 if (MemberDecl->isEmpty()) { 176 // If the class decl is empty, get its size. 177 EmptySize = Layout.getSize(); 178 } else { 179 // Otherwise, we get the largest empty subobject for the decl. 180 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 181 } 182 183 if (EmptySize > SizeOfLargestEmptySubobject) 184 SizeOfLargestEmptySubobject = EmptySize; 185 } 186 } 187 188 bool 189 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, 190 CharUnits Offset) const { 191 // We only need to check empty bases. 192 if (!RD->isEmpty()) 193 return true; 194 195 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset); 196 if (I == EmptyClassOffsets.end()) 197 return true; 198 199 const ClassVectorTy& Classes = I->second; 200 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end()) 201 return true; 202 203 // There is already an empty class of the same type at this offset. 204 return false; 205 } 206 207 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, 208 CharUnits Offset) { 209 // We only care about empty bases. 210 if (!RD->isEmpty()) 211 return; 212 213 // If we have empty structures inside an union, we can assign both 214 // the same offset. Just avoid pushing them twice in the list. 215 ClassVectorTy& Classes = EmptyClassOffsets[Offset]; 216 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end()) 217 return; 218 219 Classes.push_back(RD); 220 221 // Update the empty class offset. 222 if (Offset > MaxEmptyClassOffset) 223 MaxEmptyClassOffset = Offset; 224 } 225 226 bool 227 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, 228 CharUnits Offset) { 229 // We don't have to keep looking past the maximum offset that's known to 230 // contain an empty class. 231 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 232 return true; 233 234 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset)) 235 return false; 236 237 // Traverse all non-virtual bases. 238 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 239 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) { 240 BaseSubobjectInfo* Base = Info->Bases[I]; 241 if (Base->IsVirtual) 242 continue; 243 244 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 245 246 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset)) 247 return false; 248 } 249 250 if (Info->PrimaryVirtualBaseInfo) { 251 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; 252 253 if (Info == PrimaryVirtualBaseInfo->Derived) { 254 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset)) 255 return false; 256 } 257 } 258 259 // Traverse all member variables. 260 unsigned FieldNo = 0; 261 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 262 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { 263 if (I->isBitField()) 264 continue; 265 266 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 267 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset)) 268 return false; 269 } 270 271 return true; 272 } 273 274 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 275 CharUnits Offset, 276 bool PlacingEmptyBase) { 277 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) { 278 // We know that the only empty subobjects that can conflict with empty 279 // subobject of non-empty bases, are empty bases that can be placed at 280 // offset zero. Because of this, we only need to keep track of empty base 281 // subobjects with offsets less than the size of the largest empty 282 // subobject for our class. 283 return; 284 } 285 286 AddSubobjectAtOffset(Info->Class, Offset); 287 288 // Traverse all non-virtual bases. 289 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 290 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) { 291 BaseSubobjectInfo* Base = Info->Bases[I]; 292 if (Base->IsVirtual) 293 continue; 294 295 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 296 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase); 297 } 298 299 if (Info->PrimaryVirtualBaseInfo) { 300 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; 301 302 if (Info == PrimaryVirtualBaseInfo->Derived) 303 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset, 304 PlacingEmptyBase); 305 } 306 307 // Traverse all member variables. 308 unsigned FieldNo = 0; 309 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 310 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { 311 if (I->isBitField()) 312 continue; 313 314 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 315 UpdateEmptyFieldSubobjects(*I, FieldOffset); 316 } 317 } 318 319 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, 320 CharUnits Offset) { 321 // If we know this class doesn't have any empty subobjects we don't need to 322 // bother checking. 323 if (SizeOfLargestEmptySubobject.isZero()) 324 return true; 325 326 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset)) 327 return false; 328 329 // We are able to place the base at this offset. Make sure to update the 330 // empty base subobject map. 331 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty()); 332 return true; 333 } 334 335 bool 336 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 337 const CXXRecordDecl *Class, 338 CharUnits Offset) const { 339 // We don't have to keep looking past the maximum offset that's known to 340 // contain an empty class. 341 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 342 return true; 343 344 if (!CanPlaceSubobjectAtOffset(RD, Offset)) 345 return false; 346 347 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 348 349 // Traverse all non-virtual bases. 350 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 351 E = RD->bases_end(); I != E; ++I) { 352 if (I->isVirtual()) 353 continue; 354 355 const CXXRecordDecl *BaseDecl = 356 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 357 358 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 359 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset)) 360 return false; 361 } 362 363 if (RD == Class) { 364 // This is the most derived class, traverse virtual bases as well. 365 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 366 E = RD->vbases_end(); I != E; ++I) { 367 const CXXRecordDecl *VBaseDecl = 368 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 369 370 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl); 371 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset)) 372 return false; 373 } 374 } 375 376 // Traverse all member variables. 377 unsigned FieldNo = 0; 378 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 379 I != E; ++I, ++FieldNo) { 380 if (I->isBitField()) 381 continue; 382 383 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 384 385 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset)) 386 return false; 387 } 388 389 return true; 390 } 391 392 bool 393 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, 394 CharUnits Offset) const { 395 // We don't have to keep looking past the maximum offset that's known to 396 // contain an empty class. 397 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 398 return true; 399 400 QualType T = FD->getType(); 401 if (const RecordType *RT = T->getAs<RecordType>()) { 402 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 403 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset); 404 } 405 406 // If we have an array type we need to look at every element. 407 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 408 QualType ElemTy = Context.getBaseElementType(AT); 409 const RecordType *RT = ElemTy->getAs<RecordType>(); 410 if (!RT) 411 return true; 412 413 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 414 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 415 416 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 417 CharUnits ElementOffset = Offset; 418 for (uint64_t I = 0; I != NumElements; ++I) { 419 // We don't have to keep looking past the maximum offset that's known to 420 // contain an empty class. 421 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset)) 422 return true; 423 424 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset)) 425 return false; 426 427 ElementOffset += Layout.getSize(); 428 } 429 } 430 431 return true; 432 } 433 434 bool 435 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, 436 CharUnits Offset) { 437 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset)) 438 return false; 439 440 // We are able to place the member variable at this offset. 441 // Make sure to update the empty base subobject map. 442 UpdateEmptyFieldSubobjects(FD, Offset); 443 return true; 444 } 445 446 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 447 const CXXRecordDecl *Class, 448 CharUnits Offset) { 449 // We know that the only empty subobjects that can conflict with empty 450 // field subobjects are subobjects of empty bases that can be placed at offset 451 // zero. Because of this, we only need to keep track of empty field 452 // subobjects with offsets less than the size of the largest empty 453 // subobject for our class. 454 if (Offset >= SizeOfLargestEmptySubobject) 455 return; 456 457 AddSubobjectAtOffset(RD, Offset); 458 459 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 460 461 // Traverse all non-virtual bases. 462 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 463 E = RD->bases_end(); I != E; ++I) { 464 if (I->isVirtual()) 465 continue; 466 467 const CXXRecordDecl *BaseDecl = 468 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 469 470 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 471 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset); 472 } 473 474 if (RD == Class) { 475 // This is the most derived class, traverse virtual bases as well. 476 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 477 E = RD->vbases_end(); I != E; ++I) { 478 const CXXRecordDecl *VBaseDecl = 479 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 480 481 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl); 482 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset); 483 } 484 } 485 486 // Traverse all member variables. 487 unsigned FieldNo = 0; 488 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 489 I != E; ++I, ++FieldNo) { 490 if (I->isBitField()) 491 continue; 492 493 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 494 495 UpdateEmptyFieldSubobjects(*I, FieldOffset); 496 } 497 } 498 499 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, 500 CharUnits Offset) { 501 QualType T = FD->getType(); 502 if (const RecordType *RT = T->getAs<RecordType>()) { 503 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 504 UpdateEmptyFieldSubobjects(RD, RD, Offset); 505 return; 506 } 507 508 // If we have an array type we need to update every element. 509 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 510 QualType ElemTy = Context.getBaseElementType(AT); 511 const RecordType *RT = ElemTy->getAs<RecordType>(); 512 if (!RT) 513 return; 514 515 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 516 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 517 518 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 519 CharUnits ElementOffset = Offset; 520 521 for (uint64_t I = 0; I != NumElements; ++I) { 522 // We know that the only empty subobjects that can conflict with empty 523 // field subobjects are subobjects of empty bases that can be placed at 524 // offset zero. Because of this, we only need to keep track of empty field 525 // subobjects with offsets less than the size of the largest empty 526 // subobject for our class. 527 if (ElementOffset >= SizeOfLargestEmptySubobject) 528 return; 529 530 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset); 531 ElementOffset += Layout.getSize(); 532 } 533 } 534 } 535 536 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy; 537 538 class RecordLayoutBuilder { 539 protected: 540 // FIXME: Remove this and make the appropriate fields public. 541 friend class clang::ASTContext; 542 543 const ASTContext &Context; 544 545 EmptySubobjectMap *EmptySubobjects; 546 547 /// Size - The current size of the record layout. 548 uint64_t Size; 549 550 /// Alignment - The current alignment of the record layout. 551 CharUnits Alignment; 552 553 /// \brief The alignment if attribute packed is not used. 554 CharUnits UnpackedAlignment; 555 556 SmallVector<uint64_t, 16> FieldOffsets; 557 558 /// \brief Whether the external AST source has provided a layout for this 559 /// record. 560 unsigned ExternalLayout : 1; 561 562 /// \brief Whether we need to infer alignment, even when we have an 563 /// externally-provided layout. 564 unsigned InferAlignment : 1; 565 566 /// Packed - Whether the record is packed or not. 567 unsigned Packed : 1; 568 569 unsigned IsUnion : 1; 570 571 unsigned IsMac68kAlign : 1; 572 573 unsigned IsMsStruct : 1; 574 575 /// UnfilledBitsInLastByte - If the last field laid out was a bitfield, 576 /// this contains the number of bits in the last byte that can be used for 577 /// an adjacent bitfield if necessary. 578 unsigned char UnfilledBitsInLastByte; 579 580 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by 581 /// #pragma pack. 582 CharUnits MaxFieldAlignment; 583 584 /// DataSize - The data size of the record being laid out. 585 uint64_t DataSize; 586 587 CharUnits NonVirtualSize; 588 CharUnits NonVirtualAlignment; 589 590 FieldDecl *ZeroLengthBitfield; 591 592 /// PrimaryBase - the primary base class (if one exists) of the class 593 /// we're laying out. 594 const CXXRecordDecl *PrimaryBase; 595 596 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying 597 /// out is virtual. 598 bool PrimaryBaseIsVirtual; 599 600 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl 601 /// pointer, as opposed to inheriting one from a primary base class. 602 bool HasOwnVFPtr; 603 604 /// VBPtrOffset - Virtual base table offset. Only for MS layout. 605 CharUnits VBPtrOffset; 606 607 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy; 608 609 /// Bases - base classes and their offsets in the record. 610 BaseOffsetsMapTy Bases; 611 612 // VBases - virtual base classes and their offsets in the record. 613 ASTRecordLayout::VBaseOffsetsMapTy VBases; 614 615 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are 616 /// primary base classes for some other direct or indirect base class. 617 CXXIndirectPrimaryBaseSet IndirectPrimaryBases; 618 619 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in 620 /// inheritance graph order. Used for determining the primary base class. 621 const CXXRecordDecl *FirstNearlyEmptyVBase; 622 623 /// VisitedVirtualBases - A set of all the visited virtual bases, used to 624 /// avoid visiting virtual bases more than once. 625 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; 626 627 /// \brief Externally-provided size. 628 uint64_t ExternalSize; 629 630 /// \brief Externally-provided alignment. 631 uint64_t ExternalAlign; 632 633 /// \brief Externally-provided field offsets. 634 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets; 635 636 /// \brief Externally-provided direct, non-virtual base offsets. 637 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets; 638 639 /// \brief Externally-provided virtual base offsets. 640 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets; 641 642 RecordLayoutBuilder(const ASTContext &Context, 643 EmptySubobjectMap *EmptySubobjects) 644 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), 645 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()), 646 ExternalLayout(false), InferAlignment(false), 647 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false), 648 UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()), 649 DataSize(0), NonVirtualSize(CharUnits::Zero()), 650 NonVirtualAlignment(CharUnits::One()), 651 ZeroLengthBitfield(0), PrimaryBase(0), 652 PrimaryBaseIsVirtual(false), 653 HasOwnVFPtr(false), 654 VBPtrOffset(CharUnits::fromQuantity(-1)), 655 FirstNearlyEmptyVBase(0) { } 656 657 /// Reset this RecordLayoutBuilder to a fresh state, using the given 658 /// alignment as the initial alignment. This is used for the 659 /// correct layout of vb-table pointers in MSVC. 660 void resetWithTargetAlignment(CharUnits TargetAlignment) { 661 const ASTContext &Context = this->Context; 662 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects; 663 this->~RecordLayoutBuilder(); 664 new (this) RecordLayoutBuilder(Context, EmptySubobjects); 665 Alignment = UnpackedAlignment = TargetAlignment; 666 } 667 668 void Layout(const RecordDecl *D); 669 void Layout(const CXXRecordDecl *D); 670 void Layout(const ObjCInterfaceDecl *D); 671 672 void LayoutFields(const RecordDecl *D); 673 void LayoutField(const FieldDecl *D); 674 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize, 675 bool FieldPacked, const FieldDecl *D); 676 void LayoutBitField(const FieldDecl *D); 677 678 bool isMicrosoftCXXABI() const { 679 return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft; 680 } 681 682 void MSLayoutVirtualBases(const CXXRecordDecl *RD); 683 684 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects. 685 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator; 686 687 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *> 688 BaseSubobjectInfoMapTy; 689 690 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases 691 /// of the class we're laying out to their base subobject info. 692 BaseSubobjectInfoMapTy VirtualBaseInfo; 693 694 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the 695 /// class we're laying out to their base subobject info. 696 BaseSubobjectInfoMapTy NonVirtualBaseInfo; 697 698 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the 699 /// bases of the given class. 700 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD); 701 702 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a 703 /// single class and all of its base classes. 704 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 705 bool IsVirtual, 706 BaseSubobjectInfo *Derived); 707 708 /// DeterminePrimaryBase - Determine the primary base of the given class. 709 void DeterminePrimaryBase(const CXXRecordDecl *RD); 710 711 void SelectPrimaryVBase(const CXXRecordDecl *RD); 712 713 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign); 714 715 /// LayoutNonVirtualBases - Determines the primary base class (if any) and 716 /// lays it out. Will then proceed to lay out all non-virtual base clasess. 717 void LayoutNonVirtualBases(const CXXRecordDecl *RD); 718 719 /// LayoutNonVirtualBase - Lays out a single non-virtual base. 720 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base); 721 722 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info, 723 CharUnits Offset); 724 725 bool needsVFTable(const CXXRecordDecl *RD) const; 726 bool hasNewVirtualFunction(const CXXRecordDecl *RD, 727 bool IgnoreDestructor = false) const; 728 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const; 729 730 void computeVtordisps(const CXXRecordDecl *RD, 731 ClassSetTy &VtordispVBases); 732 733 /// LayoutVirtualBases - Lays out all the virtual bases. 734 void LayoutVirtualBases(const CXXRecordDecl *RD, 735 const CXXRecordDecl *MostDerivedClass); 736 737 /// LayoutVirtualBase - Lays out a single virtual base. 738 void LayoutVirtualBase(const BaseSubobjectInfo *Base, 739 bool IsVtordispNeed = false); 740 741 /// LayoutBase - Will lay out a base and return the offset where it was 742 /// placed, in chars. 743 CharUnits LayoutBase(const BaseSubobjectInfo *Base); 744 745 /// InitializeLayout - Initialize record layout for the given record decl. 746 void InitializeLayout(const Decl *D); 747 748 /// FinishLayout - Finalize record layout. Adjust record size based on the 749 /// alignment. 750 void FinishLayout(const NamedDecl *D); 751 752 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment); 753 void UpdateAlignment(CharUnits NewAlignment) { 754 UpdateAlignment(NewAlignment, NewAlignment); 755 } 756 757 /// \brief Retrieve the externally-supplied field offset for the given 758 /// field. 759 /// 760 /// \param Field The field whose offset is being queried. 761 /// \param ComputedOffset The offset that we've computed for this field. 762 uint64_t updateExternalFieldOffset(const FieldDecl *Field, 763 uint64_t ComputedOffset); 764 765 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset, 766 uint64_t UnpackedOffset, unsigned UnpackedAlign, 767 bool isPacked, const FieldDecl *D); 768 769 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 770 771 CharUnits getSize() const { 772 assert(Size % Context.getCharWidth() == 0); 773 return Context.toCharUnitsFromBits(Size); 774 } 775 uint64_t getSizeInBits() const { return Size; } 776 777 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); } 778 void setSize(uint64_t NewSize) { Size = NewSize; } 779 780 CharUnits getAligment() const { return Alignment; } 781 782 CharUnits getDataSize() const { 783 assert(DataSize % Context.getCharWidth() == 0); 784 return Context.toCharUnitsFromBits(DataSize); 785 } 786 uint64_t getDataSizeInBits() const { return DataSize; } 787 788 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); } 789 void setDataSize(uint64_t NewSize) { DataSize = NewSize; } 790 791 RecordLayoutBuilder(const RecordLayoutBuilder&); // DO NOT IMPLEMENT 792 void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT 793 public: 794 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD); 795 }; 796 } // end anonymous namespace 797 798 void 799 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) { 800 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 801 E = RD->bases_end(); I != E; ++I) { 802 assert(!I->getType()->isDependentType() && 803 "Cannot layout class with dependent bases."); 804 805 const CXXRecordDecl *Base = 806 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 807 808 // Check if this is a nearly empty virtual base. 809 if (I->isVirtual() && Context.isNearlyEmpty(Base)) { 810 // If it's not an indirect primary base, then we've found our primary 811 // base. 812 if (!IndirectPrimaryBases.count(Base)) { 813 PrimaryBase = Base; 814 PrimaryBaseIsVirtual = true; 815 return; 816 } 817 818 // Is this the first nearly empty virtual base? 819 if (!FirstNearlyEmptyVBase) 820 FirstNearlyEmptyVBase = Base; 821 } 822 823 SelectPrimaryVBase(Base); 824 if (PrimaryBase) 825 return; 826 } 827 } 828 829 /// DeterminePrimaryBase - Determine the primary base of the given class. 830 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) { 831 // If the class isn't dynamic, it won't have a primary base. 832 if (!RD->isDynamicClass()) 833 return; 834 835 // Compute all the primary virtual bases for all of our direct and 836 // indirect bases, and record all their primary virtual base classes. 837 RD->getIndirectPrimaryBases(IndirectPrimaryBases); 838 839 // If the record has a dynamic base class, attempt to choose a primary base 840 // class. It is the first (in direct base class order) non-virtual dynamic 841 // base class, if one exists. 842 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 843 e = RD->bases_end(); i != e; ++i) { 844 // Ignore virtual bases. 845 if (i->isVirtual()) 846 continue; 847 848 const CXXRecordDecl *Base = 849 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 850 851 if (isPossiblePrimaryBase(Base)) { 852 // We found it. 853 PrimaryBase = Base; 854 PrimaryBaseIsVirtual = false; 855 return; 856 } 857 } 858 859 // The Microsoft ABI doesn't have primary virtual bases. 860 if (isMicrosoftCXXABI()) { 861 assert(!PrimaryBase && "Should not get here with a primary base!"); 862 return; 863 } 864 865 // Under the Itanium ABI, if there is no non-virtual primary base class, 866 // try to compute the primary virtual base. The primary virtual base is 867 // the first nearly empty virtual base that is not an indirect primary 868 // virtual base class, if one exists. 869 if (RD->getNumVBases() != 0) { 870 SelectPrimaryVBase(RD); 871 if (PrimaryBase) 872 return; 873 } 874 875 // Otherwise, it is the first indirect primary base class, if one exists. 876 if (FirstNearlyEmptyVBase) { 877 PrimaryBase = FirstNearlyEmptyVBase; 878 PrimaryBaseIsVirtual = true; 879 return; 880 } 881 882 assert(!PrimaryBase && "Should not get here with a primary base!"); 883 } 884 885 BaseSubobjectInfo * 886 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 887 bool IsVirtual, 888 BaseSubobjectInfo *Derived) { 889 BaseSubobjectInfo *Info; 890 891 if (IsVirtual) { 892 // Check if we already have info about this virtual base. 893 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD]; 894 if (InfoSlot) { 895 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!"); 896 return InfoSlot; 897 } 898 899 // We don't, create it. 900 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; 901 Info = InfoSlot; 902 } else { 903 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; 904 } 905 906 Info->Class = RD; 907 Info->IsVirtual = IsVirtual; 908 Info->Derived = 0; 909 Info->PrimaryVirtualBaseInfo = 0; 910 911 const CXXRecordDecl *PrimaryVirtualBase = 0; 912 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0; 913 914 // Check if this base has a primary virtual base. 915 if (RD->getNumVBases()) { 916 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 917 if (Layout.isPrimaryBaseVirtual()) { 918 // This base does have a primary virtual base. 919 PrimaryVirtualBase = Layout.getPrimaryBase(); 920 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!"); 921 922 // Now check if we have base subobject info about this primary base. 923 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); 924 925 if (PrimaryVirtualBaseInfo) { 926 if (PrimaryVirtualBaseInfo->Derived) { 927 // We did have info about this primary base, and it turns out that it 928 // has already been claimed as a primary virtual base for another 929 // base. 930 PrimaryVirtualBase = 0; 931 } else { 932 // We can claim this base as our primary base. 933 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; 934 PrimaryVirtualBaseInfo->Derived = Info; 935 } 936 } 937 } 938 } 939 940 // Now go through all direct bases. 941 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 942 E = RD->bases_end(); I != E; ++I) { 943 bool IsVirtual = I->isVirtual(); 944 945 const CXXRecordDecl *BaseDecl = 946 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 947 948 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info)); 949 } 950 951 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) { 952 // Traversing the bases must have created the base info for our primary 953 // virtual base. 954 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); 955 assert(PrimaryVirtualBaseInfo && 956 "Did not create a primary virtual base!"); 957 958 // Claim the primary virtual base as our primary virtual base. 959 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; 960 PrimaryVirtualBaseInfo->Derived = Info; 961 } 962 963 return Info; 964 } 965 966 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) { 967 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 968 E = RD->bases_end(); I != E; ++I) { 969 bool IsVirtual = I->isVirtual(); 970 971 const CXXRecordDecl *BaseDecl = 972 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 973 974 // Compute the base subobject info for this base. 975 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0); 976 977 if (IsVirtual) { 978 // ComputeBaseInfo has already added this base for us. 979 assert(VirtualBaseInfo.count(BaseDecl) && 980 "Did not add virtual base!"); 981 } else { 982 // Add the base info to the map of non-virtual bases. 983 assert(!NonVirtualBaseInfo.count(BaseDecl) && 984 "Non-virtual base already exists!"); 985 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info)); 986 } 987 } 988 } 989 990 void 991 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) { 992 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign; 993 994 // The maximum field alignment overrides base align. 995 if (!MaxFieldAlignment.isZero()) { 996 BaseAlign = std::min(BaseAlign, MaxFieldAlignment); 997 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment); 998 } 999 1000 // Round up the current record size to pointer alignment. 1001 setSize(getSize().RoundUpToAlignment(BaseAlign)); 1002 setDataSize(getSize()); 1003 1004 // Update the alignment. 1005 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 1006 } 1007 1008 void 1009 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) { 1010 // Then, determine the primary base class. 1011 DeterminePrimaryBase(RD); 1012 1013 // Compute base subobject info. 1014 ComputeBaseSubobjectInfo(RD); 1015 1016 // If we have a primary base class, lay it out. 1017 if (PrimaryBase) { 1018 if (PrimaryBaseIsVirtual) { 1019 // If the primary virtual base was a primary virtual base of some other 1020 // base class we'll have to steal it. 1021 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase); 1022 PrimaryBaseInfo->Derived = 0; 1023 1024 // We have a virtual primary base, insert it as an indirect primary base. 1025 IndirectPrimaryBases.insert(PrimaryBase); 1026 1027 assert(!VisitedVirtualBases.count(PrimaryBase) && 1028 "vbase already visited!"); 1029 VisitedVirtualBases.insert(PrimaryBase); 1030 1031 LayoutVirtualBase(PrimaryBaseInfo); 1032 } else { 1033 BaseSubobjectInfo *PrimaryBaseInfo = 1034 NonVirtualBaseInfo.lookup(PrimaryBase); 1035 assert(PrimaryBaseInfo && 1036 "Did not find base info for non-virtual primary base!"); 1037 1038 LayoutNonVirtualBase(PrimaryBaseInfo); 1039 } 1040 1041 // If this class needs a vtable/vf-table and didn't get one from a 1042 // primary base, add it in now. 1043 } else if (needsVFTable(RD)) { 1044 assert(DataSize == 0 && "Vtable pointer must be at offset zero!"); 1045 CharUnits PtrWidth = 1046 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 1047 CharUnits PtrAlign = 1048 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); 1049 EnsureVTablePointerAlignment(PtrAlign); 1050 HasOwnVFPtr = true; 1051 setSize(getSize() + PtrWidth); 1052 setDataSize(getSize()); 1053 } 1054 1055 bool HasDirectVirtualBases = false; 1056 bool HasNonVirtualBaseWithVBTable = false; 1057 1058 // Now lay out the non-virtual bases. 1059 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1060 E = RD->bases_end(); I != E; ++I) { 1061 1062 // Ignore virtual bases, but remember that we saw one. 1063 if (I->isVirtual()) { 1064 HasDirectVirtualBases = true; 1065 continue; 1066 } 1067 1068 const CXXRecordDecl *BaseDecl = 1069 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 1070 1071 // Remember if this base has virtual bases itself. 1072 if (BaseDecl->getNumVBases()) 1073 HasNonVirtualBaseWithVBTable = true; 1074 1075 // Skip the primary base, because we've already laid it out. The 1076 // !PrimaryBaseIsVirtual check is required because we might have a 1077 // non-virtual base of the same type as a primary virtual base. 1078 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual) 1079 continue; 1080 1081 // Lay out the base. 1082 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl); 1083 assert(BaseInfo && "Did not find base info for non-virtual base!"); 1084 1085 LayoutNonVirtualBase(BaseInfo); 1086 } 1087 1088 // In the MS ABI, add the vb-table pointer if we need one, which is 1089 // whenever we have a virtual base and we can't re-use a vb-table 1090 // pointer from a non-virtual base. 1091 if (isMicrosoftCXXABI() && 1092 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) { 1093 CharUnits PtrWidth = 1094 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 1095 CharUnits PtrAlign = 1096 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); 1097 1098 // MSVC potentially over-aligns the vb-table pointer by giving it 1099 // the max alignment of all the non-virtual objects in the class. 1100 // This is completely unnecessary, but we're not here to pass 1101 // judgment. 1102 // 1103 // Note that we've only laid out the non-virtual bases, so on the 1104 // first pass Alignment won't be set correctly here, but if the 1105 // vb-table doesn't end up aligned correctly we'll come through 1106 // and redo the layout from scratch with the right alignment. 1107 // 1108 // TODO: Instead of doing this, just lay out the fields as if the 1109 // vb-table were at offset zero, then retroactively bump the field 1110 // offsets up. 1111 PtrAlign = std::max(PtrAlign, Alignment); 1112 1113 EnsureVTablePointerAlignment(PtrAlign); 1114 VBPtrOffset = getSize(); 1115 setSize(getSize() + PtrWidth); 1116 setDataSize(getSize()); 1117 } 1118 } 1119 1120 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) { 1121 // Layout the base. 1122 CharUnits Offset = LayoutBase(Base); 1123 1124 // Add its base class offset. 1125 assert(!Bases.count(Base->Class) && "base offset already exists!"); 1126 Bases.insert(std::make_pair(Base->Class, Offset)); 1127 1128 AddPrimaryVirtualBaseOffsets(Base, Offset); 1129 } 1130 1131 void 1132 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info, 1133 CharUnits Offset) { 1134 // This base isn't interesting, it has no virtual bases. 1135 if (!Info->Class->getNumVBases()) 1136 return; 1137 1138 // First, check if we have a virtual primary base to add offsets for. 1139 if (Info->PrimaryVirtualBaseInfo) { 1140 assert(Info->PrimaryVirtualBaseInfo->IsVirtual && 1141 "Primary virtual base is not virtual!"); 1142 if (Info->PrimaryVirtualBaseInfo->Derived == Info) { 1143 // Add the offset. 1144 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && 1145 "primary vbase offset already exists!"); 1146 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class, 1147 ASTRecordLayout::VBaseInfo(Offset, false))); 1148 1149 // Traverse the primary virtual base. 1150 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset); 1151 } 1152 } 1153 1154 // Now go through all direct non-virtual bases. 1155 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 1156 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) { 1157 const BaseSubobjectInfo *Base = Info->Bases[I]; 1158 if (Base->IsVirtual) 1159 continue; 1160 1161 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 1162 AddPrimaryVirtualBaseOffsets(Base, BaseOffset); 1163 } 1164 } 1165 1166 /// needsVFTable - Return true if this class needs a vtable or vf-table 1167 /// when laid out as a base class. These are treated the same because 1168 /// they're both always laid out at offset zero. 1169 /// 1170 /// This function assumes that the class has no primary base. 1171 bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const { 1172 assert(!PrimaryBase); 1173 1174 // In the Itanium ABI, every dynamic class needs a vtable: even if 1175 // this class has no virtual functions as a base class (i.e. it's 1176 // non-polymorphic or only has virtual functions from virtual 1177 // bases),x it still needs a vtable to locate its virtual bases. 1178 if (!isMicrosoftCXXABI()) 1179 return RD->isDynamicClass(); 1180 1181 // In the MS ABI, we need a vfptr if the class has virtual functions 1182 // other than those declared by its virtual bases. The AST doesn't 1183 // tell us that directly, and checking manually for virtual 1184 // functions that aren't overrides is expensive, but there are 1185 // some important shortcuts: 1186 1187 // - Non-polymorphic classes have no virtual functions at all. 1188 if (!RD->isPolymorphic()) return false; 1189 1190 // - Polymorphic classes with no virtual bases must either declare 1191 // virtual functions directly or inherit them, but in the latter 1192 // case we would have a primary base. 1193 if (RD->getNumVBases() == 0) return true; 1194 1195 return hasNewVirtualFunction(RD); 1196 } 1197 1198 /// Does the given class inherit non-virtually from any of the classes 1199 /// in the given set? 1200 static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD, 1201 const ClassSetTy &set) { 1202 for (CXXRecordDecl::base_class_const_iterator 1203 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) { 1204 // Ignore virtual links. 1205 if (I->isVirtual()) continue; 1206 1207 // Check whether the set contains the base. 1208 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl(); 1209 if (set.count(base)) 1210 return true; 1211 1212 // Otherwise, recurse and propagate. 1213 if (hasNonVirtualBaseInSet(base, set)) 1214 return true; 1215 } 1216 1217 return false; 1218 } 1219 1220 /// Does the given method (B::foo()) already override a method (A::foo()) 1221 /// such that A requires a vtordisp in B? If so, we don't need to add a 1222 /// new vtordisp for B in a yet-more-derived class C providing C::foo(). 1223 static bool overridesMethodRequiringVtorDisp(const ASTContext &Context, 1224 const CXXMethodDecl *M) { 1225 CXXMethodDecl::method_iterator 1226 I = M->begin_overridden_methods(), E = M->end_overridden_methods(); 1227 if (I == E) return false; 1228 1229 const ASTRecordLayout::VBaseOffsetsMapTy &offsets = 1230 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap(); 1231 do { 1232 const CXXMethodDecl *overridden = *I; 1233 1234 // If the overridden method's class isn't recognized as a virtual 1235 // base in the derived class, ignore it. 1236 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator 1237 it = offsets.find(overridden->getParent()); 1238 if (it == offsets.end()) continue; 1239 1240 // Otherwise, check if the overridden method's class needs a vtordisp. 1241 if (it->second.hasVtorDisp()) return true; 1242 1243 } while (++I != E); 1244 return false; 1245 } 1246 1247 /// In the Microsoft ABI, decide which of the virtual bases require a 1248 /// vtordisp field. 1249 void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD, 1250 ClassSetTy &vtordispVBases) { 1251 // Bail out if we have no virtual bases. 1252 assert(RD->getNumVBases()); 1253 1254 // Build up the set of virtual bases that we haven't decided yet. 1255 ClassSetTy undecidedVBases; 1256 for (CXXRecordDecl::base_class_const_iterator 1257 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) { 1258 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl(); 1259 undecidedVBases.insert(vbase); 1260 } 1261 assert(!undecidedVBases.empty()); 1262 1263 // A virtual base requires a vtordisp field in a derived class if it 1264 // requires a vtordisp field in a base class. Walk all the direct 1265 // bases and collect this information. 1266 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1267 E = RD->bases_end(); I != E; ++I) { 1268 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl(); 1269 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base); 1270 1271 // Iterate over the set of virtual bases provided by this class. 1272 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator 1273 VI = baseLayout.getVBaseOffsetsMap().begin(), 1274 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) { 1275 // If it doesn't need a vtordisp in this base, ignore it. 1276 if (!VI->second.hasVtorDisp()) continue; 1277 1278 // If we've already seen it and decided it needs a vtordisp, ignore it. 1279 if (!undecidedVBases.erase(VI->first)) 1280 continue; 1281 1282 // Add it. 1283 vtordispVBases.insert(VI->first); 1284 1285 // Quit as soon as we've decided everything. 1286 if (undecidedVBases.empty()) 1287 return; 1288 } 1289 } 1290 1291 // Okay, we have virtual bases that we haven't yet decided about. A 1292 // virtual base requires a vtordisp if any the non-destructor 1293 // virtual methods declared in this class directly override a method 1294 // provided by that virtual base. (If so, we need to emit a thunk 1295 // for that method, to be used in the construction vftable, which 1296 // applies an additional 'vtordisp' this-adjustment.) 1297 1298 // Collect the set of bases directly overridden by any method in this class. 1299 // It's possible that some of these classes won't be virtual bases, or won't be 1300 // provided by virtual bases, or won't be virtual bases in the overridden 1301 // instance but are virtual bases elsewhere. Only the last matters for what 1302 // we're doing, and we can ignore those: if we don't directly override 1303 // a method provided by a virtual copy of a base class, but we do directly 1304 // override a method provided by a non-virtual copy of that base class, 1305 // then we must indirectly override the method provided by the virtual base, 1306 // and so we should already have collected it in the loop above. 1307 ClassSetTy overriddenBases; 1308 for (CXXRecordDecl::method_iterator 1309 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) { 1310 // Ignore non-virtual methods and destructors. 1311 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual()) 1312 continue; 1313 1314 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(), 1315 E = M->end_overridden_methods(); I != E; ++I) { 1316 const CXXMethodDecl *overriddenMethod = (*I); 1317 1318 // Ignore methods that override methods from vbases that require 1319 // require vtordisps. 1320 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod)) 1321 continue; 1322 1323 // As an optimization, check immediately whether we're overriding 1324 // something from the undecided set. 1325 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent(); 1326 if (undecidedVBases.erase(overriddenBase)) { 1327 vtordispVBases.insert(overriddenBase); 1328 if (undecidedVBases.empty()) return; 1329 1330 // We can't 'continue;' here because one of our undecided 1331 // vbases might non-virtually inherit from this base. 1332 // Consider: 1333 // struct A { virtual void foo(); }; 1334 // struct B : A {}; 1335 // struct C : virtual A, virtual B { virtual void foo(); }; 1336 // We need a vtordisp for B here. 1337 } 1338 1339 // Otherwise, just collect it. 1340 overriddenBases.insert(overriddenBase); 1341 } 1342 } 1343 1344 // Walk the undecided v-bases and check whether they (non-virtually) 1345 // provide any of the overridden bases. We don't need to consider 1346 // virtual links because the vtordisp inheres to the layout 1347 // subobject containing the base. 1348 for (ClassSetTy::const_iterator 1349 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) { 1350 if (hasNonVirtualBaseInSet(*I, overriddenBases)) 1351 vtordispVBases.insert(*I); 1352 } 1353 } 1354 1355 /// hasNewVirtualFunction - Does the given polymorphic class declare a 1356 /// virtual function that does not override a method from any of its 1357 /// base classes? 1358 bool 1359 RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD, 1360 bool IgnoreDestructor) const { 1361 if (!RD->getNumBases()) 1362 return true; 1363 1364 for (CXXRecordDecl::method_iterator method = RD->method_begin(); 1365 method != RD->method_end(); 1366 ++method) { 1367 if (method->isVirtual() && !method->size_overridden_methods() && 1368 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) { 1369 return true; 1370 } 1371 } 1372 return false; 1373 } 1374 1375 /// isPossiblePrimaryBase - Is the given base class an acceptable 1376 /// primary base class? 1377 bool 1378 RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const { 1379 // In the Itanium ABI, a class can be a primary base class if it has 1380 // a vtable for any reason. 1381 if (!isMicrosoftCXXABI()) 1382 return base->isDynamicClass(); 1383 1384 // In the MS ABI, a class can only be a primary base class if it 1385 // provides a vf-table at a static offset. That means it has to be 1386 // non-virtual base. The existence of a separate vb-table means 1387 // that it's possible to get virtual functions only from a virtual 1388 // base, which we have to guard against. 1389 1390 // First off, it has to have virtual functions. 1391 if (!base->isPolymorphic()) return false; 1392 1393 // If it has no virtual bases, then the vfptr must be at a static offset. 1394 if (!base->getNumVBases()) return true; 1395 1396 // Otherwise, the necessary information is cached in the layout. 1397 const ASTRecordLayout &layout = Context.getASTRecordLayout(base); 1398 1399 // If the base has its own vfptr, it can be a primary base. 1400 if (layout.hasOwnVFPtr()) return true; 1401 1402 // If the base has a primary base class, then it can be a primary base. 1403 if (layout.getPrimaryBase()) return true; 1404 1405 // Otherwise it can't. 1406 return false; 1407 } 1408 1409 void 1410 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD, 1411 const CXXRecordDecl *MostDerivedClass) { 1412 const CXXRecordDecl *PrimaryBase; 1413 bool PrimaryBaseIsVirtual; 1414 1415 if (MostDerivedClass == RD) { 1416 PrimaryBase = this->PrimaryBase; 1417 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual; 1418 } else { 1419 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1420 PrimaryBase = Layout.getPrimaryBase(); 1421 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual(); 1422 } 1423 1424 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1425 E = RD->bases_end(); I != E; ++I) { 1426 assert(!I->getType()->isDependentType() && 1427 "Cannot layout class with dependent bases."); 1428 1429 const CXXRecordDecl *BaseDecl = 1430 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 1431 1432 if (I->isVirtual()) { 1433 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) { 1434 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl); 1435 1436 // Only lay out the virtual base if it's not an indirect primary base. 1437 if (!IndirectPrimaryBase) { 1438 // Only visit virtual bases once. 1439 if (!VisitedVirtualBases.insert(BaseDecl)) 1440 continue; 1441 1442 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl); 1443 assert(BaseInfo && "Did not find virtual base info!"); 1444 LayoutVirtualBase(BaseInfo); 1445 } 1446 } 1447 } 1448 1449 if (!BaseDecl->getNumVBases()) { 1450 // This base isn't interesting since it doesn't have any virtual bases. 1451 continue; 1452 } 1453 1454 LayoutVirtualBases(BaseDecl, MostDerivedClass); 1455 } 1456 } 1457 1458 void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) { 1459 if (!RD->getNumVBases()) 1460 return; 1461 1462 ClassSetTy VtordispVBases; 1463 computeVtordisps(RD, VtordispVBases); 1464 1465 // This is substantially simplified because there are no virtual 1466 // primary bases. 1467 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 1468 E = RD->vbases_end(); I != E; ++I) { 1469 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl(); 1470 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl); 1471 assert(BaseInfo && "Did not find virtual base info!"); 1472 1473 // If this base requires a vtordisp, add enough space for an int field. 1474 // This is apparently always 32-bits, even on x64. 1475 bool vtordispNeeded = false; 1476 if (VtordispVBases.count(BaseDecl)) { 1477 CharUnits IntSize = 1478 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8); 1479 1480 setSize(getSize() + IntSize); 1481 setDataSize(getSize()); 1482 vtordispNeeded = true; 1483 } 1484 1485 LayoutVirtualBase(BaseInfo, vtordispNeeded); 1486 } 1487 } 1488 1489 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base, 1490 bool IsVtordispNeed) { 1491 assert(!Base->Derived && "Trying to lay out a primary virtual base!"); 1492 1493 // Layout the base. 1494 CharUnits Offset = LayoutBase(Base); 1495 1496 // Add its base class offset. 1497 assert(!VBases.count(Base->Class) && "vbase offset already exists!"); 1498 VBases.insert(std::make_pair(Base->Class, 1499 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed))); 1500 1501 if (!isMicrosoftCXXABI()) 1502 AddPrimaryVirtualBaseOffsets(Base, Offset); 1503 } 1504 1505 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { 1506 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class); 1507 1508 1509 CharUnits Offset; 1510 1511 // Query the external layout to see if it provides an offset. 1512 bool HasExternalLayout = false; 1513 if (ExternalLayout) { 1514 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known; 1515 if (Base->IsVirtual) { 1516 Known = ExternalVirtualBaseOffsets.find(Base->Class); 1517 if (Known != ExternalVirtualBaseOffsets.end()) { 1518 Offset = Known->second; 1519 HasExternalLayout = true; 1520 } 1521 } else { 1522 Known = ExternalBaseOffsets.find(Base->Class); 1523 if (Known != ExternalBaseOffsets.end()) { 1524 Offset = Known->second; 1525 HasExternalLayout = true; 1526 } 1527 } 1528 } 1529 1530 // If we have an empty base class, try to place it at offset 0. 1531 if (Base->Class->isEmpty() && 1532 (!HasExternalLayout || Offset == CharUnits::Zero()) && 1533 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) { 1534 setSize(std::max(getSize(), Layout.getSize())); 1535 1536 return CharUnits::Zero(); 1537 } 1538 1539 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign(); 1540 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign; 1541 1542 // The maximum field alignment overrides base align. 1543 if (!MaxFieldAlignment.isZero()) { 1544 BaseAlign = std::min(BaseAlign, MaxFieldAlignment); 1545 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment); 1546 } 1547 1548 if (!HasExternalLayout) { 1549 // Round up the current record size to the base's alignment boundary. 1550 Offset = getDataSize().RoundUpToAlignment(BaseAlign); 1551 1552 // Try to place the base. 1553 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset)) 1554 Offset += BaseAlign; 1555 } else { 1556 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset); 1557 (void)Allowed; 1558 assert(Allowed && "Base subobject externally placed at overlapping offset"); 1559 } 1560 1561 if (!Base->Class->isEmpty()) { 1562 // Update the data size. 1563 setDataSize(Offset + Layout.getNonVirtualSize()); 1564 1565 setSize(std::max(getSize(), getDataSize())); 1566 } else 1567 setSize(std::max(getSize(), Offset + Layout.getSize())); 1568 1569 // Remember max struct/class alignment. 1570 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 1571 1572 return Offset; 1573 } 1574 1575 void RecordLayoutBuilder::InitializeLayout(const Decl *D) { 1576 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 1577 IsUnion = RD->isUnion(); 1578 1579 Packed = D->hasAttr<PackedAttr>(); 1580 1581 IsMsStruct = D->hasAttr<MsStructAttr>(); 1582 1583 // Honor the default struct packing maximum alignment flag. 1584 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) { 1585 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment); 1586 } 1587 1588 // mac68k alignment supersedes maximum field alignment and attribute aligned, 1589 // and forces all structures to have 2-byte alignment. The IBM docs on it 1590 // allude to additional (more complicated) semantics, especially with regard 1591 // to bit-fields, but gcc appears not to follow that. 1592 if (D->hasAttr<AlignMac68kAttr>()) { 1593 IsMac68kAlign = true; 1594 MaxFieldAlignment = CharUnits::fromQuantity(2); 1595 Alignment = CharUnits::fromQuantity(2); 1596 } else { 1597 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>()) 1598 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment()); 1599 1600 if (unsigned MaxAlign = D->getMaxAlignment()) 1601 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign)); 1602 } 1603 1604 // If there is an external AST source, ask it for the various offsets. 1605 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 1606 if (ExternalASTSource *External = Context.getExternalSource()) { 1607 ExternalLayout = External->layoutRecordType(RD, 1608 ExternalSize, 1609 ExternalAlign, 1610 ExternalFieldOffsets, 1611 ExternalBaseOffsets, 1612 ExternalVirtualBaseOffsets); 1613 1614 // Update based on external alignment. 1615 if (ExternalLayout) { 1616 if (ExternalAlign > 0) { 1617 Alignment = Context.toCharUnitsFromBits(ExternalAlign); 1618 UnpackedAlignment = Alignment; 1619 } else { 1620 // The external source didn't have alignment information; infer it. 1621 InferAlignment = true; 1622 } 1623 } 1624 } 1625 } 1626 1627 void RecordLayoutBuilder::Layout(const RecordDecl *D) { 1628 InitializeLayout(D); 1629 LayoutFields(D); 1630 1631 // Finally, round the size of the total struct up to the alignment of the 1632 // struct itself. 1633 FinishLayout(D); 1634 } 1635 1636 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) { 1637 InitializeLayout(RD); 1638 1639 // Lay out the vtable and the non-virtual bases. 1640 LayoutNonVirtualBases(RD); 1641 1642 LayoutFields(RD); 1643 1644 NonVirtualSize = Context.toCharUnitsFromBits( 1645 llvm::RoundUpToAlignment(getSizeInBits(), 1646 Context.getTargetInfo().getCharAlign())); 1647 NonVirtualAlignment = Alignment; 1648 1649 if (isMicrosoftCXXABI()) { 1650 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) { 1651 CharUnits AlignMember = 1652 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize; 1653 1654 setSize(getSize() + AlignMember); 1655 setDataSize(getSize()); 1656 1657 NonVirtualSize = Context.toCharUnitsFromBits( 1658 llvm::RoundUpToAlignment(getSizeInBits(), 1659 Context.getTargetInfo().getCharAlign())); 1660 } 1661 1662 MSLayoutVirtualBases(RD); 1663 } else { 1664 // Lay out the virtual bases and add the primary virtual base offsets. 1665 LayoutVirtualBases(RD, RD); 1666 } 1667 1668 // Finally, round the size of the total struct up to the alignment 1669 // of the struct itself. 1670 FinishLayout(RD); 1671 1672 #ifndef NDEBUG 1673 // Check that we have base offsets for all bases. 1674 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1675 E = RD->bases_end(); I != E; ++I) { 1676 if (I->isVirtual()) 1677 continue; 1678 1679 const CXXRecordDecl *BaseDecl = 1680 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1681 1682 assert(Bases.count(BaseDecl) && "Did not find base offset!"); 1683 } 1684 1685 // And all virtual bases. 1686 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 1687 E = RD->vbases_end(); I != E; ++I) { 1688 const CXXRecordDecl *BaseDecl = 1689 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1690 1691 assert(VBases.count(BaseDecl) && "Did not find base offset!"); 1692 } 1693 #endif 1694 } 1695 1696 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) { 1697 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 1698 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD); 1699 1700 UpdateAlignment(SL.getAlignment()); 1701 1702 // We start laying out ivars not at the end of the superclass 1703 // structure, but at the next byte following the last field. 1704 setSize(SL.getDataSize()); 1705 setDataSize(getSize()); 1706 } 1707 1708 InitializeLayout(D); 1709 // Layout each ivar sequentially. 1710 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD; 1711 IVD = IVD->getNextIvar()) 1712 LayoutField(IVD); 1713 1714 // Finally, round the size of the total struct up to the alignment of the 1715 // struct itself. 1716 FinishLayout(D); 1717 } 1718 1719 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) { 1720 // Layout each field, for now, just sequentially, respecting alignment. In 1721 // the future, this will need to be tweakable by targets. 1722 const FieldDecl *LastFD = 0; 1723 ZeroLengthBitfield = 0; 1724 unsigned RemainingInAlignment = 0; 1725 for (RecordDecl::field_iterator Field = D->field_begin(), 1726 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) { 1727 if (IsMsStruct) { 1728 FieldDecl *FD = *Field; 1729 if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD)) 1730 ZeroLengthBitfield = FD; 1731 // Zero-length bitfields following non-bitfield members are 1732 // ignored: 1733 else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD)) 1734 continue; 1735 // FIXME. streamline these conditions into a simple one. 1736 else if (Context.BitfieldFollowsBitfield(FD, LastFD) || 1737 Context.BitfieldFollowsNonBitfield(FD, LastFD) || 1738 Context.NonBitfieldFollowsBitfield(FD, LastFD)) { 1739 // 1) Adjacent bit fields are packed into the same 1-, 2-, or 1740 // 4-byte allocation unit if the integral types are the same 1741 // size and if the next bit field fits into the current 1742 // allocation unit without crossing the boundary imposed by the 1743 // common alignment requirements of the bit fields. 1744 // 2) Establish a new alignment for a bitfield following 1745 // a non-bitfield if size of their types differ. 1746 // 3) Establish a new alignment for a non-bitfield following 1747 // a bitfield if size of their types differ. 1748 std::pair<uint64_t, unsigned> FieldInfo = 1749 Context.getTypeInfo(FD->getType()); 1750 uint64_t TypeSize = FieldInfo.first; 1751 unsigned FieldAlign = FieldInfo.second; 1752 // This check is needed for 'long long' in -m32 mode. 1753 if (TypeSize > FieldAlign && 1754 (Context.hasSameType(FD->getType(), 1755 Context.UnsignedLongLongTy) 1756 ||Context.hasSameType(FD->getType(), 1757 Context.LongLongTy))) 1758 FieldAlign = TypeSize; 1759 FieldInfo = Context.getTypeInfo(LastFD->getType()); 1760 uint64_t TypeSizeLastFD = FieldInfo.first; 1761 unsigned FieldAlignLastFD = FieldInfo.second; 1762 // This check is needed for 'long long' in -m32 mode. 1763 if (TypeSizeLastFD > FieldAlignLastFD && 1764 (Context.hasSameType(LastFD->getType(), 1765 Context.UnsignedLongLongTy) 1766 || Context.hasSameType(LastFD->getType(), 1767 Context.LongLongTy))) 1768 FieldAlignLastFD = TypeSizeLastFD; 1769 1770 if (TypeSizeLastFD != TypeSize) { 1771 if (RemainingInAlignment && 1772 LastFD && LastFD->isBitField() && 1773 LastFD->getBitWidthValue(Context)) { 1774 // If previous field was a bitfield with some remaining unfilled 1775 // bits, pad the field so current field starts on its type boundary. 1776 uint64_t FieldOffset = 1777 getDataSizeInBits() - UnfilledBitsInLastByte; 1778 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset; 1779 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1780 Context.getTargetInfo().getCharAlign())); 1781 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1782 RemainingInAlignment = 0; 1783 } 1784 1785 uint64_t UnpaddedFieldOffset = 1786 getDataSizeInBits() - UnfilledBitsInLastByte; 1787 FieldAlign = std::max(FieldAlign, FieldAlignLastFD); 1788 1789 // The maximum field alignment overrides the aligned attribute. 1790 if (!MaxFieldAlignment.isZero()) { 1791 unsigned MaxFieldAlignmentInBits = 1792 Context.toBits(MaxFieldAlignment); 1793 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits); 1794 } 1795 1796 uint64_t NewSizeInBits = 1797 llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign); 1798 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1799 Context.getTargetInfo().getCharAlign())); 1800 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits; 1801 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1802 } 1803 if (FD->isBitField()) { 1804 uint64_t FieldSize = FD->getBitWidthValue(Context); 1805 assert (FieldSize > 0 && "LayoutFields - ms_struct layout"); 1806 if (RemainingInAlignment < FieldSize) 1807 RemainingInAlignment = TypeSize - FieldSize; 1808 else 1809 RemainingInAlignment -= FieldSize; 1810 } 1811 } 1812 else if (FD->isBitField()) { 1813 uint64_t FieldSize = FD->getBitWidthValue(Context); 1814 std::pair<uint64_t, unsigned> FieldInfo = 1815 Context.getTypeInfo(FD->getType()); 1816 uint64_t TypeSize = FieldInfo.first; 1817 RemainingInAlignment = TypeSize - FieldSize; 1818 } 1819 LastFD = FD; 1820 } 1821 else if (!Context.getTargetInfo().useBitFieldTypeAlignment() && 1822 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) { 1823 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 1824 ZeroLengthBitfield = *Field; 1825 } 1826 LayoutField(*Field); 1827 } 1828 if (IsMsStruct && RemainingInAlignment && 1829 LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) { 1830 // If we ended a bitfield before the full length of the type then 1831 // pad the struct out to the full length of the last type. 1832 uint64_t FieldOffset = 1833 getDataSizeInBits() - UnfilledBitsInLastByte; 1834 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset; 1835 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1836 Context.getTargetInfo().getCharAlign())); 1837 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1838 } 1839 } 1840 1841 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize, 1842 uint64_t TypeSize, 1843 bool FieldPacked, 1844 const FieldDecl *D) { 1845 assert(Context.getLangOpts().CPlusPlus && 1846 "Can only have wide bit-fields in C++!"); 1847 1848 // Itanium C++ ABI 2.4: 1849 // If sizeof(T)*8 < n, let T' be the largest integral POD type with 1850 // sizeof(T')*8 <= n. 1851 1852 QualType IntegralPODTypes[] = { 1853 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy, 1854 Context.UnsignedLongTy, Context.UnsignedLongLongTy 1855 }; 1856 1857 QualType Type; 1858 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes); 1859 I != E; ++I) { 1860 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]); 1861 1862 if (Size > FieldSize) 1863 break; 1864 1865 Type = IntegralPODTypes[I]; 1866 } 1867 assert(!Type.isNull() && "Did not find a type!"); 1868 1869 CharUnits TypeAlign = Context.getTypeAlignInChars(Type); 1870 1871 // We're not going to use any of the unfilled bits in the last byte. 1872 UnfilledBitsInLastByte = 0; 1873 1874 uint64_t FieldOffset; 1875 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte; 1876 1877 if (IsUnion) { 1878 setDataSize(std::max(getDataSizeInBits(), FieldSize)); 1879 FieldOffset = 0; 1880 } else { 1881 // The bitfield is allocated starting at the next offset aligned 1882 // appropriately for T', with length n bits. 1883 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(), 1884 Context.toBits(TypeAlign)); 1885 1886 uint64_t NewSizeInBits = FieldOffset + FieldSize; 1887 1888 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1889 Context.getTargetInfo().getCharAlign())); 1890 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits; 1891 } 1892 1893 // Place this field at the current location. 1894 FieldOffsets.push_back(FieldOffset); 1895 1896 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset, 1897 Context.toBits(TypeAlign), FieldPacked, D); 1898 1899 // Update the size. 1900 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1901 1902 // Remember max struct/class alignment. 1903 UpdateAlignment(TypeAlign); 1904 } 1905 1906 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { 1907 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 1908 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte; 1909 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset; 1910 uint64_t FieldSize = D->getBitWidthValue(Context); 1911 1912 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType()); 1913 uint64_t TypeSize = FieldInfo.first; 1914 unsigned FieldAlign = FieldInfo.second; 1915 1916 // This check is needed for 'long long' in -m32 mode. 1917 if (IsMsStruct && (TypeSize > FieldAlign) && 1918 (Context.hasSameType(D->getType(), 1919 Context.UnsignedLongLongTy) 1920 || Context.hasSameType(D->getType(), Context.LongLongTy))) 1921 FieldAlign = TypeSize; 1922 1923 if (ZeroLengthBitfield) { 1924 std::pair<uint64_t, unsigned> FieldInfo; 1925 unsigned ZeroLengthBitfieldAlignment; 1926 if (IsMsStruct) { 1927 // If a zero-length bitfield is inserted after a bitfield, 1928 // and the alignment of the zero-length bitfield is 1929 // greater than the member that follows it, `bar', `bar' 1930 // will be aligned as the type of the zero-length bitfield. 1931 if (ZeroLengthBitfield != D) { 1932 FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType()); 1933 ZeroLengthBitfieldAlignment = FieldInfo.second; 1934 // Ignore alignment of subsequent zero-length bitfields. 1935 if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0)) 1936 FieldAlign = ZeroLengthBitfieldAlignment; 1937 if (FieldSize) 1938 ZeroLengthBitfield = 0; 1939 } 1940 } else { 1941 // The alignment of a zero-length bitfield affects the alignment 1942 // of the next member. The alignment is the max of the zero 1943 // length bitfield's alignment and a target specific fixed value. 1944 unsigned ZeroLengthBitfieldBoundary = 1945 Context.getTargetInfo().getZeroLengthBitfieldBoundary(); 1946 if (ZeroLengthBitfieldBoundary > FieldAlign) 1947 FieldAlign = ZeroLengthBitfieldBoundary; 1948 } 1949 } 1950 1951 if (FieldSize > TypeSize) { 1952 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D); 1953 return; 1954 } 1955 1956 // The align if the field is not packed. This is to check if the attribute 1957 // was unnecessary (-Wpacked). 1958 unsigned UnpackedFieldAlign = FieldAlign; 1959 uint64_t UnpackedFieldOffset = FieldOffset; 1960 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield) 1961 UnpackedFieldAlign = 1; 1962 1963 if (FieldPacked || 1964 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)) 1965 FieldAlign = 1; 1966 FieldAlign = std::max(FieldAlign, D->getMaxAlignment()); 1967 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment()); 1968 1969 // The maximum field alignment overrides the aligned attribute. 1970 if (!MaxFieldAlignment.isZero() && FieldSize != 0) { 1971 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment); 1972 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits); 1973 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits); 1974 } 1975 1976 // Check if we need to add padding to give the field the correct alignment. 1977 if (FieldSize == 0 || 1978 (MaxFieldAlignment.isZero() && 1979 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) 1980 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign); 1981 1982 if (FieldSize == 0 || 1983 (MaxFieldAlignment.isZero() && 1984 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize)) 1985 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset, 1986 UnpackedFieldAlign); 1987 1988 // Padding members don't affect overall alignment, unless zero length bitfield 1989 // alignment is enabled. 1990 if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment()) 1991 FieldAlign = UnpackedFieldAlign = 1; 1992 1993 if (!IsMsStruct) 1994 ZeroLengthBitfield = 0; 1995 1996 if (ExternalLayout) 1997 FieldOffset = updateExternalFieldOffset(D, FieldOffset); 1998 1999 // Place this field at the current location. 2000 FieldOffsets.push_back(FieldOffset); 2001 2002 if (!ExternalLayout) 2003 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset, 2004 UnpackedFieldAlign, FieldPacked, D); 2005 2006 // Update DataSize to include the last byte containing (part of) the bitfield. 2007 if (IsUnion) { 2008 // FIXME: I think FieldSize should be TypeSize here. 2009 setDataSize(std::max(getDataSizeInBits(), FieldSize)); 2010 } else { 2011 uint64_t NewSizeInBits = FieldOffset + FieldSize; 2012 2013 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 2014 Context.getTargetInfo().getCharAlign())); 2015 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits; 2016 } 2017 2018 // Update the size. 2019 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 2020 2021 // Remember max struct/class alignment. 2022 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), 2023 Context.toCharUnitsFromBits(UnpackedFieldAlign)); 2024 } 2025 2026 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) { 2027 if (D->isBitField()) { 2028 LayoutBitField(D); 2029 return; 2030 } 2031 2032 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte; 2033 2034 // Reset the unfilled bits. 2035 UnfilledBitsInLastByte = 0; 2036 2037 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 2038 CharUnits FieldOffset = 2039 IsUnion ? CharUnits::Zero() : getDataSize(); 2040 CharUnits FieldSize; 2041 CharUnits FieldAlign; 2042 2043 if (D->getType()->isIncompleteArrayType()) { 2044 // This is a flexible array member; we can't directly 2045 // query getTypeInfo about these, so we figure it out here. 2046 // Flexible array members don't have any size, but they 2047 // have to be aligned appropriately for their element type. 2048 FieldSize = CharUnits::Zero(); 2049 const ArrayType* ATy = Context.getAsArrayType(D->getType()); 2050 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType()); 2051 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) { 2052 unsigned AS = RT->getPointeeType().getAddressSpace(); 2053 FieldSize = 2054 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS)); 2055 FieldAlign = 2056 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS)); 2057 } else { 2058 std::pair<CharUnits, CharUnits> FieldInfo = 2059 Context.getTypeInfoInChars(D->getType()); 2060 FieldSize = FieldInfo.first; 2061 FieldAlign = FieldInfo.second; 2062 2063 if (ZeroLengthBitfield) { 2064 CharUnits ZeroLengthBitfieldBoundary = 2065 Context.toCharUnitsFromBits( 2066 Context.getTargetInfo().getZeroLengthBitfieldBoundary()); 2067 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) { 2068 // If a zero-length bitfield is inserted after a bitfield, 2069 // and the alignment of the zero-length bitfield is 2070 // greater than the member that follows it, `bar', `bar' 2071 // will be aligned as the type of the zero-length bitfield. 2072 std::pair<CharUnits, CharUnits> FieldInfo = 2073 Context.getTypeInfoInChars(ZeroLengthBitfield->getType()); 2074 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second; 2075 if (ZeroLengthBitfieldAlignment > FieldAlign) 2076 FieldAlign = ZeroLengthBitfieldAlignment; 2077 } else if (ZeroLengthBitfieldBoundary > FieldAlign) { 2078 // Align 'bar' based on a fixed alignment specified by the target. 2079 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() && 2080 "ZeroLengthBitfieldBoundary should only be used in conjunction" 2081 " with useZeroLengthBitfieldAlignment."); 2082 FieldAlign = ZeroLengthBitfieldBoundary; 2083 } 2084 ZeroLengthBitfield = 0; 2085 } 2086 2087 if (Context.getLangOpts().MSBitfields || IsMsStruct) { 2088 // If MS bitfield layout is required, figure out what type is being 2089 // laid out and align the field to the width of that type. 2090 2091 // Resolve all typedefs down to their base type and round up the field 2092 // alignment if necessary. 2093 QualType T = Context.getBaseElementType(D->getType()); 2094 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) { 2095 CharUnits TypeSize = Context.getTypeSizeInChars(BTy); 2096 if (TypeSize > FieldAlign) 2097 FieldAlign = TypeSize; 2098 } 2099 } 2100 } 2101 2102 // The align if the field is not packed. This is to check if the attribute 2103 // was unnecessary (-Wpacked). 2104 CharUnits UnpackedFieldAlign = FieldAlign; 2105 CharUnits UnpackedFieldOffset = FieldOffset; 2106 2107 if (FieldPacked) 2108 FieldAlign = CharUnits::One(); 2109 CharUnits MaxAlignmentInChars = 2110 Context.toCharUnitsFromBits(D->getMaxAlignment()); 2111 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars); 2112 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars); 2113 2114 // The maximum field alignment overrides the aligned attribute. 2115 if (!MaxFieldAlignment.isZero()) { 2116 FieldAlign = std::min(FieldAlign, MaxFieldAlignment); 2117 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment); 2118 } 2119 2120 // Round up the current record size to the field's alignment boundary. 2121 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign); 2122 UnpackedFieldOffset = 2123 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign); 2124 2125 if (ExternalLayout) { 2126 FieldOffset = Context.toCharUnitsFromBits( 2127 updateExternalFieldOffset(D, Context.toBits(FieldOffset))); 2128 2129 if (!IsUnion && EmptySubobjects) { 2130 // Record the fact that we're placing a field at this offset. 2131 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset); 2132 (void)Allowed; 2133 assert(Allowed && "Externally-placed field cannot be placed here"); 2134 } 2135 } else { 2136 if (!IsUnion && EmptySubobjects) { 2137 // Check if we can place the field at this offset. 2138 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) { 2139 // We couldn't place the field at the offset. Try again at a new offset. 2140 FieldOffset += FieldAlign; 2141 } 2142 } 2143 } 2144 2145 // Place this field at the current location. 2146 FieldOffsets.push_back(Context.toBits(FieldOffset)); 2147 2148 if (!ExternalLayout) 2149 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, 2150 Context.toBits(UnpackedFieldOffset), 2151 Context.toBits(UnpackedFieldAlign), FieldPacked, D); 2152 2153 // Reserve space for this field. 2154 uint64_t FieldSizeInBits = Context.toBits(FieldSize); 2155 if (IsUnion) 2156 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits)); 2157 else 2158 setDataSize(FieldOffset + FieldSize); 2159 2160 // Update the size. 2161 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 2162 2163 // Remember max struct/class alignment. 2164 UpdateAlignment(FieldAlign, UnpackedFieldAlign); 2165 } 2166 2167 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) { 2168 if (ExternalLayout) { 2169 setSize(ExternalSize); 2170 return; 2171 } 2172 2173 // In C++, records cannot be of size 0. 2174 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) { 2175 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 2176 // Compatibility with gcc requires a class (pod or non-pod) 2177 // which is not empty but of size 0; such as having fields of 2178 // array of zero-length, remains of Size 0 2179 if (RD->isEmpty()) 2180 setSize(CharUnits::One()); 2181 } 2182 else 2183 setSize(CharUnits::One()); 2184 } 2185 2186 // MSVC doesn't round up to the alignment of the record with virtual bases. 2187 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 2188 if (isMicrosoftCXXABI() && RD->getNumVBases()) 2189 return; 2190 } 2191 2192 // Finally, round the size of the record up to the alignment of the 2193 // record itself. 2194 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte; 2195 uint64_t UnpackedSizeInBits = 2196 llvm::RoundUpToAlignment(getSizeInBits(), 2197 Context.toBits(UnpackedAlignment)); 2198 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits); 2199 setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment))); 2200 2201 unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); 2202 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) { 2203 // Warn if padding was introduced to the struct/class/union. 2204 if (getSizeInBits() > UnpaddedSize) { 2205 unsigned PadSize = getSizeInBits() - UnpaddedSize; 2206 bool InBits = true; 2207 if (PadSize % CharBitNum == 0) { 2208 PadSize = PadSize / CharBitNum; 2209 InBits = false; 2210 } 2211 Diag(RD->getLocation(), diag::warn_padded_struct_size) 2212 << Context.getTypeDeclType(RD) 2213 << PadSize 2214 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not 2215 } 2216 2217 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't 2218 // bother since there won't be alignment issues. 2219 if (Packed && UnpackedAlignment > CharUnits::One() && 2220 getSize() == UnpackedSize) 2221 Diag(D->getLocation(), diag::warn_unnecessary_packed) 2222 << Context.getTypeDeclType(RD); 2223 } 2224 } 2225 2226 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment, 2227 CharUnits UnpackedNewAlignment) { 2228 // The alignment is not modified when using 'mac68k' alignment or when 2229 // we have an externally-supplied layout that also provides overall alignment. 2230 if (IsMac68kAlign || (ExternalLayout && !InferAlignment)) 2231 return; 2232 2233 if (NewAlignment > Alignment) { 2234 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() && 2235 "Alignment not a power of 2")); 2236 Alignment = NewAlignment; 2237 } 2238 2239 if (UnpackedNewAlignment > UnpackedAlignment) { 2240 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() && 2241 "Alignment not a power of 2")); 2242 UnpackedAlignment = UnpackedNewAlignment; 2243 } 2244 } 2245 2246 uint64_t 2247 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, 2248 uint64_t ComputedOffset) { 2249 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() && 2250 "Field does not have an external offset"); 2251 2252 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field]; 2253 2254 if (InferAlignment && ExternalFieldOffset < ComputedOffset) { 2255 // The externally-supplied field offset is before the field offset we 2256 // computed. Assume that the structure is packed. 2257 Alignment = CharUnits::fromQuantity(1); 2258 InferAlignment = false; 2259 } 2260 2261 // Use the externally-supplied field offset. 2262 return ExternalFieldOffset; 2263 } 2264 2265 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset, 2266 uint64_t UnpaddedOffset, 2267 uint64_t UnpackedOffset, 2268 unsigned UnpackedAlign, 2269 bool isPacked, 2270 const FieldDecl *D) { 2271 // We let objc ivars without warning, objc interfaces generally are not used 2272 // for padding tricks. 2273 if (isa<ObjCIvarDecl>(D)) 2274 return; 2275 2276 // Don't warn about structs created without a SourceLocation. This can 2277 // be done by clients of the AST, such as codegen. 2278 if (D->getLocation().isInvalid()) 2279 return; 2280 2281 unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); 2282 2283 // Warn if padding was introduced to the struct/class. 2284 if (!IsUnion && Offset > UnpaddedOffset) { 2285 unsigned PadSize = Offset - UnpaddedOffset; 2286 bool InBits = true; 2287 if (PadSize % CharBitNum == 0) { 2288 PadSize = PadSize / CharBitNum; 2289 InBits = false; 2290 } 2291 if (D->getIdentifier()) 2292 Diag(D->getLocation(), diag::warn_padded_struct_field) 2293 << (D->getParent()->isStruct() ? 0 : 1) // struct|class 2294 << Context.getTypeDeclType(D->getParent()) 2295 << PadSize 2296 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not 2297 << D->getIdentifier(); 2298 else 2299 Diag(D->getLocation(), diag::warn_padded_struct_anon_field) 2300 << (D->getParent()->isStruct() ? 0 : 1) // struct|class 2301 << Context.getTypeDeclType(D->getParent()) 2302 << PadSize 2303 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not 2304 } 2305 2306 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't 2307 // bother since there won't be alignment issues. 2308 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset) 2309 Diag(D->getLocation(), diag::warn_unnecessary_packed) 2310 << D->getIdentifier(); 2311 } 2312 2313 const CXXMethodDecl * 2314 RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) { 2315 // If a class isn't polymorphic it doesn't have a key function. 2316 if (!RD->isPolymorphic()) 2317 return 0; 2318 2319 // A class that is not externally visible doesn't have a key function. (Or 2320 // at least, there's no point to assigning a key function to such a class; 2321 // this doesn't affect the ABI.) 2322 if (RD->getLinkage() != ExternalLinkage) 2323 return 0; 2324 2325 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6. 2326 // Same behavior as GCC. 2327 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind(); 2328 if (TSK == TSK_ImplicitInstantiation || 2329 TSK == TSK_ExplicitInstantiationDefinition) 2330 return 0; 2331 2332 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 2333 E = RD->method_end(); I != E; ++I) { 2334 const CXXMethodDecl *MD = *I; 2335 2336 if (!MD->isVirtual()) 2337 continue; 2338 2339 if (MD->isPure()) 2340 continue; 2341 2342 // Ignore implicit member functions, they are always marked as inline, but 2343 // they don't have a body until they're defined. 2344 if (MD->isImplicit()) 2345 continue; 2346 2347 if (MD->isInlineSpecified()) 2348 continue; 2349 2350 if (MD->hasInlineBody()) 2351 continue; 2352 2353 // We found it. 2354 return MD; 2355 } 2356 2357 return 0; 2358 } 2359 2360 DiagnosticBuilder 2361 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) { 2362 return Context.getDiagnostics().Report(Loc, DiagID); 2363 } 2364 2365 /// getASTRecordLayout - Get or compute information about the layout of the 2366 /// specified record (struct/union/class), which indicates its size and field 2367 /// position information. 2368 const ASTRecordLayout & 2369 ASTContext::getASTRecordLayout(const RecordDecl *D) const { 2370 // These asserts test different things. A record has a definition 2371 // as soon as we begin to parse the definition. That definition is 2372 // not a complete definition (which is what isDefinition() tests) 2373 // until we *finish* parsing the definition. 2374 2375 if (D->hasExternalLexicalStorage() && !D->getDefinition()) 2376 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D)); 2377 2378 D = D->getDefinition(); 2379 assert(D && "Cannot get layout of forward declarations!"); 2380 assert(D->isCompleteDefinition() && "Cannot layout type before complete!"); 2381 2382 // Look up this layout, if already laid out, return what we have. 2383 // Note that we can't save a reference to the entry because this function 2384 // is recursive. 2385 const ASTRecordLayout *Entry = ASTRecordLayouts[D]; 2386 if (Entry) return *Entry; 2387 2388 const ASTRecordLayout *NewEntry; 2389 2390 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 2391 EmptySubobjectMap EmptySubobjects(*this, RD); 2392 RecordLayoutBuilder Builder(*this, &EmptySubobjects); 2393 Builder.Layout(RD); 2394 2395 // MSVC gives the vb-table pointer an alignment equal to that of 2396 // the non-virtual part of the structure. That's an inherently 2397 // multi-pass operation. If our first pass doesn't give us 2398 // adequate alignment, try again with the specified minimum 2399 // alignment. This is *much* more maintainable than computing the 2400 // alignment in advance in a separately-coded pass; it's also 2401 // significantly more efficient in the common case where the 2402 // vb-table doesn't need extra padding. 2403 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) && 2404 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) { 2405 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment); 2406 Builder.Layout(RD); 2407 } 2408 2409 // FIXME: This is not always correct. See the part about bitfields at 2410 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info. 2411 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout. 2412 // This does not affect the calculations of MSVC layouts 2413 bool IsPODForThePurposeOfLayout = 2414 (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD()); 2415 2416 // FIXME: This should be done in FinalizeLayout. 2417 CharUnits DataSize = 2418 IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize(); 2419 CharUnits NonVirtualSize = 2420 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize; 2421 2422 NewEntry = 2423 new (*this) ASTRecordLayout(*this, Builder.getSize(), 2424 Builder.Alignment, 2425 Builder.HasOwnVFPtr, 2426 Builder.VBPtrOffset, 2427 DataSize, 2428 Builder.FieldOffsets.data(), 2429 Builder.FieldOffsets.size(), 2430 NonVirtualSize, 2431 Builder.NonVirtualAlignment, 2432 EmptySubobjects.SizeOfLargestEmptySubobject, 2433 Builder.PrimaryBase, 2434 Builder.PrimaryBaseIsVirtual, 2435 Builder.Bases, Builder.VBases); 2436 } else { 2437 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0); 2438 Builder.Layout(D); 2439 2440 NewEntry = 2441 new (*this) ASTRecordLayout(*this, Builder.getSize(), 2442 Builder.Alignment, 2443 Builder.getSize(), 2444 Builder.FieldOffsets.data(), 2445 Builder.FieldOffsets.size()); 2446 } 2447 2448 ASTRecordLayouts[D] = NewEntry; 2449 2450 if (getLangOpts().DumpRecordLayouts) { 2451 llvm::errs() << "\n*** Dumping AST Record Layout\n"; 2452 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple); 2453 } 2454 2455 return *NewEntry; 2456 } 2457 2458 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) { 2459 RD = cast<CXXRecordDecl>(RD->getDefinition()); 2460 assert(RD && "Cannot get key function for forward declarations!"); 2461 2462 const CXXMethodDecl *&Entry = KeyFunctions[RD]; 2463 if (!Entry) 2464 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD); 2465 2466 return Entry; 2467 } 2468 2469 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) { 2470 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent()); 2471 return Layout.getFieldOffset(FD->getFieldIndex()); 2472 } 2473 2474 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const { 2475 uint64_t OffsetInBits; 2476 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 2477 OffsetInBits = ::getFieldOffset(*this, FD); 2478 } else { 2479 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD); 2480 2481 OffsetInBits = 0; 2482 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(), 2483 CE = IFD->chain_end(); 2484 CI != CE; ++CI) 2485 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI)); 2486 } 2487 2488 return OffsetInBits; 2489 } 2490 2491 /// getObjCLayout - Get or compute information about the layout of the 2492 /// given interface. 2493 /// 2494 /// \param Impl - If given, also include the layout of the interface's 2495 /// implementation. This may differ by including synthesized ivars. 2496 const ASTRecordLayout & 2497 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 2498 const ObjCImplementationDecl *Impl) const { 2499 // Retrieve the definition 2500 if (D->hasExternalLexicalStorage() && !D->getDefinition()) 2501 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D)); 2502 D = D->getDefinition(); 2503 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!"); 2504 2505 // Look up this layout, if already laid out, return what we have. 2506 ObjCContainerDecl *Key = 2507 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 2508 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 2509 return *Entry; 2510 2511 // Add in synthesized ivar count if laying out an implementation. 2512 if (Impl) { 2513 unsigned SynthCount = CountNonClassIvars(D); 2514 // If there aren't any sythesized ivars then reuse the interface 2515 // entry. Note we can't cache this because we simply free all 2516 // entries later; however we shouldn't look up implementations 2517 // frequently. 2518 if (SynthCount == 0) 2519 return getObjCLayout(D, 0); 2520 } 2521 2522 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0); 2523 Builder.Layout(D); 2524 2525 const ASTRecordLayout *NewEntry = 2526 new (*this) ASTRecordLayout(*this, Builder.getSize(), 2527 Builder.Alignment, 2528 Builder.getDataSize(), 2529 Builder.FieldOffsets.data(), 2530 Builder.FieldOffsets.size()); 2531 2532 ObjCLayouts[Key] = NewEntry; 2533 2534 return *NewEntry; 2535 } 2536 2537 static void PrintOffset(raw_ostream &OS, 2538 CharUnits Offset, unsigned IndentLevel) { 2539 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity()); 2540 OS.indent(IndentLevel * 2); 2541 } 2542 2543 static void DumpCXXRecordLayout(raw_ostream &OS, 2544 const CXXRecordDecl *RD, const ASTContext &C, 2545 CharUnits Offset, 2546 unsigned IndentLevel, 2547 const char* Description, 2548 bool IncludeVirtualBases) { 2549 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD); 2550 2551 PrintOffset(OS, Offset, IndentLevel); 2552 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString(); 2553 if (Description) 2554 OS << ' ' << Description; 2555 if (RD->isEmpty()) 2556 OS << " (empty)"; 2557 OS << '\n'; 2558 2559 IndentLevel++; 2560 2561 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 2562 bool HasVfptr = Layout.hasOwnVFPtr(); 2563 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1); 2564 2565 // Vtable pointer. 2566 if (RD->isDynamicClass() && !PrimaryBase && 2567 C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) { 2568 PrintOffset(OS, Offset, IndentLevel); 2569 OS << '(' << *RD << " vtable pointer)\n"; 2570 } 2571 2572 // Dump (non-virtual) bases 2573 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 2574 E = RD->bases_end(); I != E; ++I) { 2575 assert(!I->getType()->isDependentType() && 2576 "Cannot layout class with dependent bases."); 2577 if (I->isVirtual()) 2578 continue; 2579 2580 const CXXRecordDecl *Base = 2581 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 2582 2583 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base); 2584 2585 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel, 2586 Base == PrimaryBase ? "(primary base)" : "(base)", 2587 /*IncludeVirtualBases=*/false); 2588 } 2589 2590 // vfptr and vbptr (for Microsoft C++ ABI) 2591 if (HasVfptr) { 2592 PrintOffset(OS, Offset, IndentLevel); 2593 OS << '(' << *RD << " vftable pointer)\n"; 2594 } 2595 if (HasVbptr) { 2596 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel); 2597 OS << '(' << *RD << " vbtable pointer)\n"; 2598 } 2599 2600 // Dump fields. 2601 uint64_t FieldNo = 0; 2602 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2603 E = RD->field_end(); I != E; ++I, ++FieldNo) { 2604 const FieldDecl &Field = **I; 2605 CharUnits FieldOffset = Offset + 2606 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo)); 2607 2608 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) { 2609 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2610 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel, 2611 Field.getName().data(), 2612 /*IncludeVirtualBases=*/true); 2613 continue; 2614 } 2615 } 2616 2617 PrintOffset(OS, FieldOffset, IndentLevel); 2618 OS << Field.getType().getAsString() << ' ' << Field << '\n'; 2619 } 2620 2621 if (!IncludeVirtualBases) 2622 return; 2623 2624 // Dump virtual bases. 2625 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps = 2626 Layout.getVBaseOffsetsMap(); 2627 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 2628 E = RD->vbases_end(); I != E; ++I) { 2629 assert(I->isVirtual() && "Found non-virtual class!"); 2630 const CXXRecordDecl *VBase = 2631 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 2632 2633 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase); 2634 2635 if (vtordisps.find(VBase)->second.hasVtorDisp()) { 2636 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel); 2637 OS << "(vtordisp for vbase " << *VBase << ")\n"; 2638 } 2639 2640 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel, 2641 VBase == PrimaryBase ? 2642 "(primary virtual base)" : "(virtual base)", 2643 /*IncludeVirtualBases=*/false); 2644 } 2645 2646 OS << " sizeof=" << Layout.getSize().getQuantity(); 2647 OS << ", dsize=" << Layout.getDataSize().getQuantity(); 2648 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n'; 2649 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity(); 2650 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n'; 2651 OS << '\n'; 2652 } 2653 2654 void ASTContext::DumpRecordLayout(const RecordDecl *RD, 2655 raw_ostream &OS, 2656 bool Simple) const { 2657 const ASTRecordLayout &Info = getASTRecordLayout(RD); 2658 2659 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 2660 if (!Simple) 2661 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0, 2662 /*IncludeVirtualBases=*/true); 2663 2664 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n"; 2665 if (!Simple) { 2666 OS << "Record: "; 2667 RD->dump(); 2668 } 2669 OS << "\nLayout: "; 2670 OS << "<ASTRecordLayout\n"; 2671 OS << " Size:" << toBits(Info.getSize()) << "\n"; 2672 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n"; 2673 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n"; 2674 OS << " FieldOffsets: ["; 2675 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) { 2676 if (i) OS << ", "; 2677 OS << Info.getFieldOffset(i); 2678 } 2679 OS << "]>\n"; 2680 } 2681