RecordLayoutBuilder.cpp revision d6007f9acc37ac27bb889ee26161ef213ca808b0
1//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10#include "clang/AST/Attr.h" 11#include "clang/AST/Decl.h" 12#include "clang/AST/DeclCXX.h" 13#include "clang/AST/DeclObjC.h" 14#include "clang/AST/Expr.h" 15#include "clang/AST/RecordLayout.h" 16#include "clang/Basic/TargetInfo.h" 17#include "llvm/Support/Format.h" 18#include "llvm/ADT/SmallSet.h" 19#include "llvm/Support/MathExtras.h" 20#include <map> 21 22using namespace clang; 23 24namespace { 25 26/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different 27/// offsets while laying out a C++ class. 28class EmptySubobjectMap { 29 ASTContext &Context; 30 31 /// Class - The class whose empty entries we're keeping track of. 32 const CXXRecordDecl *Class; 33 34 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or 35 /// member subobject that is empty. 36 void ComputeEmptySubobjectSizes(); 37 38public: 39 /// This holds the size of the largest empty subobject (either a base 40 /// or a member). Will be zero if the record being built doesn't contain 41 /// any empty classes. 42 uint64_t SizeOfLargestEmptySubobject; 43 44 EmptySubobjectMap(ASTContext &Context, const CXXRecordDecl *Class) 45 : Context(Context), Class(Class), SizeOfLargestEmptySubobject(0) { 46 ComputeEmptySubobjectSizes(); 47 } 48 49 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed 50 /// at the given offset. 51 /// Returns false if placing the record will result in two components 52 /// (direct or indirect) of the same type having the same offset. 53 bool CanPlaceBaseAtOffset(const CXXRecordDecl *RD, bool BaseIsVirtual, 54 uint64_t Offset); 55}; 56 57void EmptySubobjectMap::ComputeEmptySubobjectSizes() { 58 // Check the bases. 59 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(), 60 E = Class->bases_end(); I != E; ++I) { 61 const CXXRecordDecl *BaseDecl = 62 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 63 64 uint64_t EmptySize = 0; 65 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl); 66 if (BaseDecl->isEmpty()) { 67 // If the class decl is empty, get its size. 68 EmptySize = Layout.getSize(); 69 } else { 70 // Otherwise, we get the largest empty subobject for the decl. 71 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 72 } 73 74 SizeOfLargestEmptySubobject = std::max(SizeOfLargestEmptySubobject, 75 EmptySize); 76 } 77 78 // Check the fields. 79 for (CXXRecordDecl::field_iterator I = Class->field_begin(), 80 E = Class->field_end(); I != E; ++I) { 81 const FieldDecl *FD = *I; 82 83 const RecordType *RT = 84 Context.getBaseElementType(FD->getType())->getAs<RecordType>(); 85 86 // We only care about record types. 87 if (!RT) 88 continue; 89 90 uint64_t EmptySize = 0; 91 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl()); 92 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl); 93 if (MemberDecl->isEmpty()) { 94 // If the class decl is empty, get its size. 95 EmptySize = Layout.getSize(); 96 } else { 97 // Otherwise, we get the largest empty subobject for the decl. 98 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 99 } 100 101 SizeOfLargestEmptySubobject = std::max(SizeOfLargestEmptySubobject, 102 EmptySize); 103 } 104} 105 106bool 107EmptySubobjectMap::CanPlaceBaseAtOffset(const CXXRecordDecl *RD, 108 bool BaseIsVirtual, 109 uint64_t Offset) { 110 // If we know this class doesn't have any empty subobjects we don't need to 111 // bother checking. 112 if (!SizeOfLargestEmptySubobject) 113 return true; 114 115 return true; 116} 117 118class RecordLayoutBuilder { 119 // FIXME: Remove this and make the appropriate fields public. 120 friend class clang::ASTContext; 121 122 ASTContext &Context; 123 124 EmptySubobjectMap *EmptySubobjects; 125 126 /// Size - The current size of the record layout. 127 uint64_t Size; 128 129 /// Alignment - The current alignment of the record layout. 130 unsigned Alignment; 131 132 llvm::SmallVector<uint64_t, 16> FieldOffsets; 133 134 /// Packed - Whether the record is packed or not. 135 bool Packed; 136 137 /// UnfilledBitsInLastByte - If the last field laid out was a bitfield, 138 /// this contains the number of bits in the last byte that can be used for 139 /// an adjacent bitfield if necessary. 140 unsigned char UnfilledBitsInLastByte; 141 142 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by 143 /// #pragma pack. 144 unsigned MaxFieldAlignment; 145 146 /// DataSize - The data size of the record being laid out. 147 uint64_t DataSize; 148 149 bool IsUnion; 150 151 uint64_t NonVirtualSize; 152 unsigned NonVirtualAlignment; 153 154 /// PrimaryBase - the primary base class (if one exists) of the class 155 /// we're laying out. 156 const CXXRecordDecl *PrimaryBase; 157 158 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying 159 /// out is virtual. 160 bool PrimaryBaseIsVirtual; 161 162 typedef llvm::DenseMap<const CXXRecordDecl *, uint64_t> BaseOffsetsMapTy; 163 164 /// Bases - base classes and their offsets in the record. 165 BaseOffsetsMapTy Bases; 166 167 // VBases - virtual base classes and their offsets in the record. 168 BaseOffsetsMapTy VBases; 169 170 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are 171 /// primary base classes for some other direct or indirect base class. 172 llvm::SmallSet<const CXXRecordDecl*, 32> IndirectPrimaryBases; 173 174 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in 175 /// inheritance graph order. Used for determining the primary base class. 176 const CXXRecordDecl *FirstNearlyEmptyVBase; 177 178 /// VisitedVirtualBases - A set of all the visited virtual bases, used to 179 /// avoid visiting virtual bases more than once. 180 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; 181 182 /// EmptyClassOffsets - A map from offsets to empty record decls. 183 typedef std::multimap<uint64_t, const CXXRecordDecl *> EmptyClassOffsetsTy; 184 EmptyClassOffsetsTy EmptyClassOffsets; 185 186 RecordLayoutBuilder(ASTContext &Context, EmptySubobjectMap *EmptySubobjects) 187 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), Alignment(8), 188 Packed(false), UnfilledBitsInLastByte(0), MaxFieldAlignment(0), DataSize(0), 189 IsUnion(false), NonVirtualSize(0), NonVirtualAlignment(8), PrimaryBase(0), 190 PrimaryBaseIsVirtual(false), FirstNearlyEmptyVBase(0) { } 191 192 void Layout(const RecordDecl *D); 193 void Layout(const CXXRecordDecl *D); 194 void Layout(const ObjCInterfaceDecl *D); 195 196 void LayoutFields(const RecordDecl *D); 197 void LayoutField(const FieldDecl *D); 198 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize); 199 void LayoutBitField(const FieldDecl *D); 200 201 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or 202 /// member subobject that is empty. 203 void ComputeEmptySubobjectSizes(const CXXRecordDecl *RD); 204 205 /// DeterminePrimaryBase - Determine the primary base of the given class. 206 void DeterminePrimaryBase(const CXXRecordDecl *RD); 207 208 void SelectPrimaryVBase(const CXXRecordDecl *RD); 209 210 /// IdentifyPrimaryBases - Identify all virtual base classes, direct or 211 /// indirect, that are primary base classes for some other direct or indirect 212 /// base class. 213 void IdentifyPrimaryBases(const CXXRecordDecl *RD); 214 215 bool IsNearlyEmpty(const CXXRecordDecl *RD) const; 216 217 /// LayoutNonVirtualBases - Determines the primary base class (if any) and 218 /// lays it out. Will then proceed to lay out all non-virtual base clasess. 219 void LayoutNonVirtualBases(const CXXRecordDecl *RD); 220 221 /// LayoutNonVirtualBase - Lays out a single non-virtual base. 222 void LayoutNonVirtualBase(const CXXRecordDecl *Base); 223 224 void AddPrimaryVirtualBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset, 225 const CXXRecordDecl *MostDerivedClass); 226 227 /// LayoutVirtualBases - Lays out all the virtual bases. 228 void LayoutVirtualBases(const CXXRecordDecl *RD, 229 const CXXRecordDecl *MostDerivedClass); 230 231 /// LayoutVirtualBase - Lays out a single virtual base. 232 void LayoutVirtualBase(const CXXRecordDecl *Base); 233 234 /// LayoutBase - Will lay out a base and return the offset where it was 235 /// placed, in bits. 236 uint64_t LayoutBase(const CXXRecordDecl *Base, bool BaseIsVirtual); 237 238 /// canPlaceRecordAtOffset - Return whether a record (either a base class 239 /// or a field) can be placed at the given offset. 240 /// Returns false if placing the record will result in two components 241 /// (direct or indirect) of the same type having the same offset. 242 bool canPlaceRecordAtOffset(const CXXRecordDecl *RD, uint64_t Offset, 243 bool CheckVBases) const; 244 245 /// canPlaceFieldAtOffset - Return whether a field can be placed at the given 246 /// offset. 247 bool canPlaceFieldAtOffset(const FieldDecl *FD, uint64_t Offset) const; 248 249 /// UpdateEmptyClassOffsets - Called after a record (either a base class 250 /// or a field) has been placed at the given offset. Will update the 251 /// EmptyClassOffsets map if the class is empty or has any empty bases or 252 /// fields. 253 void UpdateEmptyClassOffsets(const CXXRecordDecl *RD, uint64_t Offset, 254 bool UpdateVBases); 255 256 /// UpdateEmptyClassOffsets - Called after a field has been placed at the 257 /// given offset. 258 void UpdateEmptyClassOffsets(const FieldDecl *FD, uint64_t Offset); 259 260 /// InitializeLayout - Initialize record layout for the given record decl. 261 void InitializeLayout(const RecordDecl *D); 262 263 /// FinishLayout - Finalize record layout. Adjust record size based on the 264 /// alignment. 265 void FinishLayout(); 266 267 void UpdateAlignment(unsigned NewAlignment); 268 269 RecordLayoutBuilder(const RecordLayoutBuilder&); // DO NOT IMPLEMENT 270 void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT 271public: 272 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD); 273}; 274} // end anonymous namespace 275 276/// IsNearlyEmpty - Indicates when a class has a vtable pointer, but 277/// no other data. 278bool RecordLayoutBuilder::IsNearlyEmpty(const CXXRecordDecl *RD) const { 279 // FIXME: Audit the corners 280 if (!RD->isDynamicClass()) 281 return false; 282 const ASTRecordLayout &BaseInfo = Context.getASTRecordLayout(RD); 283 if (BaseInfo.getNonVirtualSize() == Context.Target.getPointerWidth(0)) 284 return true; 285 return false; 286} 287 288void RecordLayoutBuilder::IdentifyPrimaryBases(const CXXRecordDecl *RD) { 289 const ASTRecordLayout::PrimaryBaseInfo &BaseInfo = 290 Context.getASTRecordLayout(RD).getPrimaryBaseInfo(); 291 292 // If the record has a primary base class that is virtual, add it to the set 293 // of primary bases. 294 if (BaseInfo.isVirtual()) 295 IndirectPrimaryBases.insert(BaseInfo.getBase()); 296 297 // Now traverse all bases and find primary bases for them. 298 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 299 e = RD->bases_end(); i != e; ++i) { 300 assert(!i->getType()->isDependentType() && 301 "Cannot layout class with dependent bases."); 302 const CXXRecordDecl *Base = 303 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 304 305 // Only bases with virtual bases participate in computing the 306 // indirect primary virtual base classes. 307 if (Base->getNumVBases()) 308 IdentifyPrimaryBases(Base); 309 } 310} 311 312void 313RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) { 314 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 315 E = RD->bases_end(); I != E; ++I) { 316 assert(!I->getType()->isDependentType() && 317 "Cannot layout class with dependent bases."); 318 319 const CXXRecordDecl *Base = 320 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 321 322 // Check if this is a nearly empty virtual base. 323 if (I->isVirtual() && IsNearlyEmpty(Base)) { 324 // If it's not an indirect primary base, then we've found our primary 325 // base. 326 if (!IndirectPrimaryBases.count(Base)) { 327 PrimaryBase = Base; 328 PrimaryBaseIsVirtual = true; 329 return; 330 } 331 332 // Is this the first nearly empty virtual base? 333 if (!FirstNearlyEmptyVBase) 334 FirstNearlyEmptyVBase = Base; 335 } 336 337 SelectPrimaryVBase(Base); 338 if (PrimaryBase) 339 return; 340 } 341} 342 343/// DeterminePrimaryBase - Determine the primary base of the given class. 344void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) { 345 // If the class isn't dynamic, it won't have a primary base. 346 if (!RD->isDynamicClass()) 347 return; 348 349 // Compute all the primary virtual bases for all of our direct and 350 // indirect bases, and record all their primary virtual base classes. 351 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 352 e = RD->bases_end(); i != e; ++i) { 353 assert(!i->getType()->isDependentType() && 354 "Cannot lay out class with dependent bases."); 355 const CXXRecordDecl *Base = 356 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 357 IdentifyPrimaryBases(Base); 358 } 359 360 // If the record has a dynamic base class, attempt to choose a primary base 361 // class. It is the first (in direct base class order) non-virtual dynamic 362 // base class, if one exists. 363 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 364 e = RD->bases_end(); i != e; ++i) { 365 // Ignore virtual bases. 366 if (i->isVirtual()) 367 continue; 368 369 const CXXRecordDecl *Base = 370 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 371 372 if (Base->isDynamicClass()) { 373 // We found it. 374 PrimaryBase = Base; 375 PrimaryBaseIsVirtual = false; 376 return; 377 } 378 } 379 380 // Otherwise, it is the first nearly empty virtual base that is not an 381 // indirect primary virtual base class, if one exists. 382 if (RD->getNumVBases() != 0) { 383 SelectPrimaryVBase(RD); 384 if (PrimaryBase) 385 return; 386 } 387 388 // Otherwise, it is the first nearly empty virtual base that is not an 389 // indirect primary virtual base class, if one exists. 390 if (FirstNearlyEmptyVBase) { 391 PrimaryBase = FirstNearlyEmptyVBase; 392 PrimaryBaseIsVirtual = true; 393 return; 394 } 395 396 // Otherwise there is no primary base class. 397 assert(!PrimaryBase && "Should not get here with a primary base!"); 398 399 // Allocate the virtual table pointer at offset zero. 400 assert(DataSize == 0 && "Vtable pointer must be at offset zero!"); 401 402 // Update the size. 403 Size += Context.Target.getPointerWidth(0); 404 DataSize = Size; 405 406 // Update the alignment. 407 UpdateAlignment(Context.Target.getPointerAlign(0)); 408} 409 410void 411RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) { 412 // First, determine the primary base class. 413 DeterminePrimaryBase(RD); 414 415 // If we have a primary base class, lay it out. 416 if (PrimaryBase) { 417 if (PrimaryBaseIsVirtual) { 418 // We have a virtual primary base, insert it as an indirect primary base. 419 IndirectPrimaryBases.insert(PrimaryBase); 420 421 assert(!VisitedVirtualBases.count(PrimaryBase) && 422 "vbase already visited!"); 423 VisitedVirtualBases.insert(PrimaryBase); 424 425 LayoutVirtualBase(PrimaryBase); 426 } else 427 LayoutNonVirtualBase(PrimaryBase); 428 } 429 430 // Now lay out the non-virtual bases. 431 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 432 E = RD->bases_end(); I != E; ++I) { 433 434 // Ignore virtual bases. 435 if (I->isVirtual()) 436 continue; 437 438 const CXXRecordDecl *Base = 439 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 440 441 // Skip the primary base. 442 if (Base == PrimaryBase && !PrimaryBaseIsVirtual) 443 continue; 444 445 // Lay out the base. 446 LayoutNonVirtualBase(Base); 447 } 448} 449 450void RecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *Base) { 451 // Layout the base. 452 uint64_t Offset = LayoutBase(Base, /*BaseIsVirtual=*/false); 453 454 // Add its base class offset. 455 if (!Bases.insert(std::make_pair(Base, Offset)).second) 456 assert(false && "Added same base offset more than once!"); 457} 458 459void 460RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const CXXRecordDecl *RD, 461 uint64_t Offset, 462 const CXXRecordDecl *MostDerivedClass) { 463 // We already have the offset for the primary base of the most derived class. 464 if (RD != MostDerivedClass) { 465 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 466 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 467 468 // If this is a primary virtual base and we haven't seen it before, add it. 469 if (PrimaryBase && Layout.getPrimaryBaseWasVirtual() && 470 !VBases.count(PrimaryBase)) 471 VBases.insert(std::make_pair(PrimaryBase, Offset)); 472 } 473 474 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 475 E = RD->bases_end(); I != E; ++I) { 476 assert(!I->getType()->isDependentType() && 477 "Cannot layout class with dependent bases."); 478 479 const CXXRecordDecl *BaseDecl = 480 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 481 482 if (!BaseDecl->getNumVBases()) { 483 // This base isn't interesting since it doesn't have any virtual bases. 484 continue; 485 } 486 487 // Compute the offset of this base. 488 uint64_t BaseOffset; 489 490 if (I->isVirtual()) { 491 // If we don't know this vbase yet, don't visit it. It will be visited 492 // later. 493 if (!VBases.count(BaseDecl)) { 494 continue; 495 } 496 497 // Check if we've already visited this base. 498 if (!VisitedVirtualBases.insert(BaseDecl)) 499 continue; 500 501 // We want the vbase offset from the class we're currently laying out. 502 BaseOffset = VBases[BaseDecl]; 503 } else if (RD == MostDerivedClass) { 504 // We want the base offset from the class we're currently laying out. 505 assert(Bases.count(BaseDecl) && "Did not find base!"); 506 BaseOffset = Bases[BaseDecl]; 507 } else { 508 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 509 BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 510 } 511 512 AddPrimaryVirtualBaseOffsets(BaseDecl, BaseOffset, MostDerivedClass); 513 } 514} 515 516void 517RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD, 518 const CXXRecordDecl *MostDerivedClass) { 519 const CXXRecordDecl *PrimaryBase; 520 bool PrimaryBaseIsVirtual; 521 522 if (MostDerivedClass == RD) { 523 PrimaryBase = this->PrimaryBase; 524 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual; 525 } else { 526 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 527 PrimaryBase = Layout.getPrimaryBase(); 528 PrimaryBaseIsVirtual = Layout.getPrimaryBaseWasVirtual(); 529 } 530 531 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 532 E = RD->bases_end(); I != E; ++I) { 533 assert(!I->getType()->isDependentType() && 534 "Cannot layout class with dependent bases."); 535 536 const CXXRecordDecl *Base = 537 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 538 539 if (I->isVirtual()) { 540 if (PrimaryBase != Base || !PrimaryBaseIsVirtual) { 541 bool IndirectPrimaryBase = IndirectPrimaryBases.count(Base); 542 543 // Only lay out the virtual base if it's not an indirect primary base. 544 if (!IndirectPrimaryBase) { 545 // Only visit virtual bases once. 546 if (!VisitedVirtualBases.insert(Base)) 547 continue; 548 549 LayoutVirtualBase(Base); 550 } 551 } 552 } 553 554 if (!Base->getNumVBases()) { 555 // This base isn't interesting since it doesn't have any virtual bases. 556 continue; 557 } 558 559 LayoutVirtualBases(Base, MostDerivedClass); 560 } 561} 562 563void RecordLayoutBuilder::LayoutVirtualBase(const CXXRecordDecl *Base) { 564 // Layout the base. 565 uint64_t Offset = LayoutBase(Base, /*BaseIsVirtual=*/true); 566 567 // Add its base class offset. 568 if (!VBases.insert(std::make_pair(Base, Offset)).second) 569 assert(false && "Added same vbase offset more than once!"); 570} 571 572uint64_t RecordLayoutBuilder::LayoutBase(const CXXRecordDecl *Base, 573 bool BaseIsVirtual) { 574 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base); 575 576 // If we have an empty base class, try to place it at offset 0. 577 if (Base->isEmpty() && 578 EmptySubobjects->CanPlaceBaseAtOffset(Base, BaseIsVirtual, 0) && 579 canPlaceRecordAtOffset(Base, 0, /*CheckVBases=*/false)) { 580 // We were able to place the class at offset 0. 581 UpdateEmptyClassOffsets(Base, 0, /*UpdateVBases=*/false); 582 583 Size = std::max(Size, Layout.getSize()); 584 585 return 0; 586 } 587 588 unsigned BaseAlign = Layout.getNonVirtualAlign(); 589 590 // Round up the current record size to the base's alignment boundary. 591 uint64_t Offset = llvm::RoundUpToAlignment(DataSize, BaseAlign); 592 593 // Try to place the base. 594 while (true) { 595 if (EmptySubobjects->CanPlaceBaseAtOffset(Base, BaseIsVirtual, Offset) && 596 canPlaceRecordAtOffset(Base, Offset, /*CheckVBases=*/false)) 597 break; 598 599 Offset += BaseAlign; 600 } 601 602 if (!Base->isEmpty()) { 603 // Update the data size. 604 DataSize = Offset + Layout.getNonVirtualSize(); 605 606 Size = std::max(Size, DataSize); 607 } else 608 Size = std::max(Size, Offset + Layout.getSize()); 609 610 // Remember max struct/class alignment. 611 UpdateAlignment(BaseAlign); 612 613 UpdateEmptyClassOffsets(Base, Offset, /*UpdateVBases=*/false); 614 return Offset; 615} 616 617bool 618RecordLayoutBuilder::canPlaceRecordAtOffset(const CXXRecordDecl *RD, 619 uint64_t Offset, 620 bool CheckVBases) const { 621 // Look for an empty class with the same type at the same offset. 622 for (EmptyClassOffsetsTy::const_iterator I = 623 EmptyClassOffsets.lower_bound(Offset), 624 E = EmptyClassOffsets.upper_bound(Offset); I != E; ++I) { 625 626 if (I->second == RD) 627 return false; 628 } 629 630 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 631 632 // Check bases. 633 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 634 E = RD->bases_end(); I != E; ++I) { 635 assert(!I->getType()->isDependentType() && 636 "Cannot layout class with dependent bases."); 637 if (I->isVirtual()) 638 continue; 639 640 const CXXRecordDecl *BaseDecl = 641 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 642 643 uint64_t BaseOffset = Layout.getBaseClassOffset(BaseDecl); 644 645 if (!canPlaceRecordAtOffset(BaseDecl, Offset + BaseOffset, 646 /*CheckVBases=*/false)) 647 return false; 648 } 649 650 // Check fields. 651 unsigned FieldNo = 0; 652 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 653 I != E; ++I, ++FieldNo) { 654 const FieldDecl *FD = *I; 655 656 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); 657 658 if (!canPlaceFieldAtOffset(FD, Offset + FieldOffset)) 659 return false; 660 } 661 662 if (CheckVBases) { 663 // FIXME: virtual bases. 664 } 665 666 return true; 667} 668 669bool RecordLayoutBuilder::canPlaceFieldAtOffset(const FieldDecl *FD, 670 uint64_t Offset) const { 671 QualType T = FD->getType(); 672 if (const RecordType *RT = T->getAs<RecordType>()) { 673 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 674 return canPlaceRecordAtOffset(RD, Offset, /*CheckVBases=*/true); 675 } 676 677 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 678 QualType ElemTy = Context.getBaseElementType(AT); 679 const RecordType *RT = ElemTy->getAs<RecordType>(); 680 if (!RT) 681 return true; 682 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 683 if (!RD) 684 return true; 685 686 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 687 688 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 689 uint64_t ElementOffset = Offset; 690 for (uint64_t I = 0; I != NumElements; ++I) { 691 if (!canPlaceRecordAtOffset(RD, ElementOffset, /*CheckVBases=*/true)) 692 return false; 693 694 ElementOffset += Layout.getSize(); 695 } 696 } 697 698 return true; 699} 700 701void RecordLayoutBuilder::UpdateEmptyClassOffsets(const CXXRecordDecl *RD, 702 uint64_t Offset, 703 bool UpdateVBases) { 704 if (RD->isEmpty()) 705 EmptyClassOffsets.insert(std::make_pair(Offset, RD)); 706 707 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 708 709 // Update bases. 710 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 711 E = RD->bases_end(); I != E; ++I) { 712 assert(!I->getType()->isDependentType() && 713 "Cannot layout class with dependent bases."); 714 if (I->isVirtual()) 715 continue; 716 717 const CXXRecordDecl *Base = 718 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 719 720 uint64_t BaseClassOffset = Layout.getBaseClassOffset(Base); 721 UpdateEmptyClassOffsets(Base, Offset + BaseClassOffset, 722 /*UpdateVBases=*/false); 723 } 724 725 // Update fields. 726 unsigned FieldNo = 0; 727 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 728 I != E; ++I, ++FieldNo) { 729 const FieldDecl *FD = *I; 730 731 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); 732 UpdateEmptyClassOffsets(FD, Offset + FieldOffset); 733 } 734 735 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 736 737 if (UpdateVBases) { 738 // FIXME: Update virtual bases. 739 } else if (PrimaryBase && Layout.getPrimaryBaseWasVirtual()) { 740 // We always want to update the offsets of a primary virtual base. 741 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 && 742 "primary base class offset must always be 0!"); 743 UpdateEmptyClassOffsets(PrimaryBase, Offset, /*UpdateVBases=*/false); 744 } 745} 746 747void 748RecordLayoutBuilder::UpdateEmptyClassOffsets(const FieldDecl *FD, 749 uint64_t Offset) { 750 QualType T = FD->getType(); 751 752 if (const RecordType *RT = T->getAs<RecordType>()) { 753 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 754 UpdateEmptyClassOffsets(RD, Offset, /*UpdateVBases=*/true); 755 return; 756 } 757 } 758 759 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 760 QualType ElemTy = Context.getBaseElementType(AT); 761 const RecordType *RT = ElemTy->getAs<RecordType>(); 762 if (!RT) 763 return; 764 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 765 if (!RD) 766 return; 767 768 const ASTRecordLayout &Info = Context.getASTRecordLayout(RD); 769 770 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 771 uint64_t ElementOffset = Offset; 772 773 for (uint64_t I = 0; I != NumElements; ++I) { 774 UpdateEmptyClassOffsets(RD, ElementOffset, /*UpdateVBases=*/true); 775 ElementOffset += Info.getSize(); 776 } 777 } 778} 779 780void RecordLayoutBuilder::InitializeLayout(const RecordDecl *D) { 781 IsUnion = D->isUnion(); 782 783 Packed = D->hasAttr<PackedAttr>(); 784 785 // The #pragma pack attribute specifies the maximum field alignment. 786 if (const PragmaPackAttr *PPA = D->getAttr<PragmaPackAttr>()) 787 MaxFieldAlignment = PPA->getAlignment(); 788 789 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 790 UpdateAlignment(AA->getMaxAlignment()); 791} 792 793void RecordLayoutBuilder::Layout(const RecordDecl *D) { 794 InitializeLayout(D); 795 LayoutFields(D); 796 797 // Finally, round the size of the total struct up to the alignment of the 798 // struct itself. 799 FinishLayout(); 800} 801 802void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) { 803 // Create our empty subobject offset map. 804 EmptySubobjectMap EmptySubobjectMap(Context, RD); 805 EmptySubobjects = &EmptySubobjectMap; 806 807 InitializeLayout(RD); 808 809 // Lay out the vtable and the non-virtual bases. 810 LayoutNonVirtualBases(RD); 811 812 LayoutFields(RD); 813 814 NonVirtualSize = Size; 815 NonVirtualAlignment = Alignment; 816 817 // Lay out the virtual bases and add the primary virtual base offsets. 818 LayoutVirtualBases(RD, RD); 819 820 VisitedVirtualBases.clear(); 821 AddPrimaryVirtualBaseOffsets(RD, 0, RD); 822 823 // Finally, round the size of the total struct up to the alignment of the 824 // struct itself. 825 FinishLayout(); 826 827#ifndef NDEBUG 828 // Check that we have base offsets for all bases. 829 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 830 E = RD->bases_end(); I != E; ++I) { 831 if (I->isVirtual()) 832 continue; 833 834 const CXXRecordDecl *BaseDecl = 835 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 836 837 assert(Bases.count(BaseDecl) && "Did not find base offset!"); 838 } 839 840 // And all virtual bases. 841 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 842 E = RD->vbases_end(); I != E; ++I) { 843 const CXXRecordDecl *BaseDecl = 844 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 845 846 assert(VBases.count(BaseDecl) && "Did not find base offset!"); 847 } 848#endif 849} 850 851void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) { 852 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 853 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD); 854 855 UpdateAlignment(SL.getAlignment()); 856 857 // We start laying out ivars not at the end of the superclass 858 // structure, but at the next byte following the last field. 859 Size = llvm::RoundUpToAlignment(SL.getDataSize(), 8); 860 DataSize = Size; 861 } 862 863 Packed = D->hasAttr<PackedAttr>(); 864 865 // The #pragma pack attribute specifies the maximum field alignment. 866 if (const PragmaPackAttr *PPA = D->getAttr<PragmaPackAttr>()) 867 MaxFieldAlignment = PPA->getAlignment(); 868 869 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 870 UpdateAlignment(AA->getMaxAlignment()); 871 // Layout each ivar sequentially. 872 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 873 Context.ShallowCollectObjCIvars(D, Ivars); 874 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) 875 LayoutField(Ivars[i]); 876 877 // Finally, round the size of the total struct up to the alignment of the 878 // struct itself. 879 FinishLayout(); 880} 881 882void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) { 883 // Layout each field, for now, just sequentially, respecting alignment. In 884 // the future, this will need to be tweakable by targets. 885 for (RecordDecl::field_iterator Field = D->field_begin(), 886 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) 887 LayoutField(*Field); 888} 889 890void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize, 891 uint64_t TypeSize) { 892 assert(Context.getLangOptions().CPlusPlus && 893 "Can only have wide bit-fields in C++!"); 894 895 // Itanium C++ ABI 2.4: 896 // If sizeof(T)*8 < n, let T' be the largest integral POD type with 897 // sizeof(T')*8 <= n. 898 899 QualType IntegralPODTypes[] = { 900 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy, 901 Context.UnsignedLongTy, Context.UnsignedLongLongTy 902 }; 903 904 QualType Type; 905 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes); 906 I != E; ++I) { 907 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]); 908 909 if (Size > FieldSize) 910 break; 911 912 Type = IntegralPODTypes[I]; 913 } 914 assert(!Type.isNull() && "Did not find a type!"); 915 916 unsigned TypeAlign = Context.getTypeAlign(Type); 917 918 // We're not going to use any of the unfilled bits in the last byte. 919 UnfilledBitsInLastByte = 0; 920 921 uint64_t FieldOffset; 922 923 if (IsUnion) { 924 DataSize = std::max(DataSize, FieldSize); 925 FieldOffset = 0; 926 } else { 927 // The bitfield is allocated starting at the next offset aligned appropriately 928 // for T', with length n bits. 929 FieldOffset = llvm::RoundUpToAlignment(DataSize, TypeAlign); 930 931 uint64_t NewSizeInBits = FieldOffset + FieldSize; 932 933 DataSize = llvm::RoundUpToAlignment(NewSizeInBits, 8); 934 UnfilledBitsInLastByte = DataSize - NewSizeInBits; 935 } 936 937 // Place this field at the current location. 938 FieldOffsets.push_back(FieldOffset); 939 940 // Update the size. 941 Size = std::max(Size, DataSize); 942 943 // Remember max struct/class alignment. 944 UpdateAlignment(TypeAlign); 945} 946 947void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { 948 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 949 uint64_t FieldOffset = IsUnion ? 0 : (DataSize - UnfilledBitsInLastByte); 950 uint64_t FieldSize = D->getBitWidth()->EvaluateAsInt(Context).getZExtValue(); 951 952 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType()); 953 uint64_t TypeSize = FieldInfo.first; 954 unsigned FieldAlign = FieldInfo.second; 955 956 if (FieldSize > TypeSize) { 957 LayoutWideBitField(FieldSize, TypeSize); 958 return; 959 } 960 961 if (FieldPacked || !Context.Target.useBitFieldTypeAlignment()) 962 FieldAlign = 1; 963 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 964 FieldAlign = std::max(FieldAlign, AA->getMaxAlignment()); 965 966 // The maximum field alignment overrides the aligned attribute. 967 if (MaxFieldAlignment) 968 FieldAlign = std::min(FieldAlign, MaxFieldAlignment); 969 970 // Check if we need to add padding to give the field the correct alignment. 971 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) 972 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 973 974 // Padding members don't affect overall alignment. 975 if (!D->getIdentifier()) 976 FieldAlign = 1; 977 978 // Place this field at the current location. 979 FieldOffsets.push_back(FieldOffset); 980 981 // Update DataSize to include the last byte containing (part of) the bitfield. 982 if (IsUnion) { 983 // FIXME: I think FieldSize should be TypeSize here. 984 DataSize = std::max(DataSize, FieldSize); 985 } else { 986 uint64_t NewSizeInBits = FieldOffset + FieldSize; 987 988 DataSize = llvm::RoundUpToAlignment(NewSizeInBits, 8); 989 UnfilledBitsInLastByte = DataSize - NewSizeInBits; 990 } 991 992 // Update the size. 993 Size = std::max(Size, DataSize); 994 995 // Remember max struct/class alignment. 996 UpdateAlignment(FieldAlign); 997} 998 999void RecordLayoutBuilder::LayoutField(const FieldDecl *D) { 1000 if (D->isBitField()) { 1001 LayoutBitField(D); 1002 return; 1003 } 1004 1005 // Reset the unfilled bits. 1006 UnfilledBitsInLastByte = 0; 1007 1008 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 1009 uint64_t FieldOffset = IsUnion ? 0 : DataSize; 1010 uint64_t FieldSize; 1011 unsigned FieldAlign; 1012 1013 if (D->getType()->isIncompleteArrayType()) { 1014 // This is a flexible array member; we can't directly 1015 // query getTypeInfo about these, so we figure it out here. 1016 // Flexible array members don't have any size, but they 1017 // have to be aligned appropriately for their element type. 1018 FieldSize = 0; 1019 const ArrayType* ATy = Context.getAsArrayType(D->getType()); 1020 FieldAlign = Context.getTypeAlign(ATy->getElementType()); 1021 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) { 1022 unsigned AS = RT->getPointeeType().getAddressSpace(); 1023 FieldSize = Context.Target.getPointerWidth(AS); 1024 FieldAlign = Context.Target.getPointerAlign(AS); 1025 } else { 1026 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType()); 1027 FieldSize = FieldInfo.first; 1028 FieldAlign = FieldInfo.second; 1029 } 1030 1031 if (FieldPacked) 1032 FieldAlign = 8; 1033 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 1034 FieldAlign = std::max(FieldAlign, AA->getMaxAlignment()); 1035 1036 // The maximum field alignment overrides the aligned attribute. 1037 if (MaxFieldAlignment) 1038 FieldAlign = std::min(FieldAlign, MaxFieldAlignment); 1039 1040 // Round up the current record size to the field's alignment boundary. 1041 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign); 1042 1043 if (!IsUnion) { 1044 while (true) { 1045 // Check if we can place the field at this offset. 1046 if (canPlaceFieldAtOffset(D, FieldOffset)) 1047 break; 1048 1049 // We couldn't place the field at the offset. Try again at a new offset. 1050 FieldOffset += FieldAlign; 1051 } 1052 1053 UpdateEmptyClassOffsets(D, FieldOffset); 1054 } 1055 1056 // Place this field at the current location. 1057 FieldOffsets.push_back(FieldOffset); 1058 1059 // Reserve space for this field. 1060 if (IsUnion) 1061 Size = std::max(Size, FieldSize); 1062 else 1063 Size = FieldOffset + FieldSize; 1064 1065 // Update the data size. 1066 DataSize = Size; 1067 1068 // Remember max struct/class alignment. 1069 UpdateAlignment(FieldAlign); 1070} 1071 1072void RecordLayoutBuilder::FinishLayout() { 1073 // In C++, records cannot be of size 0. 1074 if (Context.getLangOptions().CPlusPlus && Size == 0) 1075 Size = 8; 1076 // Finally, round the size of the record up to the alignment of the 1077 // record itself. 1078 Size = llvm::RoundUpToAlignment(Size, Alignment); 1079} 1080 1081void RecordLayoutBuilder::UpdateAlignment(unsigned NewAlignment) { 1082 if (NewAlignment <= Alignment) 1083 return; 1084 1085 assert(llvm::isPowerOf2_32(NewAlignment && "Alignment not a power of 2")); 1086 1087 Alignment = NewAlignment; 1088} 1089 1090const CXXMethodDecl * 1091RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) { 1092 assert(RD->isDynamicClass() && "Class does not have any virtual methods!"); 1093 1094 // If a class isn't polymorphic it doesn't have a key function. 1095 if (!RD->isPolymorphic()) 1096 return 0; 1097 1098 // A class inside an anonymous namespace doesn't have a key function. (Or 1099 // at least, there's no point to assigning a key function to such a class; 1100 // this doesn't affect the ABI.) 1101 if (RD->isInAnonymousNamespace()) 1102 return 0; 1103 1104 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 1105 E = RD->method_end(); I != E; ++I) { 1106 const CXXMethodDecl *MD = *I; 1107 1108 if (!MD->isVirtual()) 1109 continue; 1110 1111 if (MD->isPure()) 1112 continue; 1113 1114 // Ignore implicit member functions, they are always marked as inline, but 1115 // they don't have a body until they're defined. 1116 if (MD->isImplicit()) 1117 continue; 1118 1119 if (MD->isInlineSpecified()) 1120 continue; 1121 1122 if (MD->hasInlineBody()) 1123 continue; 1124 1125 // We found it. 1126 return MD; 1127 } 1128 1129 return 0; 1130} 1131 1132/// getASTRecordLayout - Get or compute information about the layout of the 1133/// specified record (struct/union/class), which indicates its size and field 1134/// position information. 1135const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 1136 D = D->getDefinition(); 1137 assert(D && "Cannot get layout of forward declarations!"); 1138 1139 // Look up this layout, if already laid out, return what we have. 1140 // Note that we can't save a reference to the entry because this function 1141 // is recursive. 1142 const ASTRecordLayout *Entry = ASTRecordLayouts[D]; 1143 if (Entry) return *Entry; 1144 1145 const ASTRecordLayout *NewEntry; 1146 1147 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 1148 EmptySubobjectMap EmptySubobjects(*this, RD); 1149 RecordLayoutBuilder Builder(*this, &EmptySubobjects); 1150 Builder.Layout(RD); 1151 1152 // FIXME: This is not always correct. See the part about bitfields at 1153 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info. 1154 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout. 1155 bool IsPODForThePurposeOfLayout = cast<CXXRecordDecl>(D)->isPOD(); 1156 1157 // FIXME: This should be done in FinalizeLayout. 1158 uint64_t DataSize = 1159 IsPODForThePurposeOfLayout ? Builder.Size : Builder.DataSize; 1160 uint64_t NonVirtualSize = 1161 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize; 1162 1163 NewEntry = 1164 new (*this) ASTRecordLayout(*this, Builder.Size, Builder.Alignment, 1165 DataSize, Builder.FieldOffsets.data(), 1166 Builder.FieldOffsets.size(), 1167 NonVirtualSize, 1168 Builder.NonVirtualAlignment, 1169 EmptySubobjects.SizeOfLargestEmptySubobject, 1170 Builder.PrimaryBase, 1171 Builder.PrimaryBaseIsVirtual, 1172 Builder.Bases, Builder.VBases); 1173 } else { 1174 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0); 1175 Builder.Layout(D); 1176 1177 NewEntry = 1178 new (*this) ASTRecordLayout(*this, Builder.Size, Builder.Alignment, 1179 Builder.Size, 1180 Builder.FieldOffsets.data(), 1181 Builder.FieldOffsets.size()); 1182 } 1183 1184 ASTRecordLayouts[D] = NewEntry; 1185 1186 if (getLangOptions().DumpRecordLayouts) { 1187 llvm::errs() << "\n*** Dumping AST Record Layout\n"; 1188 DumpRecordLayout(D, llvm::errs()); 1189 } 1190 1191 return *NewEntry; 1192} 1193 1194const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) { 1195 RD = cast<CXXRecordDecl>(RD->getDefinition()); 1196 assert(RD && "Cannot get key function for forward declarations!"); 1197 1198 const CXXMethodDecl *&Entry = KeyFunctions[RD]; 1199 if (!Entry) 1200 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD); 1201 else 1202 assert(Entry == RecordLayoutBuilder::ComputeKeyFunction(RD) && 1203 "Key function changed!"); 1204 1205 return Entry; 1206} 1207 1208/// getInterfaceLayoutImpl - Get or compute information about the 1209/// layout of the given interface. 1210/// 1211/// \param Impl - If given, also include the layout of the interface's 1212/// implementation. This may differ by including synthesized ivars. 1213const ASTRecordLayout & 1214ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 1215 const ObjCImplementationDecl *Impl) { 1216 assert(!D->isForwardDecl() && "Invalid interface decl!"); 1217 1218 // Look up this layout, if already laid out, return what we have. 1219 ObjCContainerDecl *Key = 1220 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 1221 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 1222 return *Entry; 1223 1224 // Add in synthesized ivar count if laying out an implementation. 1225 if (Impl) { 1226 unsigned SynthCount = CountNonClassIvars(D); 1227 // If there aren't any sythesized ivars then reuse the interface 1228 // entry. Note we can't cache this because we simply free all 1229 // entries later; however we shouldn't look up implementations 1230 // frequently. 1231 if (SynthCount == 0) 1232 return getObjCLayout(D, 0); 1233 } 1234 1235 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0); 1236 Builder.Layout(D); 1237 1238 const ASTRecordLayout *NewEntry = 1239 new (*this) ASTRecordLayout(*this, Builder.Size, Builder.Alignment, 1240 Builder.DataSize, 1241 Builder.FieldOffsets.data(), 1242 Builder.FieldOffsets.size()); 1243 1244 ObjCLayouts[Key] = NewEntry; 1245 1246 return *NewEntry; 1247} 1248 1249static void PrintOffset(llvm::raw_ostream &OS, 1250 uint64_t Offset, unsigned IndentLevel) { 1251 OS << llvm::format("%4d | ", Offset); 1252 OS.indent(IndentLevel * 2); 1253} 1254 1255static void DumpCXXRecordLayout(llvm::raw_ostream &OS, 1256 const CXXRecordDecl *RD, ASTContext &C, 1257 uint64_t Offset, 1258 unsigned IndentLevel, 1259 const char* Description, 1260 bool IncludeVirtualBases) { 1261 const ASTRecordLayout &Info = C.getASTRecordLayout(RD); 1262 1263 PrintOffset(OS, Offset, IndentLevel); 1264 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString(); 1265 if (Description) 1266 OS << ' ' << Description; 1267 if (RD->isEmpty()) 1268 OS << " (empty)"; 1269 OS << '\n'; 1270 1271 IndentLevel++; 1272 1273 const CXXRecordDecl *PrimaryBase = Info.getPrimaryBase(); 1274 1275 // Vtable pointer. 1276 if (RD->isDynamicClass() && !PrimaryBase) { 1277 PrintOffset(OS, Offset, IndentLevel); 1278 OS << '(' << RD << " vtable pointer)\n"; 1279 } 1280 // Dump (non-virtual) bases 1281 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1282 E = RD->bases_end(); I != E; ++I) { 1283 assert(!I->getType()->isDependentType() && 1284 "Cannot layout class with dependent bases."); 1285 if (I->isVirtual()) 1286 continue; 1287 1288 const CXXRecordDecl *Base = 1289 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1290 1291 uint64_t BaseOffset = Offset + Info.getBaseClassOffset(Base) / 8; 1292 1293 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel, 1294 Base == PrimaryBase ? "(primary base)" : "(base)", 1295 /*IncludeVirtualBases=*/false); 1296 } 1297 1298 // Dump fields. 1299 uint64_t FieldNo = 0; 1300 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1301 E = RD->field_end(); I != E; ++I, ++FieldNo) { 1302 const FieldDecl *Field = *I; 1303 uint64_t FieldOffset = Offset + Info.getFieldOffset(FieldNo) / 8; 1304 1305 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1306 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1307 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel, 1308 Field->getNameAsCString(), 1309 /*IncludeVirtualBases=*/true); 1310 continue; 1311 } 1312 } 1313 1314 PrintOffset(OS, FieldOffset, IndentLevel); 1315 OS << Field->getType().getAsString() << ' ' << Field << '\n'; 1316 } 1317 1318 if (!IncludeVirtualBases) 1319 return; 1320 1321 // Dump virtual bases. 1322 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 1323 E = RD->vbases_end(); I != E; ++I) { 1324 assert(I->isVirtual() && "Found non-virtual class!"); 1325 const CXXRecordDecl *VBase = 1326 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1327 1328 uint64_t VBaseOffset = Offset + Info.getVBaseClassOffset(VBase) / 8; 1329 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel, 1330 VBase == PrimaryBase ? 1331 "(primary virtual base)" : "(virtual base)", 1332 /*IncludeVirtualBases=*/false); 1333 } 1334 1335 OS << " sizeof=" << Info.getSize() / 8; 1336 OS << ", dsize=" << Info.getDataSize() / 8; 1337 OS << ", align=" << Info.getAlignment() / 8 << '\n'; 1338 OS << " nvsize=" << Info.getNonVirtualSize() / 8; 1339 OS << ", nvalign=" << Info.getNonVirtualAlign() / 8 << '\n'; 1340 OS << '\n'; 1341} 1342 1343void ASTContext::DumpRecordLayout(const RecordDecl *RD, 1344 llvm::raw_ostream &OS) { 1345 const ASTRecordLayout &Info = getASTRecordLayout(RD); 1346 1347 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1348 return DumpCXXRecordLayout(OS, CXXRD, *this, 0, 0, 0, 1349 /*IncludeVirtualBases=*/true); 1350 1351 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n"; 1352 OS << "Record: "; 1353 RD->dump(); 1354 OS << "\nLayout: "; 1355 OS << "<ASTRecordLayout\n"; 1356 OS << " Size:" << Info.getSize() << "\n"; 1357 OS << " DataSize:" << Info.getDataSize() << "\n"; 1358 OS << " Alignment:" << Info.getAlignment() << "\n"; 1359 OS << " FieldOffsets: ["; 1360 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) { 1361 if (i) OS << ", "; 1362 OS << Info.getFieldOffset(i); 1363 } 1364 OS << "]>\n"; 1365} 1366