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