CGVTables.cpp revision e6203134056fe3912f4c436099a69bc6242d770f
1//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===// 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// This contains code dealing with C++ code generation of virtual tables. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenModule.h" 15#include "CodeGenFunction.h" 16#include "CGCXXABI.h" 17#include "clang/AST/CXXInheritance.h" 18#include "clang/AST/RecordLayout.h" 19#include "clang/Frontend/CodeGenOptions.h" 20#include "llvm/ADT/DenseSet.h" 21#include "llvm/ADT/SetVector.h" 22#include "llvm/Support/Compiler.h" 23#include "llvm/Support/Format.h" 24#include <algorithm> 25#include <cstdio> 26 27using namespace clang; 28using namespace CodeGen; 29 30namespace { 31 32/// BaseOffset - Represents an offset from a derived class to a direct or 33/// indirect base class. 34struct BaseOffset { 35 /// DerivedClass - The derived class. 36 const CXXRecordDecl *DerivedClass; 37 38 /// VirtualBase - If the path from the derived class to the base class 39 /// involves a virtual base class, this holds its declaration. 40 const CXXRecordDecl *VirtualBase; 41 42 /// NonVirtualOffset - The offset from the derived class to the base class. 43 /// (Or the offset from the virtual base class to the base class, if the 44 /// path from the derived class to the base class involves a virtual base 45 /// class. 46 int64_t NonVirtualOffset; 47 48 BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { } 49 BaseOffset(const CXXRecordDecl *DerivedClass, 50 const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset) 51 : DerivedClass(DerivedClass), VirtualBase(VirtualBase), 52 NonVirtualOffset(NonVirtualOffset) { } 53 54 bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; } 55}; 56 57/// FinalOverriders - Contains the final overrider member functions for all 58/// member functions in the base subobjects of a class. 59class FinalOverriders { 60public: 61 /// OverriderInfo - Information about a final overrider. 62 struct OverriderInfo { 63 /// Method - The method decl of the overrider. 64 const CXXMethodDecl *Method; 65 66 /// Offset - the base offset of the overrider in the layout class. 67 uint64_t Offset; 68 69 OverriderInfo() : Method(0), Offset(0) { } 70 }; 71 72private: 73 /// MostDerivedClass - The most derived class for which the final overriders 74 /// are stored. 75 const CXXRecordDecl *MostDerivedClass; 76 77 /// MostDerivedClassOffset - If we're building final overriders for a 78 /// construction vtable, this holds the offset from the layout class to the 79 /// most derived class. 80 const uint64_t MostDerivedClassOffset; 81 82 /// LayoutClass - The class we're using for layout information. Will be 83 /// different than the most derived class if the final overriders are for a 84 /// construction vtable. 85 const CXXRecordDecl *LayoutClass; 86 87 ASTContext &Context; 88 89 /// MostDerivedClassLayout - the AST record layout of the most derived class. 90 const ASTRecordLayout &MostDerivedClassLayout; 91 92 /// MethodBaseOffsetPairTy - Uniquely identifies a member function 93 /// in a base subobject. 94 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy; 95 96 typedef llvm::DenseMap<MethodBaseOffsetPairTy, 97 OverriderInfo> OverridersMapTy; 98 99 /// OverridersMap - The final overriders for all virtual member functions of 100 /// all the base subobjects of the most derived class. 101 OverridersMapTy OverridersMap; 102 103 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented 104 /// as a record decl and a subobject number) and its offsets in the most 105 /// derived class as well as the layout class. 106 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>, 107 CharUnits> SubobjectOffsetMapTy; 108 109 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy; 110 111 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the 112 /// given base. 113 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, 114 uint64_t OffsetInLayoutClass, 115 SubobjectOffsetMapTy &SubobjectOffsets, 116 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets, 117 SubobjectCountMapTy &SubobjectCounts); 118 119 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 120 121 /// dump - dump the final overriders for a base subobject, and all its direct 122 /// and indirect base subobjects. 123 void dump(llvm::raw_ostream &Out, BaseSubobject Base, 124 VisitedVirtualBasesSetTy& VisitedVirtualBases); 125 126public: 127 FinalOverriders(const CXXRecordDecl *MostDerivedClass, 128 uint64_t MostDerivedClassOffset, 129 const CXXRecordDecl *LayoutClass); 130 131 /// getOverrider - Get the final overrider for the given method declaration in 132 /// the subobject with the given base offset. 133 OverriderInfo getOverrider(const CXXMethodDecl *MD, 134 CharUnits BaseOffset) const { 135 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) && 136 "Did not find overrider!"); 137 138 return OverridersMap.lookup(std::make_pair(MD, BaseOffset)); 139 } 140 141 /// dump - dump the final overriders. 142 void dump() { 143 VisitedVirtualBasesSetTy VisitedVirtualBases; 144 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()), 145 VisitedVirtualBases); 146 } 147 148}; 149 150#define DUMP_OVERRIDERS 0 151 152FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, 153 uint64_t MostDerivedClassOffset, 154 const CXXRecordDecl *LayoutClass) 155 : MostDerivedClass(MostDerivedClass), 156 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass), 157 Context(MostDerivedClass->getASTContext()), 158 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) { 159 160 // Compute base offsets. 161 SubobjectOffsetMapTy SubobjectOffsets; 162 SubobjectOffsetMapTy SubobjectLayoutClassOffsets; 163 SubobjectCountMapTy SubobjectCounts; 164 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 165 /*IsVirtual=*/false, 166 MostDerivedClassOffset, SubobjectOffsets, 167 SubobjectLayoutClassOffsets, SubobjectCounts); 168 169 // Get the the final overriders. 170 CXXFinalOverriderMap FinalOverriders; 171 MostDerivedClass->getFinalOverriders(FinalOverriders); 172 173 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 174 E = FinalOverriders.end(); I != E; ++I) { 175 const CXXMethodDecl *MD = I->first; 176 const OverridingMethods& Methods = I->second; 177 178 for (OverridingMethods::const_iterator I = Methods.begin(), 179 E = Methods.end(); I != E; ++I) { 180 unsigned SubobjectNumber = I->first; 181 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(), 182 SubobjectNumber)) && 183 "Did not find subobject offset!"); 184 185 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(), 186 SubobjectNumber)]; 187 188 assert(I->second.size() == 1 && "Final overrider is not unique!"); 189 const UniqueVirtualMethod &Method = I->second.front(); 190 191 const CXXRecordDecl *OverriderRD = Method.Method->getParent(); 192 assert(SubobjectLayoutClassOffsets.count( 193 std::make_pair(OverriderRD, Method.Subobject)) 194 && "Did not find subobject offset!"); 195 CharUnits OverriderOffset = 196 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD, 197 Method.Subobject)]; 198 199 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)]; 200 assert(!Overrider.Method && "Overrider should not exist yet!"); 201 202 Overrider.Offset = Context.toBits(OverriderOffset); 203 Overrider.Method = Method.Method; 204 } 205 } 206 207#if DUMP_OVERRIDERS 208 // And dump them (for now). 209 dump(); 210#endif 211} 212 213static BaseOffset ComputeBaseOffset(ASTContext &Context, 214 const CXXRecordDecl *DerivedRD, 215 const CXXBasePath &Path) { 216 int64_t NonVirtualOffset = 0; 217 218 unsigned NonVirtualStart = 0; 219 const CXXRecordDecl *VirtualBase = 0; 220 221 // First, look for the virtual base class. 222 for (unsigned I = 0, E = Path.size(); I != E; ++I) { 223 const CXXBasePathElement &Element = Path[I]; 224 225 if (Element.Base->isVirtual()) { 226 // FIXME: Can we break when we find the first virtual base? 227 // (If we can't, can't we just iterate over the path in reverse order?) 228 NonVirtualStart = I + 1; 229 QualType VBaseType = Element.Base->getType(); 230 VirtualBase = 231 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl()); 232 } 233 } 234 235 // Now compute the non-virtual offset. 236 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) { 237 const CXXBasePathElement &Element = Path[I]; 238 239 // Check the base class offset. 240 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class); 241 242 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>(); 243 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl()); 244 245 NonVirtualOffset += Layout.getBaseClassOffsetInBits(Base); 246 } 247 248 // FIXME: This should probably use CharUnits or something. Maybe we should 249 // even change the base offsets in ASTRecordLayout to be specified in 250 // CharUnits. 251 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8); 252 253} 254 255static BaseOffset ComputeBaseOffset(ASTContext &Context, 256 const CXXRecordDecl *BaseRD, 257 const CXXRecordDecl *DerivedRD) { 258 CXXBasePaths Paths(/*FindAmbiguities=*/false, 259 /*RecordPaths=*/true, /*DetectVirtual=*/false); 260 261 if (!const_cast<CXXRecordDecl *>(DerivedRD)-> 262 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) { 263 assert(false && "Class must be derived from the passed in base class!"); 264 return BaseOffset(); 265 } 266 267 return ComputeBaseOffset(Context, DerivedRD, Paths.front()); 268} 269 270static BaseOffset 271ComputeReturnAdjustmentBaseOffset(ASTContext &Context, 272 const CXXMethodDecl *DerivedMD, 273 const CXXMethodDecl *BaseMD) { 274 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>(); 275 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>(); 276 277 // Canonicalize the return types. 278 CanQualType CanDerivedReturnType = 279 Context.getCanonicalType(DerivedFT->getResultType()); 280 CanQualType CanBaseReturnType = 281 Context.getCanonicalType(BaseFT->getResultType()); 282 283 assert(CanDerivedReturnType->getTypeClass() == 284 CanBaseReturnType->getTypeClass() && 285 "Types must have same type class!"); 286 287 if (CanDerivedReturnType == CanBaseReturnType) { 288 // No adjustment needed. 289 return BaseOffset(); 290 } 291 292 if (isa<ReferenceType>(CanDerivedReturnType)) { 293 CanDerivedReturnType = 294 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType(); 295 CanBaseReturnType = 296 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType(); 297 } else if (isa<PointerType>(CanDerivedReturnType)) { 298 CanDerivedReturnType = 299 CanDerivedReturnType->getAs<PointerType>()->getPointeeType(); 300 CanBaseReturnType = 301 CanBaseReturnType->getAs<PointerType>()->getPointeeType(); 302 } else { 303 assert(false && "Unexpected return type!"); 304 } 305 306 // We need to compare unqualified types here; consider 307 // const T *Base::foo(); 308 // T *Derived::foo(); 309 if (CanDerivedReturnType.getUnqualifiedType() == 310 CanBaseReturnType.getUnqualifiedType()) { 311 // No adjustment needed. 312 return BaseOffset(); 313 } 314 315 const CXXRecordDecl *DerivedRD = 316 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl()); 317 318 const CXXRecordDecl *BaseRD = 319 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl()); 320 321 return ComputeBaseOffset(Context, BaseRD, DerivedRD); 322} 323 324void 325FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, 326 uint64_t OffsetInLayoutClass, 327 SubobjectOffsetMapTy &SubobjectOffsets, 328 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets, 329 SubobjectCountMapTy &SubobjectCounts) { 330 const CXXRecordDecl *RD = Base.getBase(); 331 332 unsigned SubobjectNumber = 0; 333 if (!IsVirtual) 334 SubobjectNumber = ++SubobjectCounts[RD]; 335 336 // Set up the subobject to offset mapping. 337 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber)) 338 && "Subobject offset already exists!"); 339 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber)) 340 && "Subobject offset already exists!"); 341 342 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset(); 343 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] = 344 Context.toCharUnitsFromBits(OffsetInLayoutClass); 345 346 // Traverse our bases. 347 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 348 E = RD->bases_end(); I != E; ++I) { 349 const CXXRecordDecl *BaseDecl = 350 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 351 352 CharUnits BaseOffset; 353 CharUnits BaseOffsetInLayoutClass; 354 if (I->isVirtual()) { 355 // Check if we've visited this virtual base before. 356 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0))) 357 continue; 358 359 const ASTRecordLayout &LayoutClassLayout = 360 Context.getASTRecordLayout(LayoutClass); 361 362 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); 363 BaseOffsetInLayoutClass = 364 LayoutClassLayout.getVBaseClassOffset(BaseDecl); 365 } else { 366 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 367 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl); 368 369 BaseOffset = Base.getBaseOffset() + Offset; 370 BaseOffsetInLayoutClass = 371 Context.toCharUnitsFromBits(OffsetInLayoutClass) + Offset; 372 } 373 374 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), 375 I->isVirtual(), Context.toBits(BaseOffsetInLayoutClass), 376 SubobjectOffsets, SubobjectLayoutClassOffsets, 377 SubobjectCounts); 378 } 379} 380 381void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base, 382 VisitedVirtualBasesSetTy &VisitedVirtualBases) { 383 const CXXRecordDecl *RD = Base.getBase(); 384 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 385 386 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 387 E = RD->bases_end(); I != E; ++I) { 388 const CXXRecordDecl *BaseDecl = 389 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 390 391 // Ignore bases that don't have any virtual member functions. 392 if (!BaseDecl->isPolymorphic()) 393 continue; 394 395 CharUnits BaseOffset; 396 if (I->isVirtual()) { 397 if (!VisitedVirtualBases.insert(BaseDecl)) { 398 // We've visited this base before. 399 continue; 400 } 401 402 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); 403 } else { 404 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset(); 405 } 406 407 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases); 408 } 409 410 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", "; 411 Out << Base.getBaseOffset().getQuantity() << ")\n"; 412 413 // Now dump the overriders for this base subobject. 414 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 415 E = RD->method_end(); I != E; ++I) { 416 const CXXMethodDecl *MD = *I; 417 418 if (!MD->isVirtual()) 419 continue; 420 421 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset()); 422 423 Out << " " << MD->getQualifiedNameAsString() << " - ("; 424 Out << Overrider.Method->getQualifiedNameAsString(); 425 Out << ", " << ", " << Overrider.Offset / 8 << ')'; 426 427 BaseOffset Offset; 428 if (!Overrider.Method->isPure()) 429 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD); 430 431 if (!Offset.isEmpty()) { 432 Out << " [ret-adj: "; 433 if (Offset.VirtualBase) 434 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, "; 435 436 Out << Offset.NonVirtualOffset << " nv]"; 437 } 438 439 Out << "\n"; 440 } 441} 442 443/// VTableComponent - Represents a single component in a vtable. 444class VTableComponent { 445public: 446 enum Kind { 447 CK_VCallOffset, 448 CK_VBaseOffset, 449 CK_OffsetToTop, 450 CK_RTTI, 451 CK_FunctionPointer, 452 453 /// CK_CompleteDtorPointer - A pointer to the complete destructor. 454 CK_CompleteDtorPointer, 455 456 /// CK_DeletingDtorPointer - A pointer to the deleting destructor. 457 CK_DeletingDtorPointer, 458 459 /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer 460 /// will end up never being called. Such vtable function pointers are 461 /// represented as a CK_UnusedFunctionPointer. 462 CK_UnusedFunctionPointer 463 }; 464 465 static VTableComponent MakeVCallOffset(int64_t Offset) { 466 return VTableComponent(CK_VCallOffset, Offset); 467 } 468 469 static VTableComponent MakeVBaseOffset(int64_t Offset) { 470 return VTableComponent(CK_VBaseOffset, Offset); 471 } 472 473 static VTableComponent MakeOffsetToTop(int64_t Offset) { 474 return VTableComponent(CK_OffsetToTop, Offset); 475 } 476 477 static VTableComponent MakeRTTI(const CXXRecordDecl *RD) { 478 return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD)); 479 } 480 481 static VTableComponent MakeFunction(const CXXMethodDecl *MD) { 482 assert(!isa<CXXDestructorDecl>(MD) && 483 "Don't use MakeFunction with destructors!"); 484 485 return VTableComponent(CK_FunctionPointer, 486 reinterpret_cast<uintptr_t>(MD)); 487 } 488 489 static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) { 490 return VTableComponent(CK_CompleteDtorPointer, 491 reinterpret_cast<uintptr_t>(DD)); 492 } 493 494 static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) { 495 return VTableComponent(CK_DeletingDtorPointer, 496 reinterpret_cast<uintptr_t>(DD)); 497 } 498 499 static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) { 500 assert(!isa<CXXDestructorDecl>(MD) && 501 "Don't use MakeUnusedFunction with destructors!"); 502 return VTableComponent(CK_UnusedFunctionPointer, 503 reinterpret_cast<uintptr_t>(MD)); 504 } 505 506 static VTableComponent getFromOpaqueInteger(uint64_t I) { 507 return VTableComponent(I); 508 } 509 510 /// getKind - Get the kind of this vtable component. 511 Kind getKind() const { 512 return (Kind)(Value & 0x7); 513 } 514 515 int64_t getVCallOffset() const { 516 assert(getKind() == CK_VCallOffset && "Invalid component kind!"); 517 518 return getOffset(); 519 } 520 521 int64_t getVBaseOffset() const { 522 assert(getKind() == CK_VBaseOffset && "Invalid component kind!"); 523 524 return getOffset(); 525 } 526 527 int64_t getOffsetToTop() const { 528 assert(getKind() == CK_OffsetToTop && "Invalid component kind!"); 529 530 return getOffset(); 531 } 532 533 const CXXRecordDecl *getRTTIDecl() const { 534 assert(getKind() == CK_RTTI && "Invalid component kind!"); 535 536 return reinterpret_cast<CXXRecordDecl *>(getPointer()); 537 } 538 539 const CXXMethodDecl *getFunctionDecl() const { 540 assert(getKind() == CK_FunctionPointer); 541 542 return reinterpret_cast<CXXMethodDecl *>(getPointer()); 543 } 544 545 const CXXDestructorDecl *getDestructorDecl() const { 546 assert((getKind() == CK_CompleteDtorPointer || 547 getKind() == CK_DeletingDtorPointer) && "Invalid component kind!"); 548 549 return reinterpret_cast<CXXDestructorDecl *>(getPointer()); 550 } 551 552 const CXXMethodDecl *getUnusedFunctionDecl() const { 553 assert(getKind() == CK_UnusedFunctionPointer); 554 555 return reinterpret_cast<CXXMethodDecl *>(getPointer()); 556 } 557 558private: 559 VTableComponent(Kind ComponentKind, int64_t Offset) { 560 assert((ComponentKind == CK_VCallOffset || 561 ComponentKind == CK_VBaseOffset || 562 ComponentKind == CK_OffsetToTop) && "Invalid component kind!"); 563 assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!"); 564 565 Value = ((Offset << 3) | ComponentKind); 566 } 567 568 VTableComponent(Kind ComponentKind, uintptr_t Ptr) { 569 assert((ComponentKind == CK_RTTI || 570 ComponentKind == CK_FunctionPointer || 571 ComponentKind == CK_CompleteDtorPointer || 572 ComponentKind == CK_DeletingDtorPointer || 573 ComponentKind == CK_UnusedFunctionPointer) && 574 "Invalid component kind!"); 575 576 assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!"); 577 578 Value = Ptr | ComponentKind; 579 } 580 581 int64_t getOffset() const { 582 assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset || 583 getKind() == CK_OffsetToTop) && "Invalid component kind!"); 584 585 return Value >> 3; 586 } 587 588 uintptr_t getPointer() const { 589 assert((getKind() == CK_RTTI || 590 getKind() == CK_FunctionPointer || 591 getKind() == CK_CompleteDtorPointer || 592 getKind() == CK_DeletingDtorPointer || 593 getKind() == CK_UnusedFunctionPointer) && 594 "Invalid component kind!"); 595 596 return static_cast<uintptr_t>(Value & ~7ULL); 597 } 598 599 explicit VTableComponent(uint64_t Value) 600 : Value(Value) { } 601 602 /// The kind is stored in the lower 3 bits of the value. For offsets, we 603 /// make use of the facts that classes can't be larger than 2^55 bytes, 604 /// so we store the offset in the lower part of the 61 bytes that remain. 605 /// (The reason that we're not simply using a PointerIntPair here is that we 606 /// need the offsets to be 64-bit, even when on a 32-bit machine). 607 int64_t Value; 608}; 609 610/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable. 611struct VCallOffsetMap { 612 613 typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy; 614 615 /// Offsets - Keeps track of methods and their offsets. 616 // FIXME: This should be a real map and not a vector. 617 llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets; 618 619 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions 620 /// can share the same vcall offset. 621 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS, 622 const CXXMethodDecl *RHS); 623 624public: 625 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the 626 /// add was successful, or false if there was already a member function with 627 /// the same signature in the map. 628 bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset); 629 630 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the 631 /// vtable address point) for the given virtual member function. 632 int64_t getVCallOffsetOffset(const CXXMethodDecl *MD); 633 634 // empty - Return whether the offset map is empty or not. 635 bool empty() const { return Offsets.empty(); } 636}; 637 638static bool HasSameVirtualSignature(const CXXMethodDecl *LHS, 639 const CXXMethodDecl *RHS) { 640 ASTContext &C = LHS->getASTContext(); // TODO: thread this down 641 CanQual<FunctionProtoType> 642 LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(), 643 RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>(); 644 645 // Fast-path matches in the canonical types. 646 if (LT == RT) return true; 647 648 // Force the signatures to match. We can't rely on the overrides 649 // list here because there isn't necessarily an inheritance 650 // relationship between the two methods. 651 if (LT.getQualifiers() != RT.getQualifiers() || 652 LT->getNumArgs() != RT->getNumArgs()) 653 return false; 654 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I) 655 if (LT->getArgType(I) != RT->getArgType(I)) 656 return false; 657 return true; 658} 659 660bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS, 661 const CXXMethodDecl *RHS) { 662 assert(LHS->isVirtual() && "LHS must be virtual!"); 663 assert(RHS->isVirtual() && "LHS must be virtual!"); 664 665 // A destructor can share a vcall offset with another destructor. 666 if (isa<CXXDestructorDecl>(LHS)) 667 return isa<CXXDestructorDecl>(RHS); 668 669 // FIXME: We need to check more things here. 670 671 // The methods must have the same name. 672 DeclarationName LHSName = LHS->getDeclName(); 673 DeclarationName RHSName = RHS->getDeclName(); 674 if (LHSName != RHSName) 675 return false; 676 677 // And the same signatures. 678 return HasSameVirtualSignature(LHS, RHS); 679} 680 681bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, 682 int64_t OffsetOffset) { 683 // Check if we can reuse an offset. 684 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) { 685 if (MethodsCanShareVCallOffset(Offsets[I].first, MD)) 686 return false; 687 } 688 689 // Add the offset. 690 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset)); 691 return true; 692} 693 694int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) { 695 // Look for an offset. 696 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) { 697 if (MethodsCanShareVCallOffset(Offsets[I].first, MD)) 698 return Offsets[I].second; 699 } 700 701 assert(false && "Should always find a vcall offset offset!"); 702 return 0; 703} 704 705/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets. 706class VCallAndVBaseOffsetBuilder { 707public: 708 typedef llvm::DenseMap<const CXXRecordDecl *, int64_t> 709 VBaseOffsetOffsetsMapTy; 710 711private: 712 /// MostDerivedClass - The most derived class for which we're building vcall 713 /// and vbase offsets. 714 const CXXRecordDecl *MostDerivedClass; 715 716 /// LayoutClass - The class we're using for layout information. Will be 717 /// different than the most derived class if we're building a construction 718 /// vtable. 719 const CXXRecordDecl *LayoutClass; 720 721 /// Context - The ASTContext which we will use for layout information. 722 ASTContext &Context; 723 724 /// Components - vcall and vbase offset components 725 typedef llvm::SmallVector<VTableComponent, 64> VTableComponentVectorTy; 726 VTableComponentVectorTy Components; 727 728 /// VisitedVirtualBases - Visited virtual bases. 729 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; 730 731 /// VCallOffsets - Keeps track of vcall offsets. 732 VCallOffsetMap VCallOffsets; 733 734 735 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets, 736 /// relative to the address point. 737 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets; 738 739 /// FinalOverriders - The final overriders of the most derived class. 740 /// (Can be null when we're not building a vtable of the most derived class). 741 const FinalOverriders *Overriders; 742 743 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the 744 /// given base subobject. 745 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual, 746 uint64_t RealBaseOffset); 747 748 /// AddVCallOffsets - Add vcall offsets for the given base subobject. 749 void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset); 750 751 /// AddVBaseOffsets - Add vbase offsets for the given class. 752 void AddVBaseOffsets(const CXXRecordDecl *Base, uint64_t OffsetInLayoutClass); 753 754 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in 755 /// bytes, relative to the vtable address point. 756 int64_t getCurrentOffsetOffset() const; 757 758public: 759 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass, 760 const CXXRecordDecl *LayoutClass, 761 const FinalOverriders *Overriders, 762 BaseSubobject Base, bool BaseIsVirtual, 763 uint64_t OffsetInLayoutClass) 764 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), 765 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) { 766 767 // Add vcall and vbase offsets. 768 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass); 769 } 770 771 /// Methods for iterating over the components. 772 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator; 773 const_iterator components_begin() const { return Components.rbegin(); } 774 const_iterator components_end() const { return Components.rend(); } 775 776 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; } 777 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const { 778 return VBaseOffsetOffsets; 779 } 780}; 781 782void 783VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, 784 bool BaseIsVirtual, 785 uint64_t RealBaseOffset) { 786 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase()); 787 788 // Itanium C++ ABI 2.5.2: 789 // ..in classes sharing a virtual table with a primary base class, the vcall 790 // and vbase offsets added by the derived class all come before the vcall 791 // and vbase offsets required by the base class, so that the latter may be 792 // laid out as required by the base class without regard to additions from 793 // the derived class(es). 794 795 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll 796 // emit them for the primary base first). 797 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) { 798 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual(); 799 800 CharUnits PrimaryBaseOffset; 801 802 // Get the base offset of the primary base. 803 if (PrimaryBaseIsVirtual) { 804 assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 && 805 "Primary vbase should have a zero offset!"); 806 807 const ASTRecordLayout &MostDerivedClassLayout = 808 Context.getASTRecordLayout(MostDerivedClass); 809 810 PrimaryBaseOffset = 811 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase); 812 } else { 813 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 && 814 "Primary base should have a zero offset!"); 815 816 PrimaryBaseOffset = Base.getBaseOffset(); 817 } 818 819 AddVCallAndVBaseOffsets( 820 BaseSubobject(PrimaryBase,PrimaryBaseOffset), 821 PrimaryBaseIsVirtual, RealBaseOffset); 822 } 823 824 AddVBaseOffsets(Base.getBase(), RealBaseOffset); 825 826 // We only want to add vcall offsets for virtual bases. 827 if (BaseIsVirtual) 828 AddVCallOffsets(Base, RealBaseOffset); 829} 830 831int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const { 832 // OffsetIndex is the index of this vcall or vbase offset, relative to the 833 // vtable address point. (We subtract 3 to account for the information just 834 // above the address point, the RTTI info, the offset to top, and the 835 // vcall offset itself). 836 int64_t OffsetIndex = -(int64_t)(3 + Components.size()); 837 838 // FIXME: We shouldn't use / 8 here. 839 int64_t OffsetOffset = OffsetIndex * 840 (int64_t)Context.Target.getPointerWidth(0) / 8; 841 842 return OffsetOffset; 843} 844 845void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, 846 uint64_t VBaseOffset) { 847 const CXXRecordDecl *RD = Base.getBase(); 848 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 849 850 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 851 852 // Handle the primary base first. 853 // We only want to add vcall offsets if the base is non-virtual; a virtual 854 // primary base will have its vcall and vbase offsets emitted already. 855 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) { 856 // Get the base offset of the primary base. 857 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 && 858 "Primary base should have a zero offset!"); 859 860 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()), 861 VBaseOffset); 862 } 863 864 // Add the vcall offsets. 865 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 866 E = RD->method_end(); I != E; ++I) { 867 const CXXMethodDecl *MD = *I; 868 869 if (!MD->isVirtual()) 870 continue; 871 872 int64_t OffsetOffset = getCurrentOffsetOffset(); 873 874 // Don't add a vcall offset if we already have one for this member function 875 // signature. 876 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset)) 877 continue; 878 879 int64_t Offset = 0; 880 881 if (Overriders) { 882 // Get the final overrider. 883 FinalOverriders::OverriderInfo Overrider = 884 Overriders->getOverrider(MD, Base.getBaseOffset()); 885 886 /// The vcall offset is the offset from the virtual base to the object 887 /// where the function was overridden. 888 // FIXME: We should not use / 8 here. 889 Offset = (int64_t)(Overrider.Offset - VBaseOffset) / 8; 890 } 891 892 Components.push_back(VTableComponent::MakeVCallOffset(Offset)); 893 } 894 895 // And iterate over all non-virtual bases (ignoring the primary base). 896 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 897 E = RD->bases_end(); I != E; ++I) { 898 899 if (I->isVirtual()) 900 continue; 901 902 const CXXRecordDecl *BaseDecl = 903 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 904 if (BaseDecl == PrimaryBase) 905 continue; 906 907 // Get the base offset of this base. 908 CharUnits BaseOffset = Base.getBaseOffset() + 909 Layout.getBaseClassOffset(BaseDecl); 910 911 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), 912 VBaseOffset); 913 } 914} 915 916void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, 917 uint64_t OffsetInLayoutClass) { 918 const ASTRecordLayout &LayoutClassLayout = 919 Context.getASTRecordLayout(LayoutClass); 920 921 // Add vbase offsets. 922 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 923 E = RD->bases_end(); I != E; ++I) { 924 const CXXRecordDecl *BaseDecl = 925 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 926 927 // Check if this is a virtual base that we haven't visited before. 928 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) { 929 // FIXME: We shouldn't use / 8 here. 930 int64_t Offset = 931 (int64_t)(LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl) - 932 OffsetInLayoutClass) / 8; 933 934 // Add the vbase offset offset. 935 assert(!VBaseOffsetOffsets.count(BaseDecl) && 936 "vbase offset offset already exists!"); 937 938 int64_t VBaseOffsetOffset = getCurrentOffsetOffset(); 939 VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset)); 940 941 Components.push_back(VTableComponent::MakeVBaseOffset(Offset)); 942 } 943 944 // Check the base class looking for more vbase offsets. 945 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass); 946 } 947} 948 949/// VTableBuilder - Class for building vtable layout information. 950class VTableBuilder { 951public: 952 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect 953 /// primary bases. 954 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> 955 PrimaryBasesSetVectorTy; 956 957 typedef llvm::DenseMap<const CXXRecordDecl *, int64_t> 958 VBaseOffsetOffsetsMapTy; 959 960 typedef llvm::DenseMap<BaseSubobject, uint64_t> 961 AddressPointsMapTy; 962 963private: 964 /// VTables - Global vtable information. 965 CodeGenVTables &VTables; 966 967 /// MostDerivedClass - The most derived class for which we're building this 968 /// vtable. 969 const CXXRecordDecl *MostDerivedClass; 970 971 /// MostDerivedClassOffset - If we're building a construction vtable, this 972 /// holds the offset from the layout class to the most derived class. 973 const uint64_t MostDerivedClassOffset; 974 975 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual 976 /// base. (This only makes sense when building a construction vtable). 977 bool MostDerivedClassIsVirtual; 978 979 /// LayoutClass - The class we're using for layout information. Will be 980 /// different than the most derived class if we're building a construction 981 /// vtable. 982 const CXXRecordDecl *LayoutClass; 983 984 /// Context - The ASTContext which we will use for layout information. 985 ASTContext &Context; 986 987 /// FinalOverriders - The final overriders of the most derived class. 988 const FinalOverriders Overriders; 989 990 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual 991 /// bases in this vtable. 992 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases; 993 994 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for 995 /// the most derived class. 996 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets; 997 998 /// Components - The components of the vtable being built. 999 llvm::SmallVector<VTableComponent, 64> Components; 1000 1001 /// AddressPoints - Address points for the vtable being built. 1002 AddressPointsMapTy AddressPoints; 1003 1004 /// MethodInfo - Contains information about a method in a vtable. 1005 /// (Used for computing 'this' pointer adjustment thunks. 1006 struct MethodInfo { 1007 /// BaseOffset - The base offset of this method. 1008 const uint64_t BaseOffset; 1009 1010 /// BaseOffsetInLayoutClass - The base offset in the layout class of this 1011 /// method. 1012 const uint64_t BaseOffsetInLayoutClass; 1013 1014 /// VTableIndex - The index in the vtable that this method has. 1015 /// (For destructors, this is the index of the complete destructor). 1016 const uint64_t VTableIndex; 1017 1018 MethodInfo(uint64_t BaseOffset, uint64_t BaseOffsetInLayoutClass, 1019 uint64_t VTableIndex) 1020 : BaseOffset(BaseOffset), 1021 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass), 1022 VTableIndex(VTableIndex) { } 1023 1024 MethodInfo() : BaseOffset(0), BaseOffsetInLayoutClass(0), VTableIndex(0) { } 1025 }; 1026 1027 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy; 1028 1029 /// MethodInfoMap - The information for all methods in the vtable we're 1030 /// currently building. 1031 MethodInfoMapTy MethodInfoMap; 1032 1033 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy; 1034 1035 /// VTableThunks - The thunks by vtable index in the vtable currently being 1036 /// built. 1037 VTableThunksMapTy VTableThunks; 1038 1039 typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy; 1040 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy; 1041 1042 /// Thunks - A map that contains all the thunks needed for all methods in the 1043 /// most derived class for which the vtable is currently being built. 1044 ThunksMapTy Thunks; 1045 1046 /// AddThunk - Add a thunk for the given method. 1047 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk); 1048 1049 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the 1050 /// part of the vtable we're currently building. 1051 void ComputeThisAdjustments(); 1052 1053 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1054 1055 /// PrimaryVirtualBases - All known virtual bases who are a primary base of 1056 /// some other base. 1057 VisitedVirtualBasesSetTy PrimaryVirtualBases; 1058 1059 /// ComputeReturnAdjustment - Compute the return adjustment given a return 1060 /// adjustment base offset. 1061 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset); 1062 1063 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting 1064 /// the 'this' pointer from the base subobject to the derived subobject. 1065 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base, 1066 BaseSubobject Derived) const; 1067 1068 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the 1069 /// given virtual member function, its offset in the layout class and its 1070 /// final overrider. 1071 ThisAdjustment 1072 ComputeThisAdjustment(const CXXMethodDecl *MD, 1073 uint64_t BaseOffsetInLayoutClass, 1074 FinalOverriders::OverriderInfo Overrider); 1075 1076 /// AddMethod - Add a single virtual member function to the vtable 1077 /// components vector. 1078 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment); 1079 1080 /// IsOverriderUsed - Returns whether the overrider will ever be used in this 1081 /// part of the vtable. 1082 /// 1083 /// Itanium C++ ABI 2.5.2: 1084 /// 1085 /// struct A { virtual void f(); }; 1086 /// struct B : virtual public A { int i; }; 1087 /// struct C : virtual public A { int j; }; 1088 /// struct D : public B, public C {}; 1089 /// 1090 /// When B and C are declared, A is a primary base in each case, so although 1091 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this 1092 /// adjustment is required and no thunk is generated. However, inside D 1093 /// objects, A is no longer a primary base of C, so if we allowed calls to 1094 /// C::f() to use the copy of A's vtable in the C subobject, we would need 1095 /// to adjust this from C* to B::A*, which would require a third-party 1096 /// thunk. Since we require that a call to C::f() first convert to A*, 1097 /// C-in-D's copy of A's vtable is never referenced, so this is not 1098 /// necessary. 1099 bool IsOverriderUsed(const CXXMethodDecl *Overrider, 1100 uint64_t BaseOffsetInLayoutClass, 1101 const CXXRecordDecl *FirstBaseInPrimaryBaseChain, 1102 uint64_t FirstBaseOffsetInLayoutClass) const; 1103 1104 1105 /// AddMethods - Add the methods of this base subobject and all its 1106 /// primary bases to the vtable components vector. 1107 void AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass, 1108 const CXXRecordDecl *FirstBaseInPrimaryBaseChain, 1109 uint64_t FirstBaseOffsetInLayoutClass, 1110 PrimaryBasesSetVectorTy &PrimaryBases); 1111 1112 // LayoutVTable - Layout the vtable for the given base class, including its 1113 // secondary vtables and any vtables for virtual bases. 1114 void LayoutVTable(); 1115 1116 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the 1117 /// given base subobject, as well as all its secondary vtables. 1118 /// 1119 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base 1120 /// or a direct or indirect base of a virtual base. 1121 /// 1122 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual 1123 /// in the layout class. 1124 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base, 1125 bool BaseIsMorallyVirtual, 1126 bool BaseIsVirtualInLayoutClass, 1127 uint64_t OffsetInLayoutClass); 1128 1129 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base 1130 /// subobject. 1131 /// 1132 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base 1133 /// or a direct or indirect base of a virtual base. 1134 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual, 1135 uint64_t OffsetInLayoutClass); 1136 1137 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this 1138 /// class hierarchy. 1139 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, 1140 uint64_t OffsetInLayoutClass, 1141 VisitedVirtualBasesSetTy &VBases); 1142 1143 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the 1144 /// given base (excluding any primary bases). 1145 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, 1146 VisitedVirtualBasesSetTy &VBases); 1147 1148 /// isBuildingConstructionVTable - Return whether this vtable builder is 1149 /// building a construction vtable. 1150 bool isBuildingConstructorVTable() const { 1151 return MostDerivedClass != LayoutClass; 1152 } 1153 1154public: 1155 VTableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass, 1156 uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual, 1157 const CXXRecordDecl *LayoutClass) 1158 : VTables(VTables), MostDerivedClass(MostDerivedClass), 1159 MostDerivedClassOffset(MostDerivedClassOffset), 1160 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual), 1161 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), 1162 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) { 1163 1164 LayoutVTable(); 1165 } 1166 1167 ThunksMapTy::const_iterator thunks_begin() const { 1168 return Thunks.begin(); 1169 } 1170 1171 ThunksMapTy::const_iterator thunks_end() const { 1172 return Thunks.end(); 1173 } 1174 1175 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const { 1176 return VBaseOffsetOffsets; 1177 } 1178 1179 /// getNumVTableComponents - Return the number of components in the vtable 1180 /// currently built. 1181 uint64_t getNumVTableComponents() const { 1182 return Components.size(); 1183 } 1184 1185 const uint64_t *vtable_components_data_begin() const { 1186 return reinterpret_cast<const uint64_t *>(Components.begin()); 1187 } 1188 1189 const uint64_t *vtable_components_data_end() const { 1190 return reinterpret_cast<const uint64_t *>(Components.end()); 1191 } 1192 1193 AddressPointsMapTy::const_iterator address_points_begin() const { 1194 return AddressPoints.begin(); 1195 } 1196 1197 AddressPointsMapTy::const_iterator address_points_end() const { 1198 return AddressPoints.end(); 1199 } 1200 1201 VTableThunksMapTy::const_iterator vtable_thunks_begin() const { 1202 return VTableThunks.begin(); 1203 } 1204 1205 VTableThunksMapTy::const_iterator vtable_thunks_end() const { 1206 return VTableThunks.end(); 1207 } 1208 1209 /// dumpLayout - Dump the vtable layout. 1210 void dumpLayout(llvm::raw_ostream&); 1211}; 1212 1213void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) { 1214 assert(!isBuildingConstructorVTable() && 1215 "Can't add thunks for construction vtable"); 1216 1217 llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD]; 1218 1219 // Check if we have this thunk already. 1220 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != 1221 ThunksVector.end()) 1222 return; 1223 1224 ThunksVector.push_back(Thunk); 1225} 1226 1227typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy; 1228 1229/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all 1230/// the overridden methods that the function decl overrides. 1231static void 1232ComputeAllOverriddenMethods(const CXXMethodDecl *MD, 1233 OverriddenMethodsSetTy& OverriddenMethods) { 1234 assert(MD->isVirtual() && "Method is not virtual!"); 1235 1236 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1237 E = MD->end_overridden_methods(); I != E; ++I) { 1238 const CXXMethodDecl *OverriddenMD = *I; 1239 1240 OverriddenMethods.insert(OverriddenMD); 1241 1242 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods); 1243 } 1244} 1245 1246void VTableBuilder::ComputeThisAdjustments() { 1247 // Now go through the method info map and see if any of the methods need 1248 // 'this' pointer adjustments. 1249 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(), 1250 E = MethodInfoMap.end(); I != E; ++I) { 1251 const CXXMethodDecl *MD = I->first; 1252 const MethodInfo &MethodInfo = I->second; 1253 1254 // Ignore adjustments for unused function pointers. 1255 uint64_t VTableIndex = MethodInfo.VTableIndex; 1256 if (Components[VTableIndex].getKind() == 1257 VTableComponent::CK_UnusedFunctionPointer) 1258 continue; 1259 1260 // Get the final overrider for this method. 1261 FinalOverriders::OverriderInfo Overrider = 1262 Overriders.getOverrider(MD, 1263 Context.toCharUnitsFromBits(MethodInfo.BaseOffset)); 1264 1265 // Check if we need an adjustment at all. 1266 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) { 1267 // When a return thunk is needed by a derived class that overrides a 1268 // virtual base, gcc uses a virtual 'this' adjustment as well. 1269 // While the thunk itself might be needed by vtables in subclasses or 1270 // in construction vtables, there doesn't seem to be a reason for using 1271 // the thunk in this vtable. Still, we do so to match gcc. 1272 if (VTableThunks.lookup(VTableIndex).Return.isEmpty()) 1273 continue; 1274 } 1275 1276 ThisAdjustment ThisAdjustment = 1277 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider); 1278 1279 if (ThisAdjustment.isEmpty()) 1280 continue; 1281 1282 // Add it. 1283 VTableThunks[VTableIndex].This = ThisAdjustment; 1284 1285 if (isa<CXXDestructorDecl>(MD)) { 1286 // Add an adjustment for the deleting destructor as well. 1287 VTableThunks[VTableIndex + 1].This = ThisAdjustment; 1288 } 1289 } 1290 1291 /// Clear the method info map. 1292 MethodInfoMap.clear(); 1293 1294 if (isBuildingConstructorVTable()) { 1295 // We don't need to store thunk information for construction vtables. 1296 return; 1297 } 1298 1299 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(), 1300 E = VTableThunks.end(); I != E; ++I) { 1301 const VTableComponent &Component = Components[I->first]; 1302 const ThunkInfo &Thunk = I->second; 1303 const CXXMethodDecl *MD; 1304 1305 switch (Component.getKind()) { 1306 default: 1307 llvm_unreachable("Unexpected vtable component kind!"); 1308 case VTableComponent::CK_FunctionPointer: 1309 MD = Component.getFunctionDecl(); 1310 break; 1311 case VTableComponent::CK_CompleteDtorPointer: 1312 MD = Component.getDestructorDecl(); 1313 break; 1314 case VTableComponent::CK_DeletingDtorPointer: 1315 // We've already added the thunk when we saw the complete dtor pointer. 1316 continue; 1317 } 1318 1319 if (MD->getParent() == MostDerivedClass) 1320 AddThunk(MD, Thunk); 1321 } 1322} 1323 1324ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) { 1325 ReturnAdjustment Adjustment; 1326 1327 if (!Offset.isEmpty()) { 1328 if (Offset.VirtualBase) { 1329 // Get the virtual base offset offset. 1330 if (Offset.DerivedClass == MostDerivedClass) { 1331 // We can get the offset offset directly from our map. 1332 Adjustment.VBaseOffsetOffset = 1333 VBaseOffsetOffsets.lookup(Offset.VirtualBase); 1334 } else { 1335 Adjustment.VBaseOffsetOffset = 1336 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass, 1337 Offset.VirtualBase); 1338 } 1339 } 1340 1341 Adjustment.NonVirtual = Offset.NonVirtualOffset; 1342 } 1343 1344 return Adjustment; 1345} 1346 1347BaseOffset 1348VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base, 1349 BaseSubobject Derived) const { 1350 const CXXRecordDecl *BaseRD = Base.getBase(); 1351 const CXXRecordDecl *DerivedRD = Derived.getBase(); 1352 1353 CXXBasePaths Paths(/*FindAmbiguities=*/true, 1354 /*RecordPaths=*/true, /*DetectVirtual=*/true); 1355 1356 if (!const_cast<CXXRecordDecl *>(DerivedRD)-> 1357 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) { 1358 assert(false && "Class must be derived from the passed in base class!"); 1359 return BaseOffset(); 1360 } 1361 1362 // We have to go through all the paths, and see which one leads us to the 1363 // right base subobject. 1364 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end(); 1365 I != E; ++I) { 1366 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I); 1367 1368 CharUnits OffsetToBaseSubobject = 1369 CharUnits::fromQuantity(Offset.NonVirtualOffset); 1370 1371 if (Offset.VirtualBase) { 1372 // If we have a virtual base class, the non-virtual offset is relative 1373 // to the virtual base class offset. 1374 const ASTRecordLayout &LayoutClassLayout = 1375 Context.getASTRecordLayout(LayoutClass); 1376 1377 /// Get the virtual base offset, relative to the most derived class 1378 /// layout. 1379 OffsetToBaseSubobject += 1380 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase); 1381 } else { 1382 // Otherwise, the non-virtual offset is relative to the derived class 1383 // offset. 1384 OffsetToBaseSubobject += Derived.getBaseOffset(); 1385 } 1386 1387 // Check if this path gives us the right base subobject. 1388 if (OffsetToBaseSubobject == Base.getBaseOffset()) { 1389 // Since we're going from the base class _to_ the derived class, we'll 1390 // invert the non-virtual offset here. 1391 Offset.NonVirtualOffset = -Offset.NonVirtualOffset; 1392 return Offset; 1393 } 1394 } 1395 1396 return BaseOffset(); 1397} 1398 1399ThisAdjustment 1400VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD, 1401 uint64_t BaseOffsetInLayoutClass, 1402 FinalOverriders::OverriderInfo Overrider) { 1403 // Ignore adjustments for pure virtual member functions. 1404 if (Overrider.Method->isPure()) 1405 return ThisAdjustment(); 1406 1407 BaseSubobject OverriddenBaseSubobject(MD->getParent(), 1408 Context.toCharUnitsFromBits( 1409 BaseOffsetInLayoutClass)); 1410 1411 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(), 1412 Context.toCharUnitsFromBits( 1413 Overrider.Offset)); 1414 1415 // Compute the adjustment offset. 1416 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject, 1417 OverriderBaseSubobject); 1418 if (Offset.isEmpty()) 1419 return ThisAdjustment(); 1420 1421 ThisAdjustment Adjustment; 1422 1423 if (Offset.VirtualBase) { 1424 // Get the vcall offset map for this virtual base. 1425 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase]; 1426 1427 if (VCallOffsets.empty()) { 1428 // We don't have vcall offsets for this virtual base, go ahead and 1429 // build them. 1430 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass, 1431 /*FinalOverriders=*/0, 1432 BaseSubobject(Offset.VirtualBase, 1433 CharUnits::Zero()), 1434 /*BaseIsVirtual=*/true, 1435 /*OffsetInLayoutClass=*/0); 1436 1437 VCallOffsets = Builder.getVCallOffsets(); 1438 } 1439 1440 Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD); 1441 } 1442 1443 // Set the non-virtual part of the adjustment. 1444 Adjustment.NonVirtual = Offset.NonVirtualOffset; 1445 1446 return Adjustment; 1447} 1448 1449void 1450VTableBuilder::AddMethod(const CXXMethodDecl *MD, 1451 ReturnAdjustment ReturnAdjustment) { 1452 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1453 assert(ReturnAdjustment.isEmpty() && 1454 "Destructor can't have return adjustment!"); 1455 1456 // Add both the complete destructor and the deleting destructor. 1457 Components.push_back(VTableComponent::MakeCompleteDtor(DD)); 1458 Components.push_back(VTableComponent::MakeDeletingDtor(DD)); 1459 } else { 1460 // Add the return adjustment if necessary. 1461 if (!ReturnAdjustment.isEmpty()) 1462 VTableThunks[Components.size()].Return = ReturnAdjustment; 1463 1464 // Add the function. 1465 Components.push_back(VTableComponent::MakeFunction(MD)); 1466 } 1467} 1468 1469/// OverridesIndirectMethodInBase - Return whether the given member function 1470/// overrides any methods in the set of given bases. 1471/// Unlike OverridesMethodInBase, this checks "overriders of overriders". 1472/// For example, if we have: 1473/// 1474/// struct A { virtual void f(); } 1475/// struct B : A { virtual void f(); } 1476/// struct C : B { virtual void f(); } 1477/// 1478/// OverridesIndirectMethodInBase will return true if given C::f as the method 1479/// and { A } as the set of bases. 1480static bool 1481OverridesIndirectMethodInBases(const CXXMethodDecl *MD, 1482 VTableBuilder::PrimaryBasesSetVectorTy &Bases) { 1483 if (Bases.count(MD->getParent())) 1484 return true; 1485 1486 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1487 E = MD->end_overridden_methods(); I != E; ++I) { 1488 const CXXMethodDecl *OverriddenMD = *I; 1489 1490 // Check "indirect overriders". 1491 if (OverridesIndirectMethodInBases(OverriddenMD, Bases)) 1492 return true; 1493 } 1494 1495 return false; 1496} 1497 1498bool 1499VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider, 1500 uint64_t BaseOffsetInLayoutClass, 1501 const CXXRecordDecl *FirstBaseInPrimaryBaseChain, 1502 uint64_t FirstBaseOffsetInLayoutClass) const { 1503 // If the base and the first base in the primary base chain have the same 1504 // offsets, then this overrider will be used. 1505 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass) 1506 return true; 1507 1508 // We know now that Base (or a direct or indirect base of it) is a primary 1509 // base in part of the class hierarchy, but not a primary base in the most 1510 // derived class. 1511 1512 // If the overrider is the first base in the primary base chain, we know 1513 // that the overrider will be used. 1514 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain) 1515 return true; 1516 1517 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases; 1518 1519 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain; 1520 PrimaryBases.insert(RD); 1521 1522 // Now traverse the base chain, starting with the first base, until we find 1523 // the base that is no longer a primary base. 1524 while (true) { 1525 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1526 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 1527 1528 if (!PrimaryBase) 1529 break; 1530 1531 if (Layout.isPrimaryBaseVirtual()) { 1532 assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 && 1533 "Primary base should always be at offset 0!"); 1534 1535 const ASTRecordLayout &LayoutClassLayout = 1536 Context.getASTRecordLayout(LayoutClass); 1537 1538 // Now check if this is the primary base that is not a primary base in the 1539 // most derived class. 1540 if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) != 1541 FirstBaseOffsetInLayoutClass) { 1542 // We found it, stop walking the chain. 1543 break; 1544 } 1545 } else { 1546 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 && 1547 "Primary base should always be at offset 0!"); 1548 } 1549 1550 if (!PrimaryBases.insert(PrimaryBase)) 1551 assert(false && "Found a duplicate primary base!"); 1552 1553 RD = PrimaryBase; 1554 } 1555 1556 // If the final overrider is an override of one of the primary bases, 1557 // then we know that it will be used. 1558 return OverridesIndirectMethodInBases(Overrider, PrimaryBases); 1559} 1560 1561/// FindNearestOverriddenMethod - Given a method, returns the overridden method 1562/// from the nearest base. Returns null if no method was found. 1563static const CXXMethodDecl * 1564FindNearestOverriddenMethod(const CXXMethodDecl *MD, 1565 VTableBuilder::PrimaryBasesSetVectorTy &Bases) { 1566 OverriddenMethodsSetTy OverriddenMethods; 1567 ComputeAllOverriddenMethods(MD, OverriddenMethods); 1568 1569 for (int I = Bases.size(), E = 0; I != E; --I) { 1570 const CXXRecordDecl *PrimaryBase = Bases[I - 1]; 1571 1572 // Now check the overriden methods. 1573 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(), 1574 E = OverriddenMethods.end(); I != E; ++I) { 1575 const CXXMethodDecl *OverriddenMD = *I; 1576 1577 // We found our overridden method. 1578 if (OverriddenMD->getParent() == PrimaryBase) 1579 return OverriddenMD; 1580 } 1581 } 1582 1583 return 0; 1584} 1585 1586void 1587VTableBuilder::AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass, 1588 const CXXRecordDecl *FirstBaseInPrimaryBaseChain, 1589 uint64_t FirstBaseOffsetInLayoutClass, 1590 PrimaryBasesSetVectorTy &PrimaryBases) { 1591 const CXXRecordDecl *RD = Base.getBase(); 1592 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1593 1594 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) { 1595 CharUnits PrimaryBaseOffset; 1596 uint64_t PrimaryBaseOffsetInLayoutClass; 1597 if (Layout.isPrimaryBaseVirtual()) { 1598 assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 && 1599 "Primary vbase should have a zero offset!"); 1600 1601 const ASTRecordLayout &MostDerivedClassLayout = 1602 Context.getASTRecordLayout(MostDerivedClass); 1603 1604 PrimaryBaseOffset = 1605 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase); 1606 1607 const ASTRecordLayout &LayoutClassLayout = 1608 Context.getASTRecordLayout(LayoutClass); 1609 1610 PrimaryBaseOffsetInLayoutClass = 1611 LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase); 1612 } else { 1613 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 && 1614 "Primary base should have a zero offset!"); 1615 1616 PrimaryBaseOffset = Base.getBaseOffset(); 1617 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass; 1618 } 1619 1620 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset), 1621 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, 1622 FirstBaseOffsetInLayoutClass, PrimaryBases); 1623 1624 if (!PrimaryBases.insert(PrimaryBase)) 1625 assert(false && "Found a duplicate primary base!"); 1626 } 1627 1628 // Now go through all virtual member functions and add them. 1629 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 1630 E = RD->method_end(); I != E; ++I) { 1631 const CXXMethodDecl *MD = *I; 1632 1633 if (!MD->isVirtual()) 1634 continue; 1635 1636 // Get the final overrider. 1637 FinalOverriders::OverriderInfo Overrider = 1638 Overriders.getOverrider(MD, Base.getBaseOffset()); 1639 1640 // Check if this virtual member function overrides a method in a primary 1641 // base. If this is the case, and the return type doesn't require adjustment 1642 // then we can just use the member function from the primary base. 1643 if (const CXXMethodDecl *OverriddenMD = 1644 FindNearestOverriddenMethod(MD, PrimaryBases)) { 1645 if (ComputeReturnAdjustmentBaseOffset(Context, MD, 1646 OverriddenMD).isEmpty()) { 1647 // Replace the method info of the overridden method with our own 1648 // method. 1649 assert(MethodInfoMap.count(OverriddenMD) && 1650 "Did not find the overridden method!"); 1651 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD]; 1652 1653 MethodInfo MethodInfo(Context.toBits(Base.getBaseOffset()), 1654 BaseOffsetInLayoutClass, 1655 OverriddenMethodInfo.VTableIndex); 1656 1657 assert(!MethodInfoMap.count(MD) && 1658 "Should not have method info for this method yet!"); 1659 1660 MethodInfoMap.insert(std::make_pair(MD, MethodInfo)); 1661 MethodInfoMap.erase(OverriddenMD); 1662 1663 // If the overridden method exists in a virtual base class or a direct 1664 // or indirect base class of a virtual base class, we need to emit a 1665 // thunk if we ever have a class hierarchy where the base class is not 1666 // a primary base in the complete object. 1667 if (!isBuildingConstructorVTable() && OverriddenMD != MD) { 1668 // Compute the this adjustment. 1669 ThisAdjustment ThisAdjustment = 1670 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass, 1671 Overrider); 1672 1673 if (ThisAdjustment.VCallOffsetOffset && 1674 Overrider.Method->getParent() == MostDerivedClass) { 1675 1676 // There's no return adjustment from OverriddenMD and MD, 1677 // but that doesn't mean there isn't one between MD and 1678 // the final overrider. 1679 BaseOffset ReturnAdjustmentOffset = 1680 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD); 1681 ReturnAdjustment ReturnAdjustment = 1682 ComputeReturnAdjustment(ReturnAdjustmentOffset); 1683 1684 // This is a virtual thunk for the most derived class, add it. 1685 AddThunk(Overrider.Method, 1686 ThunkInfo(ThisAdjustment, ReturnAdjustment)); 1687 } 1688 } 1689 1690 continue; 1691 } 1692 } 1693 1694 // Insert the method info for this method. 1695 MethodInfo MethodInfo(Context.toBits(Base.getBaseOffset()), 1696 BaseOffsetInLayoutClass, Components.size()); 1697 1698 assert(!MethodInfoMap.count(MD) && 1699 "Should not have method info for this method yet!"); 1700 MethodInfoMap.insert(std::make_pair(MD, MethodInfo)); 1701 1702 // Check if this overrider is going to be used. 1703 const CXXMethodDecl *OverriderMD = Overrider.Method; 1704 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass, 1705 FirstBaseInPrimaryBaseChain, 1706 FirstBaseOffsetInLayoutClass)) { 1707 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD)); 1708 continue; 1709 } 1710 1711 // Check if this overrider needs a return adjustment. 1712 // We don't want to do this for pure virtual member functions. 1713 BaseOffset ReturnAdjustmentOffset; 1714 if (!OverriderMD->isPure()) { 1715 ReturnAdjustmentOffset = 1716 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD); 1717 } 1718 1719 ReturnAdjustment ReturnAdjustment = 1720 ComputeReturnAdjustment(ReturnAdjustmentOffset); 1721 1722 AddMethod(Overrider.Method, ReturnAdjustment); 1723 } 1724} 1725 1726void VTableBuilder::LayoutVTable() { 1727 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass, 1728 CharUnits::Zero()), 1729 /*BaseIsMorallyVirtual=*/false, 1730 MostDerivedClassIsVirtual, 1731 MostDerivedClassOffset); 1732 1733 VisitedVirtualBasesSetTy VBases; 1734 1735 // Determine the primary virtual bases. 1736 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset, 1737 VBases); 1738 VBases.clear(); 1739 1740 LayoutVTablesForVirtualBases(MostDerivedClass, VBases); 1741} 1742 1743void 1744VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base, 1745 bool BaseIsMorallyVirtual, 1746 bool BaseIsVirtualInLayoutClass, 1747 uint64_t OffsetInLayoutClass) { 1748 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!"); 1749 1750 // Add vcall and vbase offsets for this vtable. 1751 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders, 1752 Base, BaseIsVirtualInLayoutClass, 1753 OffsetInLayoutClass); 1754 Components.append(Builder.components_begin(), Builder.components_end()); 1755 1756 // Check if we need to add these vcall offsets. 1757 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) { 1758 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()]; 1759 1760 if (VCallOffsets.empty()) 1761 VCallOffsets = Builder.getVCallOffsets(); 1762 } 1763 1764 // If we're laying out the most derived class we want to keep track of the 1765 // virtual base class offset offsets. 1766 if (Base.getBase() == MostDerivedClass) 1767 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets(); 1768 1769 // Add the offset to top. 1770 // FIXME: We should not use / 8 here. 1771 int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass - 1772 MostDerivedClassOffset) / 8; 1773 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop)); 1774 1775 // Next, add the RTTI. 1776 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass)); 1777 1778 uint64_t AddressPoint = Components.size(); 1779 1780 // Now go through all virtual member functions and add them. 1781 PrimaryBasesSetVectorTy PrimaryBases; 1782 AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass, 1783 PrimaryBases); 1784 1785 // Compute 'this' pointer adjustments. 1786 ComputeThisAdjustments(); 1787 1788 // Add all address points. 1789 const CXXRecordDecl *RD = Base.getBase(); 1790 while (true) { 1791 AddressPoints.insert(std::make_pair( 1792 BaseSubobject(RD, Context.toCharUnitsFromBits(OffsetInLayoutClass)), 1793 AddressPoint)); 1794 1795 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1796 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 1797 1798 if (!PrimaryBase) 1799 break; 1800 1801 if (Layout.isPrimaryBaseVirtual()) { 1802 // Check if this virtual primary base is a primary base in the layout 1803 // class. If it's not, we don't want to add it. 1804 const ASTRecordLayout &LayoutClassLayout = 1805 Context.getASTRecordLayout(LayoutClass); 1806 1807 if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) != 1808 OffsetInLayoutClass) { 1809 // We don't want to add this class (or any of its primary bases). 1810 break; 1811 } 1812 } 1813 1814 RD = PrimaryBase; 1815 } 1816 1817 // Layout secondary vtables. 1818 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass); 1819} 1820 1821void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base, 1822 bool BaseIsMorallyVirtual, 1823 uint64_t OffsetInLayoutClass) { 1824 // Itanium C++ ABI 2.5.2: 1825 // Following the primary virtual table of a derived class are secondary 1826 // virtual tables for each of its proper base classes, except any primary 1827 // base(s) with which it shares its primary virtual table. 1828 1829 const CXXRecordDecl *RD = Base.getBase(); 1830 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1831 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 1832 1833 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1834 E = RD->bases_end(); I != E; ++I) { 1835 // Ignore virtual bases, we'll emit them later. 1836 if (I->isVirtual()) 1837 continue; 1838 1839 const CXXRecordDecl *BaseDecl = 1840 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1841 1842 // Ignore bases that don't have a vtable. 1843 if (!BaseDecl->isDynamicClass()) 1844 continue; 1845 1846 if (isBuildingConstructorVTable()) { 1847 // Itanium C++ ABI 2.6.4: 1848 // Some of the base class subobjects may not need construction virtual 1849 // tables, which will therefore not be present in the construction 1850 // virtual table group, even though the subobject virtual tables are 1851 // present in the main virtual table group for the complete object. 1852 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases()) 1853 continue; 1854 } 1855 1856 // Get the base offset of this base. 1857 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl); 1858 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset; 1859 1860 CharUnits BaseOffsetInLayoutClass = 1861 Context.toCharUnitsFromBits(OffsetInLayoutClass) + RelativeBaseOffset; 1862 1863 // Don't emit a secondary vtable for a primary base. We might however want 1864 // to emit secondary vtables for other bases of this base. 1865 if (BaseDecl == PrimaryBase) { 1866 LayoutSecondaryVTables( 1867 BaseSubobject(BaseDecl, BaseOffset), 1868 BaseIsMorallyVirtual, Context.toBits(BaseOffsetInLayoutClass)); 1869 continue; 1870 } 1871 1872 // Layout the primary vtable (and any secondary vtables) for this base. 1873 LayoutPrimaryAndSecondaryVTables( 1874 BaseSubobject(BaseDecl, BaseOffset), 1875 BaseIsMorallyVirtual, 1876 /*BaseIsVirtualInLayoutClass=*/false, 1877 Context.toBits(BaseOffsetInLayoutClass)); 1878 } 1879} 1880 1881void 1882VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, 1883 uint64_t OffsetInLayoutClass, 1884 VisitedVirtualBasesSetTy &VBases) { 1885 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1886 1887 // Check if this base has a primary base. 1888 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) { 1889 1890 // Check if it's virtual. 1891 if (Layout.isPrimaryBaseVirtual()) { 1892 bool IsPrimaryVirtualBase = true; 1893 1894 if (isBuildingConstructorVTable()) { 1895 // Check if the base is actually a primary base in the class we use for 1896 // layout. 1897 const ASTRecordLayout &LayoutClassLayout = 1898 Context.getASTRecordLayout(LayoutClass); 1899 1900 uint64_t PrimaryBaseOffsetInLayoutClass = 1901 LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase); 1902 1903 // We know that the base is not a primary base in the layout class if 1904 // the base offsets are different. 1905 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass) 1906 IsPrimaryVirtualBase = false; 1907 } 1908 1909 if (IsPrimaryVirtualBase) 1910 PrimaryVirtualBases.insert(PrimaryBase); 1911 } 1912 } 1913 1914 // Traverse bases, looking for more primary virtual bases. 1915 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1916 E = RD->bases_end(); I != E; ++I) { 1917 const CXXRecordDecl *BaseDecl = 1918 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1919 1920 uint64_t BaseOffsetInLayoutClass; 1921 1922 if (I->isVirtual()) { 1923 if (!VBases.insert(BaseDecl)) 1924 continue; 1925 1926 const ASTRecordLayout &LayoutClassLayout = 1927 Context.getASTRecordLayout(LayoutClass); 1928 1929 BaseOffsetInLayoutClass = 1930 LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl); 1931 } else { 1932 BaseOffsetInLayoutClass = 1933 OffsetInLayoutClass + Layout.getBaseClassOffsetInBits(BaseDecl); 1934 } 1935 1936 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases); 1937 } 1938} 1939 1940void 1941VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, 1942 VisitedVirtualBasesSetTy &VBases) { 1943 // Itanium C++ ABI 2.5.2: 1944 // Then come the virtual base virtual tables, also in inheritance graph 1945 // order, and again excluding primary bases (which share virtual tables with 1946 // the classes for which they are primary). 1947 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1948 E = RD->bases_end(); I != E; ++I) { 1949 const CXXRecordDecl *BaseDecl = 1950 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1951 1952 // Check if this base needs a vtable. (If it's virtual, not a primary base 1953 // of some other class, and we haven't visited it before). 1954 if (I->isVirtual() && BaseDecl->isDynamicClass() && 1955 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) { 1956 const ASTRecordLayout &MostDerivedClassLayout = 1957 Context.getASTRecordLayout(MostDerivedClass); 1958 uint64_t BaseOffset = 1959 MostDerivedClassLayout.getVBaseClassOffsetInBits(BaseDecl); 1960 1961 const ASTRecordLayout &LayoutClassLayout = 1962 Context.getASTRecordLayout(LayoutClass); 1963 uint64_t BaseOffsetInLayoutClass = 1964 LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl); 1965 1966 LayoutPrimaryAndSecondaryVTables( 1967 BaseSubobject(BaseDecl, Context.toCharUnitsFromBits(BaseOffset)), 1968 /*BaseIsMorallyVirtual=*/true, 1969 /*BaseIsVirtualInLayoutClass=*/true, 1970 BaseOffsetInLayoutClass); 1971 } 1972 1973 // We only need to check the base for virtual base vtables if it actually 1974 // has virtual bases. 1975 if (BaseDecl->getNumVBases()) 1976 LayoutVTablesForVirtualBases(BaseDecl, VBases); 1977 } 1978} 1979 1980/// dumpLayout - Dump the vtable layout. 1981void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) { 1982 1983 if (isBuildingConstructorVTable()) { 1984 Out << "Construction vtable for ('"; 1985 Out << MostDerivedClass->getQualifiedNameAsString() << "', "; 1986 // FIXME: Don't use / 8 . 1987 Out << MostDerivedClassOffset / 8 << ") in '"; 1988 Out << LayoutClass->getQualifiedNameAsString(); 1989 } else { 1990 Out << "Vtable for '"; 1991 Out << MostDerivedClass->getQualifiedNameAsString(); 1992 } 1993 Out << "' (" << Components.size() << " entries).\n"; 1994 1995 // Iterate through the address points and insert them into a new map where 1996 // they are keyed by the index and not the base object. 1997 // Since an address point can be shared by multiple subobjects, we use an 1998 // STL multimap. 1999 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex; 2000 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(), 2001 E = AddressPoints.end(); I != E; ++I) { 2002 const BaseSubobject& Base = I->first; 2003 uint64_t Index = I->second; 2004 2005 AddressPointsByIndex.insert(std::make_pair(Index, Base)); 2006 } 2007 2008 for (unsigned I = 0, E = Components.size(); I != E; ++I) { 2009 uint64_t Index = I; 2010 2011 Out << llvm::format("%4d | ", I); 2012 2013 const VTableComponent &Component = Components[I]; 2014 2015 // Dump the component. 2016 switch (Component.getKind()) { 2017 2018 case VTableComponent::CK_VCallOffset: 2019 Out << "vcall_offset (" << Component.getVCallOffset() << ")"; 2020 break; 2021 2022 case VTableComponent::CK_VBaseOffset: 2023 Out << "vbase_offset (" << Component.getVBaseOffset() << ")"; 2024 break; 2025 2026 case VTableComponent::CK_OffsetToTop: 2027 Out << "offset_to_top (" << Component.getOffsetToTop() << ")"; 2028 break; 2029 2030 case VTableComponent::CK_RTTI: 2031 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI"; 2032 break; 2033 2034 case VTableComponent::CK_FunctionPointer: { 2035 const CXXMethodDecl *MD = Component.getFunctionDecl(); 2036 2037 std::string Str = 2038 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 2039 MD); 2040 Out << Str; 2041 if (MD->isPure()) 2042 Out << " [pure]"; 2043 2044 ThunkInfo Thunk = VTableThunks.lookup(I); 2045 if (!Thunk.isEmpty()) { 2046 // If this function pointer has a return adjustment, dump it. 2047 if (!Thunk.Return.isEmpty()) { 2048 Out << "\n [return adjustment: "; 2049 Out << Thunk.Return.NonVirtual << " non-virtual"; 2050 2051 if (Thunk.Return.VBaseOffsetOffset) { 2052 Out << ", " << Thunk.Return.VBaseOffsetOffset; 2053 Out << " vbase offset offset"; 2054 } 2055 2056 Out << ']'; 2057 } 2058 2059 // If this function pointer has a 'this' pointer adjustment, dump it. 2060 if (!Thunk.This.isEmpty()) { 2061 Out << "\n [this adjustment: "; 2062 Out << Thunk.This.NonVirtual << " non-virtual"; 2063 2064 if (Thunk.This.VCallOffsetOffset) { 2065 Out << ", " << Thunk.This.VCallOffsetOffset; 2066 Out << " vcall offset offset"; 2067 } 2068 2069 Out << ']'; 2070 } 2071 } 2072 2073 break; 2074 } 2075 2076 case VTableComponent::CK_CompleteDtorPointer: 2077 case VTableComponent::CK_DeletingDtorPointer: { 2078 bool IsComplete = 2079 Component.getKind() == VTableComponent::CK_CompleteDtorPointer; 2080 2081 const CXXDestructorDecl *DD = Component.getDestructorDecl(); 2082 2083 Out << DD->getQualifiedNameAsString(); 2084 if (IsComplete) 2085 Out << "() [complete]"; 2086 else 2087 Out << "() [deleting]"; 2088 2089 if (DD->isPure()) 2090 Out << " [pure]"; 2091 2092 ThunkInfo Thunk = VTableThunks.lookup(I); 2093 if (!Thunk.isEmpty()) { 2094 // If this destructor has a 'this' pointer adjustment, dump it. 2095 if (!Thunk.This.isEmpty()) { 2096 Out << "\n [this adjustment: "; 2097 Out << Thunk.This.NonVirtual << " non-virtual"; 2098 2099 if (Thunk.This.VCallOffsetOffset) { 2100 Out << ", " << Thunk.This.VCallOffsetOffset; 2101 Out << " vcall offset offset"; 2102 } 2103 2104 Out << ']'; 2105 } 2106 } 2107 2108 break; 2109 } 2110 2111 case VTableComponent::CK_UnusedFunctionPointer: { 2112 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl(); 2113 2114 std::string Str = 2115 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 2116 MD); 2117 Out << "[unused] " << Str; 2118 if (MD->isPure()) 2119 Out << " [pure]"; 2120 } 2121 2122 } 2123 2124 Out << '\n'; 2125 2126 // Dump the next address point. 2127 uint64_t NextIndex = Index + 1; 2128 if (AddressPointsByIndex.count(NextIndex)) { 2129 if (AddressPointsByIndex.count(NextIndex) == 1) { 2130 const BaseSubobject &Base = 2131 AddressPointsByIndex.find(NextIndex)->second; 2132 2133 // FIXME: Instead of dividing by 8, we should be using CharUnits. 2134 Out << " -- (" << Base.getBase()->getQualifiedNameAsString(); 2135 Out << ", " << Base.getBaseOffset().getQuantity(); 2136 Out << ") vtable address --\n"; 2137 } else { 2138 CharUnits BaseOffset = 2139 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset(); 2140 2141 // We store the class names in a set to get a stable order. 2142 std::set<std::string> ClassNames; 2143 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I = 2144 AddressPointsByIndex.lower_bound(NextIndex), E = 2145 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) { 2146 assert(I->second.getBaseOffset() == BaseOffset && 2147 "Invalid base offset!"); 2148 const CXXRecordDecl *RD = I->second.getBase(); 2149 ClassNames.insert(RD->getQualifiedNameAsString()); 2150 } 2151 2152 for (std::set<std::string>::const_iterator I = ClassNames.begin(), 2153 E = ClassNames.end(); I != E; ++I) { 2154 Out << " -- (" << *I; 2155 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n"; 2156 } 2157 } 2158 } 2159 } 2160 2161 Out << '\n'; 2162 2163 if (isBuildingConstructorVTable()) 2164 return; 2165 2166 if (MostDerivedClass->getNumVBases()) { 2167 // We store the virtual base class names and their offsets in a map to get 2168 // a stable order. 2169 2170 std::map<std::string, int64_t> ClassNamesAndOffsets; 2171 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(), 2172 E = VBaseOffsetOffsets.end(); I != E; ++I) { 2173 std::string ClassName = I->first->getQualifiedNameAsString(); 2174 int64_t OffsetOffset = I->second; 2175 ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset)); 2176 } 2177 2178 Out << "Virtual base offset offsets for '"; 2179 Out << MostDerivedClass->getQualifiedNameAsString() << "' ("; 2180 Out << ClassNamesAndOffsets.size(); 2181 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n"; 2182 2183 for (std::map<std::string, int64_t>::const_iterator I = 2184 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end(); 2185 I != E; ++I) 2186 Out << " " << I->first << " | " << I->second << '\n'; 2187 2188 Out << "\n"; 2189 } 2190 2191 if (!Thunks.empty()) { 2192 // We store the method names in a map to get a stable order. 2193 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls; 2194 2195 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end(); 2196 I != E; ++I) { 2197 const CXXMethodDecl *MD = I->first; 2198 std::string MethodName = 2199 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 2200 MD); 2201 2202 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD)); 2203 } 2204 2205 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I = 2206 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end(); 2207 I != E; ++I) { 2208 const std::string &MethodName = I->first; 2209 const CXXMethodDecl *MD = I->second; 2210 2211 ThunkInfoVectorTy ThunksVector = Thunks[MD]; 2212 std::sort(ThunksVector.begin(), ThunksVector.end()); 2213 2214 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size(); 2215 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n"; 2216 2217 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) { 2218 const ThunkInfo &Thunk = ThunksVector[I]; 2219 2220 Out << llvm::format("%4d | ", I); 2221 2222 // If this function pointer has a return pointer adjustment, dump it. 2223 if (!Thunk.Return.isEmpty()) { 2224 Out << "return adjustment: " << Thunk.This.NonVirtual; 2225 Out << " non-virtual"; 2226 if (Thunk.Return.VBaseOffsetOffset) { 2227 Out << ", " << Thunk.Return.VBaseOffsetOffset; 2228 Out << " vbase offset offset"; 2229 } 2230 2231 if (!Thunk.This.isEmpty()) 2232 Out << "\n "; 2233 } 2234 2235 // If this function pointer has a 'this' pointer adjustment, dump it. 2236 if (!Thunk.This.isEmpty()) { 2237 Out << "this adjustment: "; 2238 Out << Thunk.This.NonVirtual << " non-virtual"; 2239 2240 if (Thunk.This.VCallOffsetOffset) { 2241 Out << ", " << Thunk.This.VCallOffsetOffset; 2242 Out << " vcall offset offset"; 2243 } 2244 } 2245 2246 Out << '\n'; 2247 } 2248 2249 Out << '\n'; 2250 2251 } 2252 } 2253} 2254 2255} 2256 2257static void 2258CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, 2259 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) { 2260 while (RD) { 2261 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 2262 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 2263 if (PrimaryBase) 2264 PrimaryBases.insert(PrimaryBase); 2265 2266 RD = PrimaryBase; 2267 } 2268} 2269 2270void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) { 2271 2272 // Itanium C++ ABI 2.5.2: 2273 // The order of the virtual function pointers in a virtual table is the 2274 // order of declaration of the corresponding member functions in the class. 2275 // 2276 // There is an entry for any virtual function declared in a class, 2277 // whether it is a new function or overrides a base class function, 2278 // unless it overrides a function from the primary base, and conversion 2279 // between their return types does not require an adjustment. 2280 2281 int64_t CurrentIndex = 0; 2282 2283 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 2284 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 2285 2286 if (PrimaryBase) { 2287 assert(PrimaryBase->isDefinition() && 2288 "Should have the definition decl of the primary base!"); 2289 2290 // Since the record decl shares its vtable pointer with the primary base 2291 // we need to start counting at the end of the primary base's vtable. 2292 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase); 2293 } 2294 2295 // Collect all the primary bases, so we can check whether methods override 2296 // a method from the base. 2297 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases; 2298 CollectPrimaryBases(RD, CGM.getContext(), PrimaryBases); 2299 2300 const CXXDestructorDecl *ImplicitVirtualDtor = 0; 2301 2302 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 2303 e = RD->method_end(); i != e; ++i) { 2304 const CXXMethodDecl *MD = *i; 2305 2306 // We only want virtual methods. 2307 if (!MD->isVirtual()) 2308 continue; 2309 2310 // Check if this method overrides a method in the primary base. 2311 if (const CXXMethodDecl *OverriddenMD = 2312 FindNearestOverriddenMethod(MD, PrimaryBases)) { 2313 // Check if converting from the return type of the method to the 2314 // return type of the overridden method requires conversion. 2315 if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD, 2316 OverriddenMD).isEmpty()) { 2317 // This index is shared between the index in the vtable of the primary 2318 // base class. 2319 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 2320 const CXXDestructorDecl *OverriddenDD = 2321 cast<CXXDestructorDecl>(OverriddenMD); 2322 2323 // Add both the complete and deleting entries. 2324 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = 2325 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete)); 2326 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = 2327 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting)); 2328 } else { 2329 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD); 2330 } 2331 2332 // We don't need to add an entry for this method. 2333 continue; 2334 } 2335 } 2336 2337 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 2338 if (MD->isImplicit()) { 2339 assert(!ImplicitVirtualDtor && 2340 "Did already see an implicit virtual dtor!"); 2341 ImplicitVirtualDtor = DD; 2342 continue; 2343 } 2344 2345 // Add the complete dtor. 2346 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++; 2347 2348 // Add the deleting dtor. 2349 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++; 2350 } else { 2351 // Add the entry. 2352 MethodVTableIndices[MD] = CurrentIndex++; 2353 } 2354 } 2355 2356 if (ImplicitVirtualDtor) { 2357 // Itanium C++ ABI 2.5.2: 2358 // If a class has an implicitly-defined virtual destructor, 2359 // its entries come after the declared virtual function pointers. 2360 2361 // Add the complete dtor. 2362 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] = 2363 CurrentIndex++; 2364 2365 // Add the deleting dtor. 2366 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] = 2367 CurrentIndex++; 2368 } 2369 2370 NumVirtualFunctionPointers[RD] = CurrentIndex; 2371} 2372 2373bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) { 2374 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable."); 2375 2376 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind(); 2377 if (TSK == TSK_ExplicitInstantiationDeclaration) 2378 return false; 2379 2380 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD); 2381 if (!KeyFunction) 2382 return true; 2383 2384 // Itanium C++ ABI, 5.2.6 Instantiated Templates: 2385 // An instantiation of a class template requires: 2386 // - In the object where instantiated, the virtual table... 2387 if (TSK == TSK_ImplicitInstantiation || 2388 TSK == TSK_ExplicitInstantiationDefinition) 2389 return true; 2390 2391 // If we're building with optimization, we always emit VTables since that 2392 // allows for virtual function calls to be devirtualized. 2393 // (We don't want to do this in -fapple-kext mode however). 2394 if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext) 2395 return true; 2396 2397 return KeyFunction->hasBody(); 2398} 2399 2400uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) { 2401 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I = 2402 NumVirtualFunctionPointers.find(RD); 2403 if (I != NumVirtualFunctionPointers.end()) 2404 return I->second; 2405 2406 ComputeMethodVTableIndices(RD); 2407 2408 I = NumVirtualFunctionPointers.find(RD); 2409 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!"); 2410 return I->second; 2411} 2412 2413uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) { 2414 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD); 2415 if (I != MethodVTableIndices.end()) 2416 return I->second; 2417 2418 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 2419 2420 ComputeMethodVTableIndices(RD); 2421 2422 I = MethodVTableIndices.find(GD); 2423 assert(I != MethodVTableIndices.end() && "Did not find index!"); 2424 return I->second; 2425} 2426 2427int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, 2428 const CXXRecordDecl *VBase) { 2429 ClassPairTy ClassPair(RD, VBase); 2430 2431 VirtualBaseClassOffsetOffsetsMapTy::iterator I = 2432 VirtualBaseClassOffsetOffsets.find(ClassPair); 2433 if (I != VirtualBaseClassOffsetOffsets.end()) 2434 return I->second; 2435 2436 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0, 2437 BaseSubobject(RD, CharUnits::Zero()), 2438 /*BaseIsVirtual=*/false, 2439 /*OffsetInLayoutClass=*/0); 2440 2441 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I = 2442 Builder.getVBaseOffsetOffsets().begin(), 2443 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) { 2444 // Insert all types. 2445 ClassPairTy ClassPair(RD, I->first); 2446 2447 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second)); 2448 } 2449 2450 I = VirtualBaseClassOffsetOffsets.find(ClassPair); 2451 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!"); 2452 2453 return I->second; 2454} 2455 2456uint64_t 2457CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) { 2458 assert(AddressPoints.count(std::make_pair(RD, Base)) && 2459 "Did not find address point!"); 2460 2461 uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base)); 2462 assert(AddressPoint && "Address point must not be zero!"); 2463 2464 return AddressPoint; 2465} 2466 2467llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD, 2468 const ThunkInfo &Thunk) { 2469 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2470 2471 // Compute the mangled name. 2472 llvm::SmallString<256> Name; 2473 llvm::raw_svector_ostream Out(Name); 2474 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD)) 2475 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), 2476 Thunk.This, Out); 2477 else 2478 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out); 2479 Out.flush(); 2480 2481 const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD); 2482 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true); 2483} 2484 2485static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF, 2486 llvm::Value *Ptr, 2487 int64_t NonVirtualAdjustment, 2488 int64_t VirtualAdjustment) { 2489 if (!NonVirtualAdjustment && !VirtualAdjustment) 2490 return Ptr; 2491 2492 const llvm::Type *Int8PtrTy = 2493 llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); 2494 2495 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy); 2496 2497 if (NonVirtualAdjustment) { 2498 // Do the non-virtual adjustment. 2499 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 2500 } 2501 2502 if (VirtualAdjustment) { 2503 const llvm::Type *PtrDiffTy = 2504 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 2505 2506 // Do the virtual adjustment. 2507 llvm::Value *VTablePtrPtr = 2508 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo()); 2509 2510 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 2511 2512 llvm::Value *OffsetPtr = 2513 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 2514 2515 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 2516 2517 // Load the adjustment offset from the vtable. 2518 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr); 2519 2520 // Adjust our pointer. 2521 V = CGF.Builder.CreateInBoundsGEP(V, Offset); 2522 } 2523 2524 // Cast back to the original type. 2525 return CGF.Builder.CreateBitCast(V, Ptr->getType()); 2526} 2527 2528static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD, 2529 const ThunkInfo &Thunk, llvm::Function *Fn) { 2530 CGM.setGlobalVisibility(Fn, MD); 2531 2532 if (!CGM.getCodeGenOpts().HiddenWeakVTables) 2533 return; 2534 2535 // If the thunk has weak/linkonce linkage, but the function must be 2536 // emitted in every translation unit that references it, then we can 2537 // emit its thunks with hidden visibility, since its thunks must be 2538 // emitted when the function is. 2539 2540 // This follows CodeGenModule::setTypeVisibility; see the comments 2541 // there for explanation. 2542 2543 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage && 2544 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) || 2545 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 2546 return; 2547 2548 if (MD->hasAttr<VisibilityAttr>()) 2549 return; 2550 2551 switch (MD->getTemplateSpecializationKind()) { 2552 case TSK_ExplicitInstantiationDefinition: 2553 case TSK_ExplicitInstantiationDeclaration: 2554 return; 2555 2556 case TSK_Undeclared: 2557 break; 2558 2559 case TSK_ExplicitSpecialization: 2560 case TSK_ImplicitInstantiation: 2561 if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables) 2562 return; 2563 break; 2564 } 2565 2566 // If there's an explicit definition, and that definition is 2567 // out-of-line, then we can't assume that all users will have a 2568 // definition to emit. 2569 const FunctionDecl *Def = 0; 2570 if (MD->hasBody(Def) && Def->isOutOfLine()) 2571 return; 2572 2573 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility); 2574} 2575 2576#ifndef NDEBUG 2577static bool similar(const ABIArgInfo &infoL, CanQualType typeL, 2578 const ABIArgInfo &infoR, CanQualType typeR) { 2579 return (infoL.getKind() == infoR.getKind() && 2580 (typeL == typeR || 2581 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) || 2582 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR)))); 2583} 2584#endif 2585 2586void CodeGenFunction::GenerateThunk(llvm::Function *Fn, 2587 const CGFunctionInfo &FnInfo, 2588 GlobalDecl GD, const ThunkInfo &Thunk) { 2589 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2590 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 2591 QualType ResultType = FPT->getResultType(); 2592 QualType ThisType = MD->getThisType(getContext()); 2593 2594 FunctionArgList FunctionArgs; 2595 2596 // FIXME: It would be nice if more of this code could be shared with 2597 // CodeGenFunction::GenerateCode. 2598 2599 // Create the implicit 'this' parameter declaration. 2600 CurGD = GD; 2601 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs); 2602 2603 // Add the rest of the parameters. 2604 for (FunctionDecl::param_const_iterator I = MD->param_begin(), 2605 E = MD->param_end(); I != E; ++I) { 2606 ParmVarDecl *Param = *I; 2607 2608 FunctionArgs.push_back(Param); 2609 } 2610 2611 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs, 2612 SourceLocation()); 2613 2614 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 2615 2616 // Adjust the 'this' pointer if necessary. 2617 llvm::Value *AdjustedThisPtr = 2618 PerformTypeAdjustment(*this, LoadCXXThis(), 2619 Thunk.This.NonVirtual, 2620 Thunk.This.VCallOffsetOffset); 2621 2622 CallArgList CallArgs; 2623 2624 // Add our adjusted 'this' pointer. 2625 CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType)); 2626 2627 // Add the rest of the parameters. 2628 for (FunctionDecl::param_const_iterator I = MD->param_begin(), 2629 E = MD->param_end(); I != E; ++I) { 2630 ParmVarDecl *param = *I; 2631 EmitDelegateCallArg(CallArgs, param); 2632 } 2633 2634 // Get our callee. 2635 const llvm::Type *Ty = 2636 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD), 2637 FPT->isVariadic()); 2638 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 2639 2640#ifndef NDEBUG 2641 const CGFunctionInfo &CallFnInfo = 2642 CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo()); 2643 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() && 2644 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() && 2645 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention()); 2646 assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(), 2647 FnInfo.getReturnInfo(), FnInfo.getReturnType())); 2648 assert(CallFnInfo.arg_size() == FnInfo.arg_size()); 2649 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i) 2650 assert(similar(CallFnInfo.arg_begin()[i].info, 2651 CallFnInfo.arg_begin()[i].type, 2652 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type)); 2653#endif 2654 2655 // Determine whether we have a return value slot to use. 2656 ReturnValueSlot Slot; 2657 if (!ResultType->isVoidType() && 2658 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect && 2659 hasAggregateLLVMType(CurFnInfo->getReturnType())) 2660 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified()); 2661 2662 // Now emit our call. 2663 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD); 2664 2665 if (!Thunk.Return.isEmpty()) { 2666 // Emit the return adjustment. 2667 bool NullCheckValue = !ResultType->isReferenceType(); 2668 2669 llvm::BasicBlock *AdjustNull = 0; 2670 llvm::BasicBlock *AdjustNotNull = 0; 2671 llvm::BasicBlock *AdjustEnd = 0; 2672 2673 llvm::Value *ReturnValue = RV.getScalarVal(); 2674 2675 if (NullCheckValue) { 2676 AdjustNull = createBasicBlock("adjust.null"); 2677 AdjustNotNull = createBasicBlock("adjust.notnull"); 2678 AdjustEnd = createBasicBlock("adjust.end"); 2679 2680 llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue); 2681 Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull); 2682 EmitBlock(AdjustNotNull); 2683 } 2684 2685 ReturnValue = PerformTypeAdjustment(*this, ReturnValue, 2686 Thunk.Return.NonVirtual, 2687 Thunk.Return.VBaseOffsetOffset); 2688 2689 if (NullCheckValue) { 2690 Builder.CreateBr(AdjustEnd); 2691 EmitBlock(AdjustNull); 2692 Builder.CreateBr(AdjustEnd); 2693 EmitBlock(AdjustEnd); 2694 2695 llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType()); 2696 PHI->reserveOperandSpace(2); 2697 PHI->addIncoming(ReturnValue, AdjustNotNull); 2698 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()), 2699 AdjustNull); 2700 ReturnValue = PHI; 2701 } 2702 2703 RV = RValue::get(ReturnValue); 2704 } 2705 2706 if (!ResultType->isVoidType() && Slot.isNull()) 2707 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType); 2708 2709 FinishFunction(); 2710 2711 // Set the right linkage. 2712 CGM.setFunctionLinkage(MD, Fn); 2713 2714 // Set the right visibility. 2715 setThunkVisibility(CGM, MD, Thunk, Fn); 2716} 2717 2718void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk, 2719 bool UseAvailableExternallyLinkage) 2720{ 2721 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD); 2722 2723 // FIXME: re-use FnInfo in this computation. 2724 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk); 2725 2726 // Strip off a bitcast if we got one back. 2727 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2728 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2729 Entry = CE->getOperand(0); 2730 } 2731 2732 // There's already a declaration with the same name, check if it has the same 2733 // type or if we need to replace it. 2734 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != 2735 CGM.getTypes().GetFunctionTypeForVTable(GD)) { 2736 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry); 2737 2738 // If the types mismatch then we have to rewrite the definition. 2739 assert(OldThunkFn->isDeclaration() && 2740 "Shouldn't replace non-declaration"); 2741 2742 // Remove the name from the old thunk function and get a new thunk. 2743 OldThunkFn->setName(llvm::StringRef()); 2744 Entry = CGM.GetAddrOfThunk(GD, Thunk); 2745 2746 // If needed, replace the old thunk with a bitcast. 2747 if (!OldThunkFn->use_empty()) { 2748 llvm::Constant *NewPtrForOldDecl = 2749 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType()); 2750 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl); 2751 } 2752 2753 // Remove the old thunk. 2754 OldThunkFn->eraseFromParent(); 2755 } 2756 2757 llvm::Function *ThunkFn = cast<llvm::Function>(Entry); 2758 2759 if (!ThunkFn->isDeclaration()) { 2760 if (UseAvailableExternallyLinkage) { 2761 // There is already a thunk emitted for this function, do nothing. 2762 return; 2763 } 2764 2765 // If a function has a body, it should have available_externally linkage. 2766 assert(ThunkFn->hasAvailableExternallyLinkage() && 2767 "Function should have available_externally linkage!"); 2768 2769 // Change the linkage. 2770 CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn); 2771 return; 2772 } 2773 2774 // Actually generate the thunk body. 2775 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk); 2776 2777 if (UseAvailableExternallyLinkage) 2778 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 2779} 2780 2781void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD, 2782 const ThunkInfo &Thunk) { 2783 // We only want to do this when building with optimizations. 2784 if (!CGM.getCodeGenOpts().OptimizationLevel) 2785 return; 2786 2787 // We can't emit thunks for member functions with incomplete types. 2788 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2789 if (CGM.getTypes().VerifyFuncTypeComplete(MD->getType().getTypePtr())) 2790 return; 2791 2792 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true); 2793} 2794 2795void CodeGenVTables::EmitThunks(GlobalDecl GD) 2796{ 2797 const CXXMethodDecl *MD = 2798 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl(); 2799 2800 // We don't need to generate thunks for the base destructor. 2801 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 2802 return; 2803 2804 const CXXRecordDecl *RD = MD->getParent(); 2805 2806 // Compute VTable related info for this class. 2807 ComputeVTableRelatedInformation(RD, false); 2808 2809 ThunksMapTy::const_iterator I = Thunks.find(MD); 2810 if (I == Thunks.end()) { 2811 // We did not find a thunk for this method. 2812 return; 2813 } 2814 2815 const ThunkInfoVectorTy &ThunkInfoVector = I->second; 2816 for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I) 2817 EmitThunk(GD, ThunkInfoVector[I], /*UseAvailableExternallyLinkage=*/false); 2818} 2819 2820void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD, 2821 bool RequireVTable) { 2822 VTableLayoutData &Entry = VTableLayoutMap[RD]; 2823 2824 // We may need to generate a definition for this vtable. 2825 if (RequireVTable && !Entry.getInt()) { 2826 if (ShouldEmitVTableInThisTU(RD)) 2827 CGM.DeferredVTables.push_back(RD); 2828 2829 Entry.setInt(true); 2830 } 2831 2832 // Check if we've computed this information before. 2833 if (Entry.getPointer()) 2834 return; 2835 2836 VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD); 2837 2838 // Add the VTable layout. 2839 uint64_t NumVTableComponents = Builder.getNumVTableComponents(); 2840 // -fapple-kext adds an extra entry at end of vtbl. 2841 bool IsAppleKext = CGM.getContext().getLangOptions().AppleKext; 2842 if (IsAppleKext) 2843 NumVTableComponents += 1; 2844 2845 uint64_t *LayoutData = new uint64_t[NumVTableComponents + 1]; 2846 if (IsAppleKext) 2847 LayoutData[NumVTableComponents] = 0; 2848 Entry.setPointer(LayoutData); 2849 2850 // Store the number of components. 2851 LayoutData[0] = NumVTableComponents; 2852 2853 // Store the components. 2854 std::copy(Builder.vtable_components_data_begin(), 2855 Builder.vtable_components_data_end(), 2856 &LayoutData[1]); 2857 2858 // Add the known thunks. 2859 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end()); 2860 2861 // Add the thunks needed in this vtable. 2862 assert(!VTableThunksMap.count(RD) && 2863 "Thunks already exists for this vtable!"); 2864 2865 VTableThunksTy &VTableThunks = VTableThunksMap[RD]; 2866 VTableThunks.append(Builder.vtable_thunks_begin(), 2867 Builder.vtable_thunks_end()); 2868 2869 // Sort them. 2870 std::sort(VTableThunks.begin(), VTableThunks.end()); 2871 2872 // Add the address points. 2873 for (VTableBuilder::AddressPointsMapTy::const_iterator I = 2874 Builder.address_points_begin(), E = Builder.address_points_end(); 2875 I != E; ++I) { 2876 2877 uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)]; 2878 2879 // Check if we already have the address points for this base. 2880 assert(!AddressPoint && "Address point already exists for this base!"); 2881 2882 AddressPoint = I->second; 2883 } 2884 2885 // If we don't have the vbase information for this class, insert it. 2886 // getVirtualBaseOffsetOffset will compute it separately without computing 2887 // the rest of the vtable related information. 2888 if (!RD->getNumVBases()) 2889 return; 2890 2891 const RecordType *VBaseRT = 2892 RD->vbases_begin()->getType()->getAs<RecordType>(); 2893 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl()); 2894 2895 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase))) 2896 return; 2897 2898 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I = 2899 Builder.getVBaseOffsetOffsets().begin(), 2900 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) { 2901 // Insert all types. 2902 ClassPairTy ClassPair(RD, I->first); 2903 2904 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second)); 2905 } 2906} 2907 2908llvm::Constant * 2909CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD, 2910 const uint64_t *Components, 2911 unsigned NumComponents, 2912 const VTableThunksTy &VTableThunks) { 2913 llvm::SmallVector<llvm::Constant *, 64> Inits; 2914 2915 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext()); 2916 2917 const llvm::Type *PtrDiffTy = 2918 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 2919 2920 QualType ClassType = CGM.getContext().getTagDeclType(RD); 2921 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType); 2922 2923 unsigned NextVTableThunkIndex = 0; 2924 2925 llvm::Constant* PureVirtualFn = 0; 2926 2927 for (unsigned I = 0; I != NumComponents; ++I) { 2928 VTableComponent Component = 2929 VTableComponent::getFromOpaqueInteger(Components[I]); 2930 2931 llvm::Constant *Init = 0; 2932 2933 switch (Component.getKind()) { 2934 case VTableComponent::CK_VCallOffset: 2935 Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset()); 2936 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy); 2937 break; 2938 case VTableComponent::CK_VBaseOffset: 2939 Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset()); 2940 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy); 2941 break; 2942 case VTableComponent::CK_OffsetToTop: 2943 Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop()); 2944 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy); 2945 break; 2946 case VTableComponent::CK_RTTI: 2947 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy); 2948 break; 2949 case VTableComponent::CK_FunctionPointer: 2950 case VTableComponent::CK_CompleteDtorPointer: 2951 case VTableComponent::CK_DeletingDtorPointer: { 2952 GlobalDecl GD; 2953 2954 // Get the right global decl. 2955 switch (Component.getKind()) { 2956 default: 2957 llvm_unreachable("Unexpected vtable component kind"); 2958 case VTableComponent::CK_FunctionPointer: 2959 GD = Component.getFunctionDecl(); 2960 break; 2961 case VTableComponent::CK_CompleteDtorPointer: 2962 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete); 2963 break; 2964 case VTableComponent::CK_DeletingDtorPointer: 2965 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting); 2966 break; 2967 } 2968 2969 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) { 2970 // We have a pure virtual member function. 2971 if (!PureVirtualFn) { 2972 const llvm::FunctionType *Ty = 2973 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2974 /*isVarArg=*/false); 2975 PureVirtualFn = 2976 CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"); 2977 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn, 2978 Int8PtrTy); 2979 } 2980 2981 Init = PureVirtualFn; 2982 } else { 2983 // Check if we should use a thunk. 2984 if (NextVTableThunkIndex < VTableThunks.size() && 2985 VTableThunks[NextVTableThunkIndex].first == I) { 2986 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second; 2987 2988 Init = CGM.GetAddrOfThunk(GD, Thunk); 2989 MaybeEmitThunkAvailableExternally(GD, Thunk); 2990 2991 NextVTableThunkIndex++; 2992 } else { 2993 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD); 2994 2995 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 2996 } 2997 2998 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy); 2999 } 3000 break; 3001 } 3002 3003 case VTableComponent::CK_UnusedFunctionPointer: 3004 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy); 3005 break; 3006 }; 3007 3008 Inits.push_back(Init); 3009 } 3010 3011 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents); 3012 return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size()); 3013} 3014 3015llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) { 3016 llvm::SmallString<256> OutName; 3017 llvm::raw_svector_ostream Out(OutName); 3018 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out); 3019 Out.flush(); 3020 llvm::StringRef Name = OutName.str(); 3021 3022 ComputeVTableRelatedInformation(RD, true); 3023 3024 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext()); 3025 llvm::ArrayType *ArrayType = 3026 llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD)); 3027 3028 llvm::GlobalVariable *GV = 3029 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, 3030 llvm::GlobalValue::ExternalLinkage); 3031 GV->setUnnamedAddr(true); 3032 return GV; 3033} 3034 3035void 3036CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable, 3037 llvm::GlobalVariable::LinkageTypes Linkage, 3038 const CXXRecordDecl *RD) { 3039 // Dump the vtable layout if necessary. 3040 if (CGM.getLangOptions().DumpVTableLayouts) { 3041 VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD); 3042 3043 Builder.dumpLayout(llvm::errs()); 3044 } 3045 3046 assert(VTableThunksMap.count(RD) && 3047 "No thunk status for this record decl!"); 3048 3049 const VTableThunksTy& Thunks = VTableThunksMap[RD]; 3050 3051 // Create and set the initializer. 3052 llvm::Constant *Init = 3053 CreateVTableInitializer(RD, getVTableComponentsData(RD), 3054 getNumVTableComponents(RD), Thunks); 3055 VTable->setInitializer(Init); 3056 3057 // Set the correct linkage. 3058 VTable->setLinkage(Linkage); 3059 3060 // Set the right visibility. 3061 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable); 3062} 3063 3064llvm::GlobalVariable * 3065CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD, 3066 const BaseSubobject &Base, 3067 bool BaseIsVirtual, 3068 VTableAddressPointsMapTy& AddressPoints) { 3069 VTableBuilder Builder(*this, Base.getBase(), 3070 CGM.getContext().toBits(Base.getBaseOffset()), 3071 /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD); 3072 3073 // Dump the vtable layout if necessary. 3074 if (CGM.getLangOptions().DumpVTableLayouts) 3075 Builder.dumpLayout(llvm::errs()); 3076 3077 // Add the address points. 3078 AddressPoints.insert(Builder.address_points_begin(), 3079 Builder.address_points_end()); 3080 3081 // Get the mangled construction vtable name. 3082 llvm::SmallString<256> OutName; 3083 llvm::raw_svector_ostream Out(OutName); 3084 CGM.getCXXABI().getMangleContext(). 3085 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(), 3086 Out); 3087 Out.flush(); 3088 llvm::StringRef Name = OutName.str(); 3089 3090 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext()); 3091 llvm::ArrayType *ArrayType = 3092 llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents()); 3093 3094 // Create the variable that will hold the construction vtable. 3095 llvm::GlobalVariable *VTable = 3096 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, 3097 llvm::GlobalValue::InternalLinkage); 3098 3099 // Add the thunks. 3100 VTableThunksTy VTableThunks; 3101 VTableThunks.append(Builder.vtable_thunks_begin(), 3102 Builder.vtable_thunks_end()); 3103 3104 // Sort them. 3105 std::sort(VTableThunks.begin(), VTableThunks.end()); 3106 3107 // Create and set the initializer. 3108 llvm::Constant *Init = 3109 CreateVTableInitializer(Base.getBase(), 3110 Builder.vtable_components_data_begin(), 3111 Builder.getNumVTableComponents(), VTableThunks); 3112 VTable->setInitializer(Init); 3113 3114 return VTable; 3115} 3116 3117void 3118CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage, 3119 const CXXRecordDecl *RD) { 3120 llvm::GlobalVariable *&VTable = VTables[RD]; 3121 if (VTable) { 3122 assert(VTable->getInitializer() && "VTable doesn't have a definition!"); 3123 return; 3124 } 3125 3126 VTable = GetAddrOfVTable(RD); 3127 EmitVTableDefinition(VTable, Linkage, RD); 3128 3129 if (RD->getNumVBases()) { 3130 llvm::GlobalVariable *VTT = GetAddrOfVTT(RD); 3131 EmitVTTDefinition(VTT, Linkage, RD); 3132 } 3133 3134 // If this is the magic class __cxxabiv1::__fundamental_type_info, 3135 // we will emit the typeinfo for the fundamental types. This is the 3136 // same behaviour as GCC. 3137 const DeclContext *DC = RD->getDeclContext(); 3138 if (RD->getIdentifier() && 3139 RD->getIdentifier()->isStr("__fundamental_type_info") && 3140 isa<NamespaceDecl>(DC) && 3141 cast<NamespaceDecl>(DC)->getIdentifier() && 3142 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 3143 DC->getParent()->isTranslationUnit()) 3144 CGM.EmitFundamentalRTTIDescriptors(); 3145} 3146