1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===// 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 provides C++ code generation targeting the Microsoft Visual C++ ABI. 11 // The class in this file generates structures that follow the Microsoft 12 // Visual C++ ABI, which is actually not very well documented at all outside 13 // of Microsoft. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "CGCXXABI.h" 18 #include "CGVTables.h" 19 #include "CodeGenModule.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/VTableBuilder.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/StringSet.h" 25 #include "llvm/IR/CallSite.h" 26 27 using namespace clang; 28 using namespace CodeGen; 29 30 namespace { 31 32 /// Holds all the vbtable globals for a given class. 33 struct VBTableGlobals { 34 const VPtrInfoVector *VBTables; 35 SmallVector<llvm::GlobalVariable *, 2> Globals; 36 }; 37 38 class MicrosoftCXXABI : public CGCXXABI { 39 public: 40 MicrosoftCXXABI(CodeGenModule &CGM) 41 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr), 42 ClassHierarchyDescriptorType(nullptr), 43 CompleteObjectLocatorType(nullptr) {} 44 45 bool HasThisReturn(GlobalDecl GD) const override; 46 47 bool classifyReturnType(CGFunctionInfo &FI) const override; 48 49 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override; 50 51 bool isSRetParameterAfterThis() const override { return true; } 52 53 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD, 54 FunctionArgList &Args) const override { 55 assert(Args.size() >= 2 && 56 "expected the arglist to have at least two args!"); 57 // The 'most_derived' parameter goes second if the ctor is variadic and 58 // has v-bases. 59 if (CD->getParent()->getNumVBases() > 0 && 60 CD->getType()->castAs<FunctionProtoType>()->isVariadic()) 61 return 2; 62 return 1; 63 } 64 65 StringRef GetPureVirtualCallName() override { return "_purecall"; } 66 StringRef GetDeletedVirtualCallName() override { return "_purecall"; } 67 68 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 69 llvm::Value *ptr, 70 QualType type) override; 71 72 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD, 73 const VPtrInfo *Info); 74 75 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 76 77 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 78 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 79 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 80 llvm::Value *ThisPtr, 81 llvm::Type *StdTypeInfoPtrTy) override; 82 83 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 84 QualType SrcRecordTy) override; 85 86 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value, 87 QualType SrcRecordTy, QualType DestTy, 88 QualType DestRecordTy, 89 llvm::BasicBlock *CastEnd) override; 90 91 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 92 QualType SrcRecordTy, 93 QualType DestTy) override; 94 95 bool EmitBadCastCall(CodeGenFunction &CGF) override; 96 97 llvm::Value * 98 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This, 99 const CXXRecordDecl *ClassDecl, 100 const CXXRecordDecl *BaseClassDecl) override; 101 102 llvm::BasicBlock * 103 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 104 const CXXRecordDecl *RD) override; 105 106 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, 107 const CXXRecordDecl *RD) override; 108 109 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 110 111 // Background on MSVC destructors 112 // ============================== 113 // 114 // Both Itanium and MSVC ABIs have destructor variants. The variant names 115 // roughly correspond in the following way: 116 // Itanium Microsoft 117 // Base -> no name, just ~Class 118 // Complete -> vbase destructor 119 // Deleting -> scalar deleting destructor 120 // vector deleting destructor 121 // 122 // The base and complete destructors are the same as in Itanium, although the 123 // complete destructor does not accept a VTT parameter when there are virtual 124 // bases. A separate mechanism involving vtordisps is used to ensure that 125 // virtual methods of destroyed subobjects are not called. 126 // 127 // The deleting destructors accept an i32 bitfield as a second parameter. Bit 128 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this 129 // pointer points to an array. The scalar deleting destructor assumes that 130 // bit 2 is zero, and therefore does not contain a loop. 131 // 132 // For virtual destructors, only one entry is reserved in the vftable, and it 133 // always points to the vector deleting destructor. The vector deleting 134 // destructor is the most general, so it can be used to destroy objects in 135 // place, delete single heap objects, or delete arrays. 136 // 137 // A TU defining a non-inline destructor is only guaranteed to emit a base 138 // destructor, and all of the other variants are emitted on an as-needed basis 139 // in COMDATs. Because a non-base destructor can be emitted in a TU that 140 // lacks a definition for the destructor, non-base destructors must always 141 // delegate to or alias the base destructor. 142 143 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 144 SmallVectorImpl<CanQualType> &ArgTys) override; 145 146 /// Non-base dtors should be emitted as delegating thunks in this ABI. 147 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 148 CXXDtorType DT) const override { 149 return DT != Dtor_Base; 150 } 151 152 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 153 154 const CXXRecordDecl * 155 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override { 156 MD = MD->getCanonicalDecl(); 157 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { 158 MicrosoftVTableContext::MethodVFTableLocation ML = 159 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 160 // The vbases might be ordered differently in the final overrider object 161 // and the complete object, so the "this" argument may sometimes point to 162 // memory that has no particular type (e.g. past the complete object). 163 // In this case, we just use a generic pointer type. 164 // FIXME: might want to have a more precise type in the non-virtual 165 // multiple inheritance case. 166 if (ML.VBase || !ML.VFPtrOffset.isZero()) 167 return nullptr; 168 } 169 return MD->getParent(); 170 } 171 172 llvm::Value * 173 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, 174 llvm::Value *This, 175 bool VirtualCall) override; 176 177 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 178 FunctionArgList &Params) override; 179 180 llvm::Value *adjustThisParameterInVirtualFunctionPrologue( 181 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override; 182 183 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 184 185 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 186 const CXXConstructorDecl *D, 187 CXXCtorType Type, bool ForVirtualBase, 188 bool Delegating, 189 CallArgList &Args) override; 190 191 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 192 CXXDtorType Type, bool ForVirtualBase, 193 bool Delegating, llvm::Value *This) override; 194 195 void emitVTableDefinitions(CodeGenVTables &CGVT, 196 const CXXRecordDecl *RD) override; 197 198 llvm::Value *getVTableAddressPointInStructor( 199 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 200 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 201 bool &NeedsVirtualOffset) override; 202 203 llvm::Constant * 204 getVTableAddressPointForConstExpr(BaseSubobject Base, 205 const CXXRecordDecl *VTableClass) override; 206 207 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 208 CharUnits VPtrOffset) override; 209 210 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 211 llvm::Value *This, 212 llvm::Type *Ty) override; 213 214 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 215 const CXXDestructorDecl *Dtor, 216 CXXDtorType DtorType, llvm::Value *This, 217 const CXXMemberCallExpr *CE) override; 218 219 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, 220 CallArgList &CallArgs) override { 221 assert(GD.getDtorType() == Dtor_Deleting && 222 "Only deleting destructor thunks are available in this ABI"); 223 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)), 224 CGM.getContext().IntTy); 225 } 226 227 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 228 229 llvm::GlobalVariable * 230 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 231 llvm::GlobalVariable::LinkageTypes Linkage); 232 233 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD, 234 llvm::GlobalVariable *GV) const; 235 236 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, 237 GlobalDecl GD, bool ReturnAdjustment) override { 238 // Never dllimport/dllexport thunks. 239 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 240 241 GVALinkage Linkage = 242 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl())); 243 244 if (Linkage == GVA_Internal) 245 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage); 246 else if (ReturnAdjustment) 247 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage); 248 else 249 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 250 } 251 252 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 253 const ThisAdjustment &TA) override; 254 255 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 256 const ReturnAdjustment &RA) override; 257 258 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 259 llvm::GlobalVariable *DeclPtr, 260 bool PerformInit) override; 261 262 // ==== Notes on array cookies ========= 263 // 264 // MSVC seems to only use cookies when the class has a destructor; a 265 // two-argument usual array deallocation function isn't sufficient. 266 // 267 // For example, this code prints "100" and "1": 268 // struct A { 269 // char x; 270 // void *operator new[](size_t sz) { 271 // printf("%u\n", sz); 272 // return malloc(sz); 273 // } 274 // void operator delete[](void *p, size_t sz) { 275 // printf("%u\n", sz); 276 // free(p); 277 // } 278 // }; 279 // int main() { 280 // A *p = new A[100]; 281 // delete[] p; 282 // } 283 // Whereas it prints "104" and "104" if you give A a destructor. 284 285 bool requiresArrayCookie(const CXXDeleteExpr *expr, 286 QualType elementType) override; 287 bool requiresArrayCookie(const CXXNewExpr *expr) override; 288 CharUnits getArrayCookieSizeImpl(QualType type) override; 289 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 290 llvm::Value *NewPtr, 291 llvm::Value *NumElements, 292 const CXXNewExpr *expr, 293 QualType ElementType) override; 294 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 295 llvm::Value *allocPtr, 296 CharUnits cookieSize) override; 297 298 friend struct MSRTTIBuilder; 299 300 bool isImageRelative() const { 301 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64; 302 } 303 304 // 5 routines for constructing the llvm types for MS RTTI structs. 305 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) { 306 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor"); 307 TDTypeName += llvm::utostr(TypeInfoString.size()); 308 llvm::StructType *&TypeDescriptorType = 309 TypeDescriptorTypeMap[TypeInfoString.size()]; 310 if (TypeDescriptorType) 311 return TypeDescriptorType; 312 llvm::Type *FieldTypes[] = { 313 CGM.Int8PtrPtrTy, 314 CGM.Int8PtrTy, 315 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)}; 316 TypeDescriptorType = 317 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName); 318 return TypeDescriptorType; 319 } 320 321 llvm::Type *getImageRelativeType(llvm::Type *PtrType) { 322 if (!isImageRelative()) 323 return PtrType; 324 return CGM.IntTy; 325 } 326 327 llvm::StructType *getBaseClassDescriptorType() { 328 if (BaseClassDescriptorType) 329 return BaseClassDescriptorType; 330 llvm::Type *FieldTypes[] = { 331 getImageRelativeType(CGM.Int8PtrTy), 332 CGM.IntTy, 333 CGM.IntTy, 334 CGM.IntTy, 335 CGM.IntTy, 336 CGM.IntTy, 337 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()), 338 }; 339 BaseClassDescriptorType = llvm::StructType::create( 340 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor"); 341 return BaseClassDescriptorType; 342 } 343 344 llvm::StructType *getClassHierarchyDescriptorType() { 345 if (ClassHierarchyDescriptorType) 346 return ClassHierarchyDescriptorType; 347 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle. 348 ClassHierarchyDescriptorType = llvm::StructType::create( 349 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor"); 350 llvm::Type *FieldTypes[] = { 351 CGM.IntTy, 352 CGM.IntTy, 353 CGM.IntTy, 354 getImageRelativeType( 355 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()), 356 }; 357 ClassHierarchyDescriptorType->setBody(FieldTypes); 358 return ClassHierarchyDescriptorType; 359 } 360 361 llvm::StructType *getCompleteObjectLocatorType() { 362 if (CompleteObjectLocatorType) 363 return CompleteObjectLocatorType; 364 CompleteObjectLocatorType = llvm::StructType::create( 365 CGM.getLLVMContext(), "rtti.CompleteObjectLocator"); 366 llvm::Type *FieldTypes[] = { 367 CGM.IntTy, 368 CGM.IntTy, 369 CGM.IntTy, 370 getImageRelativeType(CGM.Int8PtrTy), 371 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()), 372 getImageRelativeType(CompleteObjectLocatorType), 373 }; 374 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes); 375 if (!isImageRelative()) 376 FieldTypesRef = FieldTypesRef.drop_back(); 377 CompleteObjectLocatorType->setBody(FieldTypesRef); 378 return CompleteObjectLocatorType; 379 } 380 381 llvm::GlobalVariable *getImageBase() { 382 StringRef Name = "__ImageBase"; 383 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name)) 384 return GV; 385 386 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, 387 /*isConstant=*/true, 388 llvm::GlobalValue::ExternalLinkage, 389 /*Initializer=*/nullptr, Name); 390 } 391 392 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) { 393 if (!isImageRelative()) 394 return PtrVal; 395 396 llvm::Constant *ImageBaseAsInt = 397 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy); 398 llvm::Constant *PtrValAsInt = 399 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy); 400 llvm::Constant *Diff = 401 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt, 402 /*HasNUW=*/true, /*HasNSW=*/true); 403 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy); 404 } 405 406 private: 407 MicrosoftMangleContext &getMangleContext() { 408 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 409 } 410 411 llvm::Constant *getZeroInt() { 412 return llvm::ConstantInt::get(CGM.IntTy, 0); 413 } 414 415 llvm::Constant *getAllOnesInt() { 416 return llvm::Constant::getAllOnesValue(CGM.IntTy); 417 } 418 419 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) { 420 return C ? C : getZeroInt(); 421 } 422 423 llvm::Value *getValueOrZeroInt(llvm::Value *C) { 424 return C ? C : getZeroInt(); 425 } 426 427 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD); 428 429 void 430 GetNullMemberPointerFields(const MemberPointerType *MPT, 431 llvm::SmallVectorImpl<llvm::Constant *> &fields); 432 433 /// \brief Shared code for virtual base adjustment. Returns the offset from 434 /// the vbptr to the virtual base. Optionally returns the address of the 435 /// vbptr itself. 436 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 437 llvm::Value *Base, 438 llvm::Value *VBPtrOffset, 439 llvm::Value *VBTableOffset, 440 llvm::Value **VBPtr = nullptr); 441 442 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 443 llvm::Value *Base, 444 int32_t VBPtrOffset, 445 int32_t VBTableOffset, 446 llvm::Value **VBPtr = nullptr) { 447 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 448 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset); 449 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr); 450 } 451 452 /// \brief Performs a full virtual base adjustment. Used to dereference 453 /// pointers to members of virtual bases. 454 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E, 455 const CXXRecordDecl *RD, llvm::Value *Base, 456 llvm::Value *VirtualBaseAdjustmentOffset, 457 llvm::Value *VBPtrOffset /* optional */); 458 459 /// \brief Emits a full member pointer with the fields common to data and 460 /// function member pointers. 461 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField, 462 bool IsMemberFunction, 463 const CXXRecordDecl *RD, 464 CharUnits NonVirtualBaseAdjustment); 465 466 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD, 467 const CXXMethodDecl *MD, 468 CharUnits NonVirtualBaseAdjustment); 469 470 bool MemberPointerConstantIsNull(const MemberPointerType *MPT, 471 llvm::Constant *MP); 472 473 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type. 474 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD); 475 476 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables(). 477 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD); 478 479 /// \brief Generate a thunk for calling a virtual member function MD. 480 llvm::Function *EmitVirtualMemPtrThunk( 481 const CXXMethodDecl *MD, 482 const MicrosoftVTableContext::MethodVFTableLocation &ML); 483 484 public: 485 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 486 487 bool isZeroInitializable(const MemberPointerType *MPT) override; 488 489 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override { 490 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 491 return RD->hasAttr<MSInheritanceAttr>(); 492 } 493 494 virtual bool isTypeInfoCalculable(QualType Ty) const override { 495 if (!CGCXXABI::isTypeInfoCalculable(Ty)) 496 return false; 497 if (const auto *MPT = Ty->getAs<MemberPointerType>()) { 498 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 499 if (!RD->hasAttr<MSInheritanceAttr>()) 500 return false; 501 } 502 return true; 503 } 504 505 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 506 507 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 508 CharUnits offset) override; 509 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override; 510 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 511 512 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 513 llvm::Value *L, 514 llvm::Value *R, 515 const MemberPointerType *MPT, 516 bool Inequality) override; 517 518 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 519 llvm::Value *MemPtr, 520 const MemberPointerType *MPT) override; 521 522 llvm::Value * 523 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 524 llvm::Value *Base, llvm::Value *MemPtr, 525 const MemberPointerType *MPT) override; 526 527 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 528 const CastExpr *E, 529 llvm::Value *Src) override; 530 531 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 532 llvm::Constant *Src) override; 533 534 llvm::Value * 535 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, 536 llvm::Value *&This, llvm::Value *MemPtr, 537 const MemberPointerType *MPT) override; 538 539 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; 540 541 private: 542 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy; 543 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy; 544 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy; 545 /// \brief All the vftables that have been referenced. 546 VFTablesMapTy VFTablesMap; 547 VTablesMapTy VTablesMap; 548 549 /// \brief This set holds the record decls we've deferred vtable emission for. 550 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables; 551 552 553 /// \brief All the vbtables which have been referenced. 554 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap; 555 556 /// Info on the global variable used to guard initialization of static locals. 557 /// The BitIndex field is only used for externally invisible declarations. 558 struct GuardInfo { 559 GuardInfo() : Guard(nullptr), BitIndex(0) {} 560 llvm::GlobalVariable *Guard; 561 unsigned BitIndex; 562 }; 563 564 /// Map from DeclContext to the current guard variable. We assume that the 565 /// AST is visited in source code order. 566 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap; 567 568 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap; 569 llvm::StructType *BaseClassDescriptorType; 570 llvm::StructType *ClassHierarchyDescriptorType; 571 llvm::StructType *CompleteObjectLocatorType; 572 }; 573 574 } 575 576 CGCXXABI::RecordArgABI 577 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const { 578 switch (CGM.getTarget().getTriple().getArch()) { 579 default: 580 // FIXME: Implement for other architectures. 581 return RAA_Default; 582 583 case llvm::Triple::x86: 584 // All record arguments are passed in memory on x86. Decide whether to 585 // construct the object directly in argument memory, or to construct the 586 // argument elsewhere and copy the bytes during the call. 587 588 // If C++ prohibits us from making a copy, construct the arguments directly 589 // into argument memory. 590 if (!canCopyArgument(RD)) 591 return RAA_DirectInMemory; 592 593 // Otherwise, construct the argument into a temporary and copy the bytes 594 // into the outgoing argument memory. 595 return RAA_Default; 596 597 case llvm::Triple::x86_64: 598 // Win64 passes objects with non-trivial copy ctors indirectly. 599 if (RD->hasNonTrivialCopyConstructor()) 600 return RAA_Indirect; 601 602 // Win64 passes objects larger than 8 bytes indirectly. 603 if (getContext().getTypeSize(RD->getTypeForDecl()) > 64) 604 return RAA_Indirect; 605 606 // We have a trivial copy constructor or no copy constructors, but we have 607 // to make sure it isn't deleted. 608 bool CopyDeleted = false; 609 for (const CXXConstructorDecl *CD : RD->ctors()) { 610 if (CD->isCopyConstructor()) { 611 assert(CD->isTrivial()); 612 // We had at least one undeleted trivial copy ctor. Return directly. 613 if (!CD->isDeleted()) 614 return RAA_Default; 615 CopyDeleted = true; 616 } 617 } 618 619 // The trivial copy constructor was deleted. Return indirectly. 620 if (CopyDeleted) 621 return RAA_Indirect; 622 623 // There were no copy ctors. Return in RAX. 624 return RAA_Default; 625 } 626 627 llvm_unreachable("invalid enum"); 628 } 629 630 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 631 llvm::Value *ptr, 632 QualType type) { 633 // FIXME: implement 634 return ptr; 635 } 636 637 /// \brief Gets the offset to the virtual base that contains the vfptr for 638 /// MS-ABI polymorphic types. 639 static llvm::Value *getPolymorphicOffset(CodeGenFunction &CGF, 640 const CXXRecordDecl *RD, 641 llvm::Value *Value) { 642 const ASTContext &Context = RD->getASTContext(); 643 for (const CXXBaseSpecifier &Base : RD->vbases()) 644 if (Context.getASTRecordLayout(Base.getType()->getAsCXXRecordDecl()) 645 .hasExtendableVFPtr()) 646 return CGF.CGM.getCXXABI().GetVirtualBaseClassOffset( 647 CGF, Value, RD, Base.getType()->getAsCXXRecordDecl()); 648 llvm_unreachable("One of our vbases should be polymorphic."); 649 } 650 651 static std::pair<llvm::Value *, llvm::Value *> 652 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value, 653 QualType SrcRecordTy) { 654 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy); 655 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 656 657 if (CGF.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr()) 658 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 659 660 // Perform a base adjustment. 661 llvm::Value *Offset = getPolymorphicOffset(CGF, SrcDecl, Value); 662 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset); 663 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty); 664 return std::make_pair(Value, Offset); 665 } 666 667 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 668 QualType SrcRecordTy) { 669 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 670 return IsDeref && 671 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 672 } 673 674 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF, 675 llvm::Value *Argument) { 676 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 677 llvm::FunctionType *FTy = 678 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false); 679 llvm::Value *Args[] = {Argument}; 680 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid"); 681 return CGF.EmitRuntimeCallOrInvoke(Fn, Args); 682 } 683 684 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 685 llvm::CallSite Call = 686 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy)); 687 Call.setDoesNotReturn(); 688 CGF.Builder.CreateUnreachable(); 689 } 690 691 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF, 692 QualType SrcRecordTy, 693 llvm::Value *ThisPtr, 694 llvm::Type *StdTypeInfoPtrTy) { 695 llvm::Value *Offset; 696 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy); 697 return CGF.Builder.CreateBitCast( 698 emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy); 699 } 700 701 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 702 QualType SrcRecordTy) { 703 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 704 return SrcIsPtr && 705 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 706 } 707 708 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall( 709 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy, 710 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 711 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 712 713 llvm::Value *SrcRTTI = 714 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 715 llvm::Value *DestRTTI = 716 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 717 718 llvm::Value *Offset; 719 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy); 720 721 // PVOID __RTDynamicCast( 722 // PVOID inptr, 723 // LONG VfDelta, 724 // PVOID SrcType, 725 // PVOID TargetType, 726 // BOOL isReference) 727 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy, 728 CGF.Int8PtrTy, CGF.Int32Ty}; 729 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction( 730 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 731 "__RTDynamicCast"); 732 llvm::Value *Args[] = { 733 Value, Offset, SrcRTTI, DestRTTI, 734 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())}; 735 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction(); 736 return CGF.Builder.CreateBitCast(Value, DestLTy); 737 } 738 739 llvm::Value * 740 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 741 QualType SrcRecordTy, 742 QualType DestTy) { 743 llvm::Value *Offset; 744 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy); 745 746 // PVOID __RTCastToVoid( 747 // PVOID inptr) 748 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 749 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction( 750 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 751 "__RTCastToVoid"); 752 llvm::Value *Args[] = {Value}; 753 return CGF.EmitRuntimeCall(Function, Args); 754 } 755 756 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 757 return false; 758 } 759 760 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset( 761 CodeGenFunction &CGF, llvm::Value *This, const CXXRecordDecl *ClassDecl, 762 const CXXRecordDecl *BaseClassDecl) { 763 int64_t VBPtrChars = 764 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity(); 765 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars); 766 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy); 767 CharUnits VBTableChars = 768 IntSize * 769 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl); 770 llvm::Value *VBTableOffset = 771 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity()); 772 773 llvm::Value *VBPtrToNewBase = 774 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset); 775 VBPtrToNewBase = 776 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy); 777 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase); 778 } 779 780 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const { 781 return isa<CXXConstructorDecl>(GD.getDecl()); 782 } 783 784 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 785 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 786 if (!RD) 787 return false; 788 789 if (FI.isInstanceMethod()) { 790 // If it's an instance method, aggregates are always returned indirectly via 791 // the second parameter. 792 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 793 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod()); 794 return true; 795 } else if (!RD->isPOD()) { 796 // If it's a free function, non-POD types are returned indirectly. 797 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 798 return true; 799 } 800 801 // Otherwise, use the C ABI rules. 802 return false; 803 } 804 805 llvm::BasicBlock * 806 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 807 const CXXRecordDecl *RD) { 808 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 809 assert(IsMostDerivedClass && 810 "ctor for a class with virtual bases must have an implicit parameter"); 811 llvm::Value *IsCompleteObject = 812 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 813 814 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 815 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 816 CGF.Builder.CreateCondBr(IsCompleteObject, 817 CallVbaseCtorsBB, SkipVbaseCtorsBB); 818 819 CGF.EmitBlock(CallVbaseCtorsBB); 820 821 // Fill in the vbtable pointers here. 822 EmitVBPtrStores(CGF, RD); 823 824 // CGF will put the base ctor calls in this basic block for us later. 825 826 return SkipVbaseCtorsBB; 827 } 828 829 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers( 830 CodeGenFunction &CGF, const CXXRecordDecl *RD) { 831 // In most cases, an override for a vbase virtual method can adjust 832 // the "this" parameter by applying a constant offset. 833 // However, this is not enough while a constructor or a destructor of some 834 // class X is being executed if all the following conditions are met: 835 // - X has virtual bases, (1) 836 // - X overrides a virtual method M of a vbase Y, (2) 837 // - X itself is a vbase of the most derived class. 838 // 839 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X 840 // which holds the extra amount of "this" adjustment we must do when we use 841 // the X vftables (i.e. during X ctor or dtor). 842 // Outside the ctors and dtors, the values of vtorDisps are zero. 843 844 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 845 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets; 846 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap(); 847 CGBuilderTy &Builder = CGF.Builder; 848 849 unsigned AS = 850 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace(); 851 llvm::Value *Int8This = nullptr; // Initialize lazily. 852 853 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end(); 854 I != E; ++I) { 855 if (!I->second.hasVtorDisp()) 856 continue; 857 858 llvm::Value *VBaseOffset = 859 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first); 860 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset() 861 // just to Trunc back immediately. 862 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty); 863 uint64_t ConstantVBaseOffset = 864 Layout.getVBaseClassOffset(I->first).getQuantity(); 865 866 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase). 867 llvm::Value *VtorDispValue = Builder.CreateSub( 868 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset), 869 "vtordisp.value"); 870 871 if (!Int8This) 872 Int8This = Builder.CreateBitCast(getThisValue(CGF), 873 CGF.Int8Ty->getPointerTo(AS)); 874 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset); 875 // vtorDisp is always the 32-bits before the vbase in the class layout. 876 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4); 877 VtorDispPtr = Builder.CreateBitCast( 878 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr"); 879 880 Builder.CreateStore(VtorDispValue, VtorDispPtr); 881 } 882 } 883 884 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 885 // There's only one constructor type in this ABI. 886 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 887 } 888 889 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF, 890 const CXXRecordDecl *RD) { 891 llvm::Value *ThisInt8Ptr = 892 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8"); 893 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 894 895 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 896 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 897 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 898 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 899 const ASTRecordLayout &SubobjectLayout = 900 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr); 901 CharUnits Offs = VBT->NonVirtualOffset; 902 Offs += SubobjectLayout.getVBPtrOffset(); 903 if (VBT->getVBaseWithVPtr()) 904 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr()); 905 llvm::Value *VBPtr = 906 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity()); 907 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0), 908 "vbptr." + VBT->ReusingBase->getName()); 909 CGF.Builder.CreateStore(GV, VBPtr); 910 } 911 } 912 913 void 914 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 915 SmallVectorImpl<CanQualType> &ArgTys) { 916 // TODO: 'for base' flag 917 if (T == StructorType::Deleting) { 918 // The scalar deleting destructor takes an implicit int parameter. 919 ArgTys.push_back(CGM.getContext().IntTy); 920 } 921 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 922 if (!CD) 923 return; 924 925 // All parameters are already in place except is_most_derived, which goes 926 // after 'this' if it's variadic and last if it's not. 927 928 const CXXRecordDecl *Class = CD->getParent(); 929 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>(); 930 if (Class->getNumVBases()) { 931 if (FPT->isVariadic()) 932 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy); 933 else 934 ArgTys.push_back(CGM.getContext().IntTy); 935 } 936 } 937 938 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 939 // The TU defining a dtor is only guaranteed to emit a base destructor. All 940 // other destructor variants are delegating thunks. 941 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 942 } 943 944 CharUnits 945 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) { 946 GD = GD.getCanonicalDecl(); 947 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 948 949 GlobalDecl LookupGD = GD; 950 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 951 // Complete destructors take a pointer to the complete object as a 952 // parameter, thus don't need this adjustment. 953 if (GD.getDtorType() == Dtor_Complete) 954 return CharUnits(); 955 956 // There's no Dtor_Base in vftable but it shares the this adjustment with 957 // the deleting one, so look it up instead. 958 LookupGD = GlobalDecl(DD, Dtor_Deleting); 959 } 960 961 MicrosoftVTableContext::MethodVFTableLocation ML = 962 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 963 CharUnits Adjustment = ML.VFPtrOffset; 964 965 // Normal virtual instance methods need to adjust from the vfptr that first 966 // defined the virtual method to the virtual base subobject, but destructors 967 // do not. The vector deleting destructor thunk applies this adjustment for 968 // us if necessary. 969 if (isa<CXXDestructorDecl>(MD)) 970 Adjustment = CharUnits::Zero(); 971 972 if (ML.VBase) { 973 const ASTRecordLayout &DerivedLayout = 974 CGM.getContext().getASTRecordLayout(MD->getParent()); 975 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 976 } 977 978 return Adjustment; 979 } 980 981 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( 982 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) { 983 if (!VirtualCall) { 984 // If the call of a virtual function is not virtual, we just have to 985 // compensate for the adjustment the virtual function does in its prologue. 986 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 987 if (Adjustment.isZero()) 988 return This; 989 990 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 991 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 992 This = CGF.Builder.CreateBitCast(This, charPtrTy); 993 assert(Adjustment.isPositive()); 994 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity()); 995 } 996 997 GD = GD.getCanonicalDecl(); 998 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 999 1000 GlobalDecl LookupGD = GD; 1001 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1002 // Complete dtors take a pointer to the complete object, 1003 // thus don't need adjustment. 1004 if (GD.getDtorType() == Dtor_Complete) 1005 return This; 1006 1007 // There's only Dtor_Deleting in vftable but it shares the this adjustment 1008 // with the base one, so look up the deleting one instead. 1009 LookupGD = GlobalDecl(DD, Dtor_Deleting); 1010 } 1011 MicrosoftVTableContext::MethodVFTableLocation ML = 1012 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 1013 1014 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 1015 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 1016 CharUnits StaticOffset = ML.VFPtrOffset; 1017 1018 // Base destructors expect 'this' to point to the beginning of the base 1019 // subobject, not the first vfptr that happens to contain the virtual dtor. 1020 // However, we still need to apply the virtual base adjustment. 1021 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 1022 StaticOffset = CharUnits::Zero(); 1023 1024 if (ML.VBase) { 1025 This = CGF.Builder.CreateBitCast(This, charPtrTy); 1026 llvm::Value *VBaseOffset = 1027 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase); 1028 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset); 1029 } 1030 if (!StaticOffset.isZero()) { 1031 assert(StaticOffset.isPositive()); 1032 This = CGF.Builder.CreateBitCast(This, charPtrTy); 1033 if (ML.VBase) { 1034 // Non-virtual adjustment might result in a pointer outside the allocated 1035 // object, e.g. if the final overrider class is laid out after the virtual 1036 // base that declares a method in the most derived class. 1037 // FIXME: Update the code that emits this adjustment in thunks prologues. 1038 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity()); 1039 } else { 1040 This = CGF.Builder.CreateConstInBoundsGEP1_32(This, 1041 StaticOffset.getQuantity()); 1042 } 1043 } 1044 return This; 1045 } 1046 1047 static bool IsDeletingDtor(GlobalDecl GD) { 1048 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl()); 1049 if (isa<CXXDestructorDecl>(MD)) { 1050 return GD.getDtorType() == Dtor_Deleting; 1051 } 1052 return false; 1053 } 1054 1055 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1056 QualType &ResTy, 1057 FunctionArgList &Params) { 1058 ASTContext &Context = getContext(); 1059 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1060 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1061 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 1062 ImplicitParamDecl *IsMostDerived 1063 = ImplicitParamDecl::Create(Context, nullptr, 1064 CGF.CurGD.getDecl()->getLocation(), 1065 &Context.Idents.get("is_most_derived"), 1066 Context.IntTy); 1067 // The 'most_derived' parameter goes second if the ctor is variadic and last 1068 // if it's not. Dtors can't be variadic. 1069 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1070 if (FPT->isVariadic()) 1071 Params.insert(Params.begin() + 1, IsMostDerived); 1072 else 1073 Params.push_back(IsMostDerived); 1074 getStructorImplicitParamDecl(CGF) = IsMostDerived; 1075 } else if (IsDeletingDtor(CGF.CurGD)) { 1076 ImplicitParamDecl *ShouldDelete 1077 = ImplicitParamDecl::Create(Context, nullptr, 1078 CGF.CurGD.getDecl()->getLocation(), 1079 &Context.Idents.get("should_call_delete"), 1080 Context.IntTy); 1081 Params.push_back(ShouldDelete); 1082 getStructorImplicitParamDecl(CGF) = ShouldDelete; 1083 } 1084 } 1085 1086 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue( 1087 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 1088 // In this ABI, every virtual function takes a pointer to one of the 1089 // subobjects that first defines it as the 'this' parameter, rather than a 1090 // pointer to the final overrider subobject. Thus, we need to adjust it back 1091 // to the final overrider subobject before use. 1092 // See comments in the MicrosoftVFTableContext implementation for the details. 1093 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 1094 if (Adjustment.isZero()) 1095 return This; 1096 1097 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 1098 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 1099 *thisTy = This->getType(); 1100 1101 This = CGF.Builder.CreateBitCast(This, charPtrTy); 1102 assert(Adjustment.isPositive()); 1103 This = 1104 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity()); 1105 return CGF.Builder.CreateBitCast(This, thisTy); 1106 } 1107 1108 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1109 EmitThisParam(CGF); 1110 1111 /// If this is a function that the ABI specifies returns 'this', initialize 1112 /// the return slot to 'this' at the start of the function. 1113 /// 1114 /// Unlike the setting of return types, this is done within the ABI 1115 /// implementation instead of by clients of CGCXXABI because: 1116 /// 1) getThisValue is currently protected 1117 /// 2) in theory, an ABI could implement 'this' returns some other way; 1118 /// HasThisReturn only specifies a contract, not the implementation 1119 if (HasThisReturn(CGF.CurGD)) 1120 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1121 1122 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1123 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 1124 assert(getStructorImplicitParamDecl(CGF) && 1125 "no implicit parameter for a constructor with virtual bases?"); 1126 getStructorImplicitParamValue(CGF) 1127 = CGF.Builder.CreateLoad( 1128 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1129 "is_most_derived"); 1130 } 1131 1132 if (IsDeletingDtor(CGF.CurGD)) { 1133 assert(getStructorImplicitParamDecl(CGF) && 1134 "no implicit parameter for a deleting destructor?"); 1135 getStructorImplicitParamValue(CGF) 1136 = CGF.Builder.CreateLoad( 1137 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1138 "should_call_delete"); 1139 } 1140 } 1141 1142 unsigned MicrosoftCXXABI::addImplicitConstructorArgs( 1143 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1144 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1145 assert(Type == Ctor_Complete || Type == Ctor_Base); 1146 1147 // Check if we need a 'most_derived' parameter. 1148 if (!D->getParent()->getNumVBases()) 1149 return 0; 1150 1151 // Add the 'most_derived' argument second if we are variadic or last if not. 1152 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1153 llvm::Value *MostDerivedArg = 1154 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 1155 RValue RV = RValue::get(MostDerivedArg); 1156 if (MostDerivedArg) { 1157 if (FPT->isVariadic()) 1158 Args.insert(Args.begin() + 1, 1159 CallArg(RV, getContext().IntTy, /*needscopy=*/false)); 1160 else 1161 Args.add(RV, getContext().IntTy); 1162 } 1163 1164 return 1; // Added one arg. 1165 } 1166 1167 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1168 const CXXDestructorDecl *DD, 1169 CXXDtorType Type, bool ForVirtualBase, 1170 bool Delegating, llvm::Value *This) { 1171 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)); 1172 1173 if (DD->isVirtual()) { 1174 assert(Type != CXXDtorType::Dtor_Deleting && 1175 "The deleting destructor should only be called via a virtual call"); 1176 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), 1177 This, false); 1178 } 1179 1180 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, 1181 /*ImplicitParam=*/nullptr, 1182 /*ImplicitParamTy=*/QualType(), nullptr); 1183 } 1184 1185 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1186 const CXXRecordDecl *RD) { 1187 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 1188 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD); 1189 1190 for (VPtrInfo *Info : VFPtrs) { 1191 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC); 1192 if (VTable->hasInitializer()) 1193 continue; 1194 1195 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData 1196 ? getMSCompleteObjectLocator(RD, Info) 1197 : nullptr; 1198 1199 const VTableLayout &VTLayout = 1200 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC); 1201 llvm::Constant *Init = CGVT.CreateVTableInitializer( 1202 RD, VTLayout.vtable_component_begin(), 1203 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(), 1204 VTLayout.getNumVTableThunks(), RTTI); 1205 1206 VTable->setInitializer(Init); 1207 } 1208 } 1209 1210 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor( 1211 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1212 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 1213 NeedsVirtualOffset = (NearestVBase != nullptr); 1214 1215 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset()); 1216 VFTableIdTy ID(VTableClass, Base.getBaseOffset()); 1217 llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID]; 1218 if (!VTableAddressPoint) { 1219 assert(Base.getBase()->getNumVBases() && 1220 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr()); 1221 } 1222 return VTableAddressPoint; 1223 } 1224 1225 static void mangleVFTableName(MicrosoftMangleContext &MangleContext, 1226 const CXXRecordDecl *RD, const VPtrInfo *VFPtr, 1227 SmallString<256> &Name) { 1228 llvm::raw_svector_ostream Out(Name); 1229 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out); 1230 } 1231 1232 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr( 1233 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1234 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset()); 1235 VFTableIdTy ID(VTableClass, Base.getBaseOffset()); 1236 llvm::GlobalValue *VFTable = VFTablesMap[ID]; 1237 assert(VFTable && "Couldn't find a vftable for the given base?"); 1238 return VFTable; 1239 } 1240 1241 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1242 CharUnits VPtrOffset) { 1243 // getAddrOfVTable may return 0 if asked to get an address of a vtable which 1244 // shouldn't be used in the given record type. We want to cache this result in 1245 // VFTablesMap, thus a simple zero check is not sufficient. 1246 VFTableIdTy ID(RD, VPtrOffset); 1247 VTablesMapTy::iterator I; 1248 bool Inserted; 1249 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr)); 1250 if (!Inserted) 1251 return I->second; 1252 1253 llvm::GlobalVariable *&VTable = I->second; 1254 1255 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 1256 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD); 1257 1258 if (DeferredVFTables.insert(RD)) { 1259 // We haven't processed this record type before. 1260 // Queue up this v-table for possible deferred emission. 1261 CGM.addDeferredVTable(RD); 1262 1263 #ifndef NDEBUG 1264 // Create all the vftables at once in order to make sure each vftable has 1265 // a unique mangled name. 1266 llvm::StringSet<> ObservedMangledNames; 1267 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 1268 SmallString<256> Name; 1269 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 1270 if (!ObservedMangledNames.insert(Name.str())) 1271 llvm_unreachable("Already saw this mangling before?"); 1272 } 1273 #endif 1274 } 1275 1276 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 1277 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset) 1278 continue; 1279 SmallString<256> VFTableName; 1280 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], VFTableName); 1281 StringRef VTableName = VFTableName; 1282 1283 uint64_t NumVTableSlots = 1284 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC) 1285 .getNumVTableComponents(); 1286 llvm::GlobalValue::LinkageTypes VTableLinkage = 1287 llvm::GlobalValue::ExternalLinkage; 1288 llvm::ArrayType *VTableType = 1289 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots); 1290 if (getContext().getLangOpts().RTTIData) { 1291 VTableLinkage = llvm::GlobalValue::PrivateLinkage; 1292 VTableName = ""; 1293 } 1294 1295 VTable = CGM.getModule().getNamedGlobal(VFTableName); 1296 if (!VTable) { 1297 // Create a backing variable for the contents of VTable. The VTable may 1298 // or may not include space for a pointer to RTTI data. 1299 llvm::GlobalValue *VFTable = VTable = new llvm::GlobalVariable( 1300 CGM.getModule(), VTableType, /*isConstant=*/true, VTableLinkage, 1301 /*Initializer=*/nullptr, VTableName); 1302 VTable->setUnnamedAddr(true); 1303 1304 // Only insert a pointer into the VFTable for RTTI data if we are not 1305 // importing it. We never reference the RTTI data directly so there is no 1306 // need to make room for it. 1307 if (getContext().getLangOpts().RTTIData && 1308 !RD->hasAttr<DLLImportAttr>()) { 1309 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0), 1310 llvm::ConstantInt::get(CGM.IntTy, 1)}; 1311 // Create a GEP which points just after the first entry in the VFTable, 1312 // this should be the location of the first virtual method. 1313 llvm::Constant *VTableGEP = 1314 llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, GEPIndices); 1315 // The symbol for the VFTable is an alias to the GEP. It is 1316 // transparent, to other modules, what the nature of this symbol is; all 1317 // that matters is that the alias be the address of the first virtual 1318 // method. 1319 VFTable = llvm::GlobalAlias::create( 1320 cast<llvm::SequentialType>(VTableGEP->getType())->getElementType(), 1321 /*AddressSpace=*/0, llvm::GlobalValue::ExternalLinkage, 1322 VFTableName.str(), VTableGEP, &CGM.getModule()); 1323 } else { 1324 // We don't need a GlobalAlias to be a symbol for the VTable if we won't 1325 // be referencing any RTTI data. The GlobalVariable will end up being 1326 // an appropriate definition of the VFTable. 1327 VTable->setName(VFTableName.str()); 1328 } 1329 1330 VFTable->setUnnamedAddr(true); 1331 if (RD->hasAttr<DLLImportAttr>()) 1332 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1333 else if (RD->hasAttr<DLLExportAttr>()) 1334 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1335 1336 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD); 1337 if (VFTable != VTable) { 1338 if (llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage)) { 1339 // AvailableExternally implies that we grabbed the data from another 1340 // executable. No need to stick the alias in a Comdat. 1341 } else if (llvm::GlobalValue::isInternalLinkage(VFTableLinkage) || 1342 llvm::GlobalValue::isWeakODRLinkage(VFTableLinkage) || 1343 llvm::GlobalValue::isLinkOnceODRLinkage(VFTableLinkage)) { 1344 // The alias is going to be dropped into a Comdat, no need to make it 1345 // weak. 1346 if (!llvm::GlobalValue::isInternalLinkage(VFTableLinkage)) 1347 VFTableLinkage = llvm::GlobalValue::ExternalLinkage; 1348 llvm::Comdat *C = 1349 CGM.getModule().getOrInsertComdat(VFTable->getName()); 1350 // We must indicate which VFTable is larger to support linking between 1351 // translation units which do and do not have RTTI data. The largest 1352 // VFTable contains the RTTI data; translation units which reference 1353 // the smaller VFTable always reference it relative to the first 1354 // virtual method. 1355 C->setSelectionKind(llvm::Comdat::Largest); 1356 VTable->setComdat(C); 1357 } else { 1358 llvm_unreachable("unexpected linkage for vftable!"); 1359 } 1360 } 1361 VFTable->setLinkage(VFTableLinkage); 1362 CGM.setGlobalVisibility(VFTable, RD); 1363 VFTablesMap[ID] = VFTable; 1364 } 1365 break; 1366 } 1367 1368 return VTable; 1369 } 1370 1371 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1372 GlobalDecl GD, 1373 llvm::Value *This, 1374 llvm::Type *Ty) { 1375 GD = GD.getCanonicalDecl(); 1376 CGBuilderTy &Builder = CGF.Builder; 1377 1378 Ty = Ty->getPointerTo()->getPointerTo(); 1379 llvm::Value *VPtr = 1380 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1381 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty); 1382 1383 MicrosoftVTableContext::MethodVFTableLocation ML = 1384 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 1385 llvm::Value *VFuncPtr = 1386 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1387 return Builder.CreateLoad(VFuncPtr); 1388 } 1389 1390 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 1391 const CXXDestructorDecl *Dtor, 1392 CXXDtorType DtorType, 1393 llvm::Value *This, 1394 const CXXMemberCallExpr *CE) { 1395 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1396 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1397 1398 // We have only one destructor in the vftable but can get both behaviors 1399 // by passing an implicit int parameter. 1400 GlobalDecl GD(Dtor, Dtor_Deleting); 1401 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 1402 Dtor, StructorType::Deleting); 1403 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1404 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty); 1405 1406 ASTContext &Context = CGF.getContext(); 1407 llvm::Value *ImplicitParam = 1408 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 1409 DtorType == Dtor_Deleting); 1410 1411 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1412 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This, 1413 ImplicitParam, Context.IntTy, CE); 1414 } 1415 1416 const VBTableGlobals & 1417 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 1418 // At this layer, we can key the cache off of a single class, which is much 1419 // easier than caching each vbtable individually. 1420 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 1421 bool Added; 1422 std::tie(Entry, Added) = 1423 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals())); 1424 VBTableGlobals &VBGlobals = Entry->second; 1425 if (!Added) 1426 return VBGlobals; 1427 1428 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1429 VBGlobals.VBTables = &Context.enumerateVBTables(RD); 1430 1431 // Cache the globals for all vbtables so we don't have to recompute the 1432 // mangled names. 1433 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1434 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(), 1435 E = VBGlobals.VBTables->end(); 1436 I != E; ++I) { 1437 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage)); 1438 } 1439 1440 return VBGlobals; 1441 } 1442 1443 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk( 1444 const CXXMethodDecl *MD, 1445 const MicrosoftVTableContext::MethodVFTableLocation &ML) { 1446 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) && 1447 "can't form pointers to ctors or virtual dtors"); 1448 1449 // Calculate the mangled name. 1450 SmallString<256> ThunkName; 1451 llvm::raw_svector_ostream Out(ThunkName); 1452 getMangleContext().mangleVirtualMemPtrThunk(MD, Out); 1453 Out.flush(); 1454 1455 // If the thunk has been generated previously, just return it. 1456 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 1457 return cast<llvm::Function>(GV); 1458 1459 // Create the llvm::Function. 1460 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD); 1461 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 1462 llvm::Function *ThunkFn = 1463 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 1464 ThunkName.str(), &CGM.getModule()); 1465 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 1466 1467 ThunkFn->setLinkage(MD->isExternallyVisible() 1468 ? llvm::GlobalValue::LinkOnceODRLinkage 1469 : llvm::GlobalValue::InternalLinkage); 1470 1471 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 1472 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 1473 1474 // These thunks can be compared, so they are not unnamed. 1475 ThunkFn->setUnnamedAddr(false); 1476 1477 // Start codegen. 1478 CodeGenFunction CGF(CGM); 1479 CGF.CurGD = GlobalDecl(MD); 1480 CGF.CurFuncIsThunk = true; 1481 1482 // Build FunctionArgs, but only include the implicit 'this' parameter 1483 // declaration. 1484 FunctionArgList FunctionArgs; 1485 buildThisParam(CGF, FunctionArgs); 1486 1487 // Start defining the function. 1488 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo, 1489 FunctionArgs, MD->getLocation(), SourceLocation()); 1490 EmitThisParam(CGF); 1491 1492 // Load the vfptr and then callee from the vftable. The callee should have 1493 // adjusted 'this' so that the vfptr is at offset zero. 1494 llvm::Value *VTable = CGF.GetVTablePtr( 1495 getThisValue(CGF), ThunkTy->getPointerTo()->getPointerTo()); 1496 llvm::Value *VFuncPtr = 1497 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1498 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr); 1499 1500 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee); 1501 1502 return ThunkFn; 1503 } 1504 1505 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1506 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 1507 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 1508 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 1509 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 1510 emitVBTableDefinition(*VBT, RD, GV); 1511 } 1512 } 1513 1514 llvm::GlobalVariable * 1515 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 1516 llvm::GlobalVariable::LinkageTypes Linkage) { 1517 SmallString<256> OutName; 1518 llvm::raw_svector_ostream Out(OutName); 1519 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out); 1520 Out.flush(); 1521 StringRef Name = OutName.str(); 1522 1523 llvm::ArrayType *VBTableType = 1524 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases()); 1525 1526 assert(!CGM.getModule().getNamedGlobal(Name) && 1527 "vbtable with this name already exists: mangling bug?"); 1528 llvm::GlobalVariable *GV = 1529 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage); 1530 GV->setUnnamedAddr(true); 1531 1532 if (RD->hasAttr<DLLImportAttr>()) 1533 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1534 else if (RD->hasAttr<DLLExportAttr>()) 1535 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1536 1537 return GV; 1538 } 1539 1540 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT, 1541 const CXXRecordDecl *RD, 1542 llvm::GlobalVariable *GV) const { 1543 const CXXRecordDecl *ReusingBase = VBT.ReusingBase; 1544 1545 assert(RD->getNumVBases() && ReusingBase->getNumVBases() && 1546 "should only emit vbtables for classes with vbtables"); 1547 1548 const ASTRecordLayout &BaseLayout = 1549 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr); 1550 const ASTRecordLayout &DerivedLayout = 1551 CGM.getContext().getASTRecordLayout(RD); 1552 1553 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 1554 nullptr); 1555 1556 // The offset from ReusingBase's vbptr to itself always leads. 1557 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 1558 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 1559 1560 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1561 for (const auto &I : ReusingBase->vbases()) { 1562 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl(); 1563 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 1564 assert(!Offset.isNegative()); 1565 1566 // Make it relative to the subobject vbptr. 1567 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 1568 if (VBT.getVBaseWithVPtr()) 1569 CompleteVBPtrOffset += 1570 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr()); 1571 Offset -= CompleteVBPtrOffset; 1572 1573 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase); 1574 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?"); 1575 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 1576 } 1577 1578 assert(Offsets.size() == 1579 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 1580 ->getElementType())->getNumElements()); 1581 llvm::ArrayType *VBTableType = 1582 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 1583 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 1584 GV->setInitializer(Init); 1585 1586 // Set the right visibility. 1587 CGM.setGlobalVisibility(GV, RD); 1588 } 1589 1590 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1591 llvm::Value *This, 1592 const ThisAdjustment &TA) { 1593 if (TA.isEmpty()) 1594 return This; 1595 1596 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy); 1597 1598 if (!TA.Virtual.isEmpty()) { 1599 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 1600 // Adjust the this argument based on the vtordisp value. 1601 llvm::Value *VtorDispPtr = 1602 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset); 1603 VtorDispPtr = 1604 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo()); 1605 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 1606 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp)); 1607 1608 if (TA.Virtual.Microsoft.VBPtrOffset) { 1609 // If the final overrider is defined in a virtual base other than the one 1610 // that holds the vfptr, we have to use a vtordispex thunk which looks up 1611 // the vbtable of the derived class. 1612 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 1613 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 1614 llvm::Value *VBPtr; 1615 llvm::Value *VBaseOffset = 1616 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset, 1617 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 1618 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1619 } 1620 } 1621 1622 if (TA.NonVirtual) { 1623 // Non-virtual adjustment might result in a pointer outside the allocated 1624 // object, e.g. if the final overrider class is laid out after the virtual 1625 // base that declares a method in the most derived class. 1626 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 1627 } 1628 1629 // Don't need to bitcast back, the call CodeGen will handle this. 1630 return V; 1631 } 1632 1633 llvm::Value * 1634 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1635 const ReturnAdjustment &RA) { 1636 if (RA.isEmpty()) 1637 return Ret; 1638 1639 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy); 1640 1641 if (RA.Virtual.Microsoft.VBIndex) { 1642 assert(RA.Virtual.Microsoft.VBIndex > 0); 1643 int32_t IntSize = 1644 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity(); 1645 llvm::Value *VBPtr; 1646 llvm::Value *VBaseOffset = 1647 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset, 1648 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 1649 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1650 } 1651 1652 if (RA.NonVirtual) 1653 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual); 1654 1655 // Cast back to the original type. 1656 return CGF.Builder.CreateBitCast(V, Ret->getType()); 1657 } 1658 1659 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 1660 QualType elementType) { 1661 // Microsoft seems to completely ignore the possibility of a 1662 // two-argument usual deallocation function. 1663 return elementType.isDestructedType(); 1664 } 1665 1666 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 1667 // Microsoft seems to completely ignore the possibility of a 1668 // two-argument usual deallocation function. 1669 return expr->getAllocatedType().isDestructedType(); 1670 } 1671 1672 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 1673 // The array cookie is always a size_t; we then pad that out to the 1674 // alignment of the element type. 1675 ASTContext &Ctx = getContext(); 1676 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 1677 Ctx.getTypeAlignInChars(type)); 1678 } 1679 1680 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1681 llvm::Value *allocPtr, 1682 CharUnits cookieSize) { 1683 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1684 llvm::Value *numElementsPtr = 1685 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 1686 return CGF.Builder.CreateLoad(numElementsPtr); 1687 } 1688 1689 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1690 llvm::Value *newPtr, 1691 llvm::Value *numElements, 1692 const CXXNewExpr *expr, 1693 QualType elementType) { 1694 assert(requiresArrayCookie(expr)); 1695 1696 // The size of the cookie. 1697 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 1698 1699 // Compute an offset to the cookie. 1700 llvm::Value *cookiePtr = newPtr; 1701 1702 // Write the number of elements into the appropriate slot. 1703 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1704 llvm::Value *numElementsPtr 1705 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 1706 CGF.Builder.CreateStore(numElements, numElementsPtr); 1707 1708 // Finally, compute a pointer to the actual data buffer by skipping 1709 // over the cookie completely. 1710 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1711 cookieSize.getQuantity()); 1712 } 1713 1714 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 1715 llvm::GlobalVariable *GV, 1716 bool PerformInit) { 1717 // MSVC only uses guards for static locals. 1718 if (!D.isStaticLocal()) { 1719 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()); 1720 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr. 1721 CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 1722 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 1723 return; 1724 } 1725 1726 // MSVC always uses an i32 bitfield to guard initialization, which is *not* 1727 // threadsafe. Since the user may be linking in inline functions compiled by 1728 // cl.exe, there's no reason to provide a false sense of security by using 1729 // critical sections here. 1730 1731 if (D.getTLSKind()) 1732 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 1733 1734 CGBuilderTy &Builder = CGF.Builder; 1735 llvm::IntegerType *GuardTy = CGF.Int32Ty; 1736 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 1737 1738 // Get the guard variable for this function if we have one already. 1739 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()]; 1740 1741 unsigned BitIndex; 1742 if (D.isStaticLocal() && D.isExternallyVisible()) { 1743 // Externally visible variables have to be numbered in Sema to properly 1744 // handle unreachable VarDecls. 1745 BitIndex = getContext().getStaticLocalNumber(&D); 1746 assert(BitIndex > 0); 1747 BitIndex--; 1748 } else { 1749 // Non-externally visible variables are numbered here in CodeGen. 1750 BitIndex = GI->BitIndex++; 1751 } 1752 1753 if (BitIndex >= 32) { 1754 if (D.isExternallyVisible()) 1755 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 1756 BitIndex %= 32; 1757 GI->Guard = nullptr; 1758 } 1759 1760 // Lazily create the i32 bitfield for this function. 1761 if (!GI->Guard) { 1762 // Mangle the name for the guard. 1763 SmallString<256> GuardName; 1764 { 1765 llvm::raw_svector_ostream Out(GuardName); 1766 getMangleContext().mangleStaticGuardVariable(&D, Out); 1767 Out.flush(); 1768 } 1769 1770 // Create the guard variable with a zero-initializer. Just absorb linkage, 1771 // visibility and dll storage class from the guarded variable. 1772 GI->Guard = 1773 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false, 1774 GV->getLinkage(), Zero, GuardName.str()); 1775 GI->Guard->setVisibility(GV->getVisibility()); 1776 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass()); 1777 } else { 1778 assert(GI->Guard->getLinkage() == GV->getLinkage() && 1779 "static local from the same function had different linkage"); 1780 } 1781 1782 // Pseudo code for the test: 1783 // if (!(GuardVar & MyGuardBit)) { 1784 // GuardVar |= MyGuardBit; 1785 // ... initialize the object ...; 1786 // } 1787 1788 // Test our bit from the guard variable. 1789 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex); 1790 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard); 1791 llvm::Value *IsInitialized = 1792 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero); 1793 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1794 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1795 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock); 1796 1797 // Set our bit in the guard variable and emit the initializer and add a global 1798 // destructor if appropriate. 1799 CGF.EmitBlock(InitBlock); 1800 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard); 1801 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 1802 Builder.CreateBr(EndBlock); 1803 1804 // Continue. 1805 CGF.EmitBlock(EndBlock); 1806 } 1807 1808 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 1809 // Null-ness for function memptrs only depends on the first field, which is 1810 // the function pointer. The rest don't matter, so we can zero initialize. 1811 if (MPT->isMemberFunctionPointer()) 1812 return true; 1813 1814 // The virtual base adjustment field is always -1 for null, so if we have one 1815 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 1816 // valid field offset. 1817 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1818 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1819 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) && 1820 RD->nullFieldOffsetIsZero()); 1821 } 1822 1823 llvm::Type * 1824 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 1825 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1826 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1827 llvm::SmallVector<llvm::Type *, 4> fields; 1828 if (MPT->isMemberFunctionPointer()) 1829 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 1830 else 1831 fields.push_back(CGM.IntTy); // FieldOffset 1832 1833 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1834 Inheritance)) 1835 fields.push_back(CGM.IntTy); 1836 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1837 fields.push_back(CGM.IntTy); 1838 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1839 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 1840 1841 if (fields.size() == 1) 1842 return fields[0]; 1843 return llvm::StructType::get(CGM.getLLVMContext(), fields); 1844 } 1845 1846 void MicrosoftCXXABI:: 1847 GetNullMemberPointerFields(const MemberPointerType *MPT, 1848 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 1849 assert(fields.empty()); 1850 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1851 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1852 if (MPT->isMemberFunctionPointer()) { 1853 // FunctionPointerOrVirtualThunk 1854 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1855 } else { 1856 if (RD->nullFieldOffsetIsZero()) 1857 fields.push_back(getZeroInt()); // FieldOffset 1858 else 1859 fields.push_back(getAllOnesInt()); // FieldOffset 1860 } 1861 1862 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1863 Inheritance)) 1864 fields.push_back(getZeroInt()); 1865 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1866 fields.push_back(getZeroInt()); 1867 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1868 fields.push_back(getAllOnesInt()); 1869 } 1870 1871 llvm::Constant * 1872 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 1873 llvm::SmallVector<llvm::Constant *, 4> fields; 1874 GetNullMemberPointerFields(MPT, fields); 1875 if (fields.size() == 1) 1876 return fields[0]; 1877 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 1878 assert(Res->getType() == ConvertMemberPointerType(MPT)); 1879 return Res; 1880 } 1881 1882 llvm::Constant * 1883 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 1884 bool IsMemberFunction, 1885 const CXXRecordDecl *RD, 1886 CharUnits NonVirtualBaseAdjustment) 1887 { 1888 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1889 1890 // Single inheritance class member pointer are represented as scalars instead 1891 // of aggregates. 1892 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance)) 1893 return FirstField; 1894 1895 llvm::SmallVector<llvm::Constant *, 4> fields; 1896 fields.push_back(FirstField); 1897 1898 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance)) 1899 fields.push_back(llvm::ConstantInt::get( 1900 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 1901 1902 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) { 1903 CharUnits Offs = CharUnits::Zero(); 1904 if (RD->getNumVBases()) 1905 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1906 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 1907 } 1908 1909 // The rest of the fields are adjusted by conversions to a more derived class. 1910 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1911 fields.push_back(getZeroInt()); 1912 1913 return llvm::ConstantStruct::getAnon(fields); 1914 } 1915 1916 llvm::Constant * 1917 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 1918 CharUnits offset) { 1919 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1920 llvm::Constant *FirstField = 1921 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 1922 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 1923 CharUnits::Zero()); 1924 } 1925 1926 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 1927 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero()); 1928 } 1929 1930 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 1931 QualType MPType) { 1932 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 1933 const ValueDecl *MPD = MP.getMemberPointerDecl(); 1934 if (!MPD) 1935 return EmitNullMemberPointer(MPT); 1936 1937 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 1938 1939 // FIXME PR15713: Support virtual inheritance paths. 1940 1941 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 1942 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD, 1943 ThisAdjustment); 1944 1945 CharUnits FieldOffset = 1946 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 1947 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 1948 } 1949 1950 llvm::Constant * 1951 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD, 1952 const CXXMethodDecl *MD, 1953 CharUnits NonVirtualBaseAdjustment) { 1954 assert(MD->isInstance() && "Member function must not be static!"); 1955 MD = MD->getCanonicalDecl(); 1956 RD = RD->getMostRecentDecl(); 1957 CodeGenTypes &Types = CGM.getTypes(); 1958 1959 llvm::Constant *FirstField; 1960 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1961 if (!MD->isVirtual()) { 1962 llvm::Type *Ty; 1963 // Check whether the function has a computable LLVM signature. 1964 if (Types.isFuncTypeConvertible(FPT)) { 1965 // The function has a computable LLVM signature; use the correct type. 1966 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 1967 } else { 1968 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 1969 // function type is incomplete. 1970 Ty = CGM.PtrDiffTy; 1971 } 1972 FirstField = CGM.GetAddrOfFunction(MD, Ty); 1973 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 1974 } else { 1975 MicrosoftVTableContext::MethodVFTableLocation ML = 1976 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 1977 if (!CGM.getTypes().isFuncTypeConvertible( 1978 MD->getType()->castAs<FunctionType>())) { 1979 CGM.ErrorUnsupported(MD, "pointer to virtual member function with " 1980 "incomplete return or parameter type"); 1981 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1982 } else if (FPT->getCallConv() == CC_X86FastCall) { 1983 CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function"); 1984 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1985 } else if (ML.VBase) { 1986 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding " 1987 "member function in virtual base class"); 1988 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1989 } else { 1990 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML); 1991 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy); 1992 // Include the vfptr adjustment if the method is in a non-primary vftable. 1993 NonVirtualBaseAdjustment += ML.VFPtrOffset; 1994 } 1995 } 1996 1997 // The rest of the fields are common with data member pointers. 1998 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 1999 NonVirtualBaseAdjustment); 2000 } 2001 2002 /// Member pointers are the same if they're either bitwise identical *or* both 2003 /// null. Null-ness for function members is determined by the first field, 2004 /// while for data member pointers we must compare all fields. 2005 llvm::Value * 2006 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 2007 llvm::Value *L, 2008 llvm::Value *R, 2009 const MemberPointerType *MPT, 2010 bool Inequality) { 2011 CGBuilderTy &Builder = CGF.Builder; 2012 2013 // Handle != comparisons by switching the sense of all boolean operations. 2014 llvm::ICmpInst::Predicate Eq; 2015 llvm::Instruction::BinaryOps And, Or; 2016 if (Inequality) { 2017 Eq = llvm::ICmpInst::ICMP_NE; 2018 And = llvm::Instruction::Or; 2019 Or = llvm::Instruction::And; 2020 } else { 2021 Eq = llvm::ICmpInst::ICMP_EQ; 2022 And = llvm::Instruction::And; 2023 Or = llvm::Instruction::Or; 2024 } 2025 2026 // If this is a single field member pointer (single inheritance), this is a 2027 // single icmp. 2028 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2029 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 2030 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(), 2031 Inheritance)) 2032 return Builder.CreateICmp(Eq, L, R); 2033 2034 // Compare the first field. 2035 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 2036 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 2037 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 2038 2039 // Compare everything other than the first field. 2040 llvm::Value *Res = nullptr; 2041 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 2042 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 2043 llvm::Value *LF = Builder.CreateExtractValue(L, I); 2044 llvm::Value *RF = Builder.CreateExtractValue(R, I); 2045 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 2046 if (Res) 2047 Res = Builder.CreateBinOp(And, Res, Cmp); 2048 else 2049 Res = Cmp; 2050 } 2051 2052 // Check if the first field is 0 if this is a function pointer. 2053 if (MPT->isMemberFunctionPointer()) { 2054 // (l1 == r1 && ...) || l0 == 0 2055 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 2056 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 2057 Res = Builder.CreateBinOp(Or, Res, IsZero); 2058 } 2059 2060 // Combine the comparison of the first field, which must always be true for 2061 // this comparison to succeeed. 2062 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 2063 } 2064 2065 llvm::Value * 2066 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 2067 llvm::Value *MemPtr, 2068 const MemberPointerType *MPT) { 2069 CGBuilderTy &Builder = CGF.Builder; 2070 llvm::SmallVector<llvm::Constant *, 4> fields; 2071 // We only need one field for member functions. 2072 if (MPT->isMemberFunctionPointer()) 2073 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 2074 else 2075 GetNullMemberPointerFields(MPT, fields); 2076 assert(!fields.empty()); 2077 llvm::Value *FirstField = MemPtr; 2078 if (MemPtr->getType()->isStructTy()) 2079 FirstField = Builder.CreateExtractValue(MemPtr, 0); 2080 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 2081 2082 // For function member pointers, we only need to test the function pointer 2083 // field. The other fields if any can be garbage. 2084 if (MPT->isMemberFunctionPointer()) 2085 return Res; 2086 2087 // Otherwise, emit a series of compares and combine the results. 2088 for (int I = 1, E = fields.size(); I < E; ++I) { 2089 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 2090 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 2091 Res = Builder.CreateOr(Res, Next, "memptr.tobool"); 2092 } 2093 return Res; 2094 } 2095 2096 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 2097 llvm::Constant *Val) { 2098 // Function pointers are null if the pointer in the first field is null. 2099 if (MPT->isMemberFunctionPointer()) { 2100 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 2101 Val->getAggregateElement(0U) : Val; 2102 return FirstField->isNullValue(); 2103 } 2104 2105 // If it's not a function pointer and it's zero initializable, we can easily 2106 // check zero. 2107 if (isZeroInitializable(MPT) && Val->isNullValue()) 2108 return true; 2109 2110 // Otherwise, break down all the fields for comparison. Hopefully these 2111 // little Constants are reused, while a big null struct might not be. 2112 llvm::SmallVector<llvm::Constant *, 4> Fields; 2113 GetNullMemberPointerFields(MPT, Fields); 2114 if (Fields.size() == 1) { 2115 assert(Val->getType()->isIntegerTy()); 2116 return Val == Fields[0]; 2117 } 2118 2119 unsigned I, E; 2120 for (I = 0, E = Fields.size(); I != E; ++I) { 2121 if (Val->getAggregateElement(I) != Fields[I]) 2122 break; 2123 } 2124 return I == E; 2125 } 2126 2127 llvm::Value * 2128 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 2129 llvm::Value *This, 2130 llvm::Value *VBPtrOffset, 2131 llvm::Value *VBTableOffset, 2132 llvm::Value **VBPtrOut) { 2133 CGBuilderTy &Builder = CGF.Builder; 2134 // Load the vbtable pointer from the vbptr in the instance. 2135 This = Builder.CreateBitCast(This, CGM.Int8PtrTy); 2136 llvm::Value *VBPtr = 2137 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr"); 2138 if (VBPtrOut) *VBPtrOut = VBPtr; 2139 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0)); 2140 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable"); 2141 2142 // Load an i32 offset from the vb-table. 2143 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset); 2144 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 2145 return Builder.CreateLoad(VBaseOffs, "vbase_offs"); 2146 } 2147 2148 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 2149 // it. 2150 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase( 2151 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD, 2152 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) { 2153 CGBuilderTy &Builder = CGF.Builder; 2154 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 2155 llvm::BasicBlock *OriginalBB = nullptr; 2156 llvm::BasicBlock *SkipAdjustBB = nullptr; 2157 llvm::BasicBlock *VBaseAdjustBB = nullptr; 2158 2159 // In the unspecified inheritance model, there might not be a vbtable at all, 2160 // in which case we need to skip the virtual base lookup. If there is a 2161 // vbtable, the first entry is a no-op entry that gives back the original 2162 // base, so look for a virtual base adjustment offset of zero. 2163 if (VBPtrOffset) { 2164 OriginalBB = Builder.GetInsertBlock(); 2165 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 2166 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 2167 llvm::Value *IsVirtual = 2168 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 2169 "memptr.is_vbase"); 2170 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 2171 CGF.EmitBlock(VBaseAdjustBB); 2172 } 2173 2174 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 2175 // know the vbptr offset. 2176 if (!VBPtrOffset) { 2177 CharUnits offs = CharUnits::Zero(); 2178 if (!RD->hasDefinition()) { 2179 DiagnosticsEngine &Diags = CGF.CGM.getDiags(); 2180 unsigned DiagID = Diags.getCustomDiagID( 2181 DiagnosticsEngine::Error, 2182 "member pointer representation requires a " 2183 "complete class type for %0 to perform this expression"); 2184 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange(); 2185 } else if (RD->getNumVBases()) 2186 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 2187 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 2188 } 2189 llvm::Value *VBPtr = nullptr; 2190 llvm::Value *VBaseOffs = 2191 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 2192 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 2193 2194 // Merge control flow with the case where we didn't have to adjust. 2195 if (VBaseAdjustBB) { 2196 Builder.CreateBr(SkipAdjustBB); 2197 CGF.EmitBlock(SkipAdjustBB); 2198 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 2199 Phi->addIncoming(Base, OriginalBB); 2200 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 2201 return Phi; 2202 } 2203 return AdjustedBase; 2204 } 2205 2206 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress( 2207 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr, 2208 const MemberPointerType *MPT) { 2209 assert(MPT->isMemberDataPointer()); 2210 unsigned AS = Base->getType()->getPointerAddressSpace(); 2211 llvm::Type *PType = 2212 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 2213 CGBuilderTy &Builder = CGF.Builder; 2214 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2215 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 2216 2217 // Extract the fields we need, regardless of model. We'll apply them if we 2218 // have them. 2219 llvm::Value *FieldOffset = MemPtr; 2220 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 2221 llvm::Value *VBPtrOffset = nullptr; 2222 if (MemPtr->getType()->isStructTy()) { 2223 // We need to extract values. 2224 unsigned I = 0; 2225 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 2226 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 2227 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 2228 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 2229 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 2230 } 2231 2232 if (VirtualBaseAdjustmentOffset) { 2233 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset, 2234 VBPtrOffset); 2235 } 2236 2237 // Cast to char*. 2238 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 2239 2240 // Apply the offset, which we assume is non-null. 2241 llvm::Value *Addr = 2242 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 2243 2244 // Cast the address to the appropriate pointer type, adopting the address 2245 // space of the base pointer. 2246 return Builder.CreateBitCast(Addr, PType); 2247 } 2248 2249 static MSInheritanceAttr::Spelling 2250 getInheritanceFromMemptr(const MemberPointerType *MPT) { 2251 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel(); 2252 } 2253 2254 llvm::Value * 2255 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 2256 const CastExpr *E, 2257 llvm::Value *Src) { 2258 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 2259 E->getCastKind() == CK_BaseToDerivedMemberPointer || 2260 E->getCastKind() == CK_ReinterpretMemberPointer); 2261 2262 // Use constant emission if we can. 2263 if (isa<llvm::Constant>(Src)) 2264 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 2265 2266 // We may be adding or dropping fields from the member pointer, so we need 2267 // both types and the inheritance models of both records. 2268 const MemberPointerType *SrcTy = 2269 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 2270 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 2271 bool IsFunc = SrcTy->isMemberFunctionPointer(); 2272 2273 // If the classes use the same null representation, reinterpret_cast is a nop. 2274 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 2275 if (IsReinterpret && IsFunc) 2276 return Src; 2277 2278 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 2279 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 2280 if (IsReinterpret && 2281 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 2282 return Src; 2283 2284 CGBuilderTy &Builder = CGF.Builder; 2285 2286 // Branch past the conversion if Src is null. 2287 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 2288 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 2289 2290 // C++ 5.2.10p9: The null member pointer value is converted to the null member 2291 // pointer value of the destination type. 2292 if (IsReinterpret) { 2293 // For reinterpret casts, sema ensures that src and dst are both functions 2294 // or data and have the same size, which means the LLVM types should match. 2295 assert(Src->getType() == DstNull->getType()); 2296 return Builder.CreateSelect(IsNotNull, Src, DstNull); 2297 } 2298 2299 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 2300 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 2301 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 2302 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 2303 CGF.EmitBlock(ConvertBB); 2304 2305 // Decompose src. 2306 llvm::Value *FirstField = Src; 2307 llvm::Value *NonVirtualBaseAdjustment = nullptr; 2308 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 2309 llvm::Value *VBPtrOffset = nullptr; 2310 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel(); 2311 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 2312 // We need to extract values. 2313 unsigned I = 0; 2314 FirstField = Builder.CreateExtractValue(Src, I++); 2315 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 2316 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 2317 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 2318 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 2319 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 2320 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 2321 } 2322 2323 // For data pointers, we adjust the field offset directly. For functions, we 2324 // have a separate field. 2325 llvm::Constant *Adj = getMemberPointerAdjustment(E); 2326 if (Adj) { 2327 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 2328 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 2329 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 2330 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 2331 NVAdjustField = getZeroInt(); 2332 if (isDerivedToBase) 2333 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj"); 2334 else 2335 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj"); 2336 } 2337 2338 // FIXME PR15713: Support conversions through virtually derived classes. 2339 2340 // Recompose dst from the null struct and the adjusted fields from src. 2341 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel(); 2342 llvm::Value *Dst; 2343 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) { 2344 Dst = FirstField; 2345 } else { 2346 Dst = llvm::UndefValue::get(DstNull->getType()); 2347 unsigned Idx = 0; 2348 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 2349 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 2350 Dst = Builder.CreateInsertValue( 2351 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++); 2352 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 2353 Dst = Builder.CreateInsertValue( 2354 Dst, getValueOrZeroInt(VBPtrOffset), Idx++); 2355 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 2356 Dst = Builder.CreateInsertValue( 2357 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++); 2358 } 2359 Builder.CreateBr(ContinueBB); 2360 2361 // In the continuation, choose between DstNull and Dst. 2362 CGF.EmitBlock(ContinueBB); 2363 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 2364 Phi->addIncoming(DstNull, OriginalBB); 2365 Phi->addIncoming(Dst, ConvertBB); 2366 return Phi; 2367 } 2368 2369 llvm::Constant * 2370 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 2371 llvm::Constant *Src) { 2372 const MemberPointerType *SrcTy = 2373 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 2374 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 2375 2376 // If src is null, emit a new null for dst. We can't return src because dst 2377 // might have a new representation. 2378 if (MemberPointerConstantIsNull(SrcTy, Src)) 2379 return EmitNullMemberPointer(DstTy); 2380 2381 // We don't need to do anything for reinterpret_casts of non-null member 2382 // pointers. We should only get here when the two type representations have 2383 // the same size. 2384 if (E->getCastKind() == CK_ReinterpretMemberPointer) 2385 return Src; 2386 2387 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy); 2388 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy); 2389 2390 // Decompose src. 2391 llvm::Constant *FirstField = Src; 2392 llvm::Constant *NonVirtualBaseAdjustment = nullptr; 2393 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr; 2394 llvm::Constant *VBPtrOffset = nullptr; 2395 bool IsFunc = SrcTy->isMemberFunctionPointer(); 2396 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 2397 // We need to extract values. 2398 unsigned I = 0; 2399 FirstField = Src->getAggregateElement(I++); 2400 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 2401 NonVirtualBaseAdjustment = Src->getAggregateElement(I++); 2402 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 2403 VBPtrOffset = Src->getAggregateElement(I++); 2404 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 2405 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++); 2406 } 2407 2408 // For data pointers, we adjust the field offset directly. For functions, we 2409 // have a separate field. 2410 llvm::Constant *Adj = getMemberPointerAdjustment(E); 2411 if (Adj) { 2412 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 2413 llvm::Constant *&NVAdjustField = 2414 IsFunc ? NonVirtualBaseAdjustment : FirstField; 2415 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 2416 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 2417 NVAdjustField = getZeroInt(); 2418 if (IsDerivedToBase) 2419 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj); 2420 else 2421 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj); 2422 } 2423 2424 // FIXME PR15713: Support conversions through virtually derived classes. 2425 2426 // Recompose dst from the null struct and the adjusted fields from src. 2427 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) 2428 return FirstField; 2429 2430 llvm::SmallVector<llvm::Constant *, 4> Fields; 2431 Fields.push_back(FirstField); 2432 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 2433 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment)); 2434 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 2435 Fields.push_back(getConstantOrZeroInt(VBPtrOffset)); 2436 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 2437 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset)); 2438 return llvm::ConstantStruct::getAnon(Fields); 2439 } 2440 2441 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer( 2442 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This, 2443 llvm::Value *MemPtr, const MemberPointerType *MPT) { 2444 assert(MPT->isMemberFunctionPointer()); 2445 const FunctionProtoType *FPT = 2446 MPT->getPointeeType()->castAs<FunctionProtoType>(); 2447 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2448 llvm::FunctionType *FTy = 2449 CGM.getTypes().GetFunctionType( 2450 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 2451 CGBuilderTy &Builder = CGF.Builder; 2452 2453 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 2454 2455 // Extract the fields we need, regardless of model. We'll apply them if we 2456 // have them. 2457 llvm::Value *FunctionPointer = MemPtr; 2458 llvm::Value *NonVirtualBaseAdjustment = nullptr; 2459 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 2460 llvm::Value *VBPtrOffset = nullptr; 2461 if (MemPtr->getType()->isStructTy()) { 2462 // We need to extract values. 2463 unsigned I = 0; 2464 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 2465 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance)) 2466 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 2467 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 2468 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 2469 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 2470 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 2471 } 2472 2473 if (VirtualBaseAdjustmentOffset) { 2474 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset, 2475 VBPtrOffset); 2476 } 2477 2478 if (NonVirtualBaseAdjustment) { 2479 // Apply the adjustment and cast back to the original struct type. 2480 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 2481 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 2482 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 2483 } 2484 2485 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 2486 } 2487 2488 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 2489 return new MicrosoftCXXABI(CGM); 2490 } 2491 2492 // MS RTTI Overview: 2493 // The run time type information emitted by cl.exe contains 5 distinct types of 2494 // structures. Many of them reference each other. 2495 // 2496 // TypeInfo: Static classes that are returned by typeid. 2497 // 2498 // CompleteObjectLocator: Referenced by vftables. They contain information 2499 // required for dynamic casting, including OffsetFromTop. They also contain 2500 // a reference to the TypeInfo for the type and a reference to the 2501 // CompleteHierarchyDescriptor for the type. 2502 // 2503 // ClassHieararchyDescriptor: Contains information about a class hierarchy. 2504 // Used during dynamic_cast to walk a class hierarchy. References a base 2505 // class array and the size of said array. 2506 // 2507 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is 2508 // somewhat of a misnomer because the most derived class is also in the list 2509 // as well as multiple copies of virtual bases (if they occur multiple times 2510 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for 2511 // every path in the hierarchy, in pre-order depth first order. Note, we do 2512 // not declare a specific llvm type for BaseClassArray, it's merely an array 2513 // of BaseClassDescriptor pointers. 2514 // 2515 // BaseClassDescriptor: Contains information about a class in a class hierarchy. 2516 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that 2517 // BaseClassArray is. It contains information about a class within a 2518 // hierarchy such as: is this base is ambiguous and what is its offset in the 2519 // vbtable. The names of the BaseClassDescriptors have all of their fields 2520 // mangled into them so they can be aggressively deduplicated by the linker. 2521 2522 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) { 2523 StringRef MangledName("\01??_7type_info@@6B@"); 2524 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName)) 2525 return VTable; 2526 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 2527 /*Constant=*/true, 2528 llvm::GlobalVariable::ExternalLinkage, 2529 /*Initializer=*/nullptr, MangledName); 2530 } 2531 2532 namespace { 2533 2534 /// \brief A Helper struct that stores information about a class in a class 2535 /// hierarchy. The information stored in these structs struct is used during 2536 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors. 2537 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with 2538 // implicit depth first pre-order tree connectivity. getFirstChild and 2539 // getNextSibling allow us to walk the tree efficiently. 2540 struct MSRTTIClass { 2541 enum { 2542 IsPrivateOnPath = 1 | 8, 2543 IsAmbiguous = 2, 2544 IsPrivate = 4, 2545 IsVirtual = 16, 2546 HasHierarchyDescriptor = 64 2547 }; 2548 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {} 2549 uint32_t initialize(const MSRTTIClass *Parent, 2550 const CXXBaseSpecifier *Specifier); 2551 2552 MSRTTIClass *getFirstChild() { return this + 1; } 2553 static MSRTTIClass *getNextChild(MSRTTIClass *Child) { 2554 return Child + 1 + Child->NumBases; 2555 } 2556 2557 const CXXRecordDecl *RD, *VirtualRoot; 2558 uint32_t Flags, NumBases, OffsetInVBase; 2559 }; 2560 2561 /// \brief Recursively initialize the base class array. 2562 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent, 2563 const CXXBaseSpecifier *Specifier) { 2564 Flags = HasHierarchyDescriptor; 2565 if (!Parent) { 2566 VirtualRoot = nullptr; 2567 OffsetInVBase = 0; 2568 } else { 2569 if (Specifier->getAccessSpecifier() != AS_public) 2570 Flags |= IsPrivate | IsPrivateOnPath; 2571 if (Specifier->isVirtual()) { 2572 Flags |= IsVirtual; 2573 VirtualRoot = RD; 2574 OffsetInVBase = 0; 2575 } else { 2576 if (Parent->Flags & IsPrivateOnPath) 2577 Flags |= IsPrivateOnPath; 2578 VirtualRoot = Parent->VirtualRoot; 2579 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext() 2580 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity(); 2581 } 2582 } 2583 NumBases = 0; 2584 MSRTTIClass *Child = getFirstChild(); 2585 for (const CXXBaseSpecifier &Base : RD->bases()) { 2586 NumBases += Child->initialize(this, &Base) + 1; 2587 Child = getNextChild(Child); 2588 } 2589 return NumBases; 2590 } 2591 2592 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) { 2593 switch (Ty->getLinkage()) { 2594 case NoLinkage: 2595 case InternalLinkage: 2596 case UniqueExternalLinkage: 2597 return llvm::GlobalValue::InternalLinkage; 2598 2599 case VisibleNoLinkage: 2600 case ExternalLinkage: 2601 return llvm::GlobalValue::LinkOnceODRLinkage; 2602 } 2603 llvm_unreachable("Invalid linkage!"); 2604 } 2605 2606 /// \brief An ephemeral helper class for building MS RTTI types. It caches some 2607 /// calls to the module and information about the most derived class in a 2608 /// hierarchy. 2609 struct MSRTTIBuilder { 2610 enum { 2611 HasBranchingHierarchy = 1, 2612 HasVirtualBranchingHierarchy = 2, 2613 HasAmbiguousBases = 4 2614 }; 2615 2616 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD) 2617 : CGM(ABI.CGM), Context(CGM.getContext()), 2618 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD), 2619 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))), 2620 ABI(ABI) {} 2621 2622 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes); 2623 llvm::GlobalVariable * 2624 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes); 2625 llvm::GlobalVariable *getClassHierarchyDescriptor(); 2626 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info); 2627 2628 CodeGenModule &CGM; 2629 ASTContext &Context; 2630 llvm::LLVMContext &VMContext; 2631 llvm::Module &Module; 2632 const CXXRecordDecl *RD; 2633 llvm::GlobalVariable::LinkageTypes Linkage; 2634 MicrosoftCXXABI &ABI; 2635 }; 2636 2637 } // namespace 2638 2639 /// \brief Recursively serializes a class hierarchy in pre-order depth first 2640 /// order. 2641 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes, 2642 const CXXRecordDecl *RD) { 2643 Classes.push_back(MSRTTIClass(RD)); 2644 for (const CXXBaseSpecifier &Base : RD->bases()) 2645 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl()); 2646 } 2647 2648 /// \brief Find ambiguity among base classes. 2649 static void 2650 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) { 2651 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases; 2652 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases; 2653 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases; 2654 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) { 2655 if ((Class->Flags & MSRTTIClass::IsVirtual) && 2656 !VirtualBases.insert(Class->RD)) { 2657 Class = MSRTTIClass::getNextChild(Class); 2658 continue; 2659 } 2660 if (!UniqueBases.insert(Class->RD)) 2661 AmbiguousBases.insert(Class->RD); 2662 Class++; 2663 } 2664 if (AmbiguousBases.empty()) 2665 return; 2666 for (MSRTTIClass &Class : Classes) 2667 if (AmbiguousBases.count(Class.RD)) 2668 Class.Flags |= MSRTTIClass::IsAmbiguous; 2669 } 2670 2671 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() { 2672 SmallString<256> MangledName; 2673 { 2674 llvm::raw_svector_ostream Out(MangledName); 2675 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out); 2676 } 2677 2678 // Check to see if we've already declared this ClassHierarchyDescriptor. 2679 if (auto CHD = Module.getNamedGlobal(MangledName)) 2680 return CHD; 2681 2682 // Serialize the class hierarchy and initialize the CHD Fields. 2683 SmallVector<MSRTTIClass, 8> Classes; 2684 serializeClassHierarchy(Classes, RD); 2685 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr); 2686 detectAmbiguousBases(Classes); 2687 int Flags = 0; 2688 for (auto Class : Classes) { 2689 if (Class.RD->getNumBases() > 1) 2690 Flags |= HasBranchingHierarchy; 2691 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We 2692 // believe the field isn't actually used. 2693 if (Class.Flags & MSRTTIClass::IsAmbiguous) 2694 Flags |= HasAmbiguousBases; 2695 } 2696 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0) 2697 Flags |= HasVirtualBranchingHierarchy; 2698 // These gep indices are used to get the address of the first element of the 2699 // base class array. 2700 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0), 2701 llvm::ConstantInt::get(CGM.IntTy, 0)}; 2702 2703 // Forward-declare the class hierarchy descriptor 2704 auto Type = ABI.getClassHierarchyDescriptorType(); 2705 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage, 2706 /*Initializer=*/nullptr, 2707 MangledName.c_str()); 2708 2709 // Initialize the base class ClassHierarchyDescriptor. 2710 llvm::Constant *Fields[] = { 2711 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown 2712 llvm::ConstantInt::get(CGM.IntTy, Flags), 2713 llvm::ConstantInt::get(CGM.IntTy, Classes.size()), 2714 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr( 2715 getBaseClassArray(Classes), 2716 llvm::ArrayRef<llvm::Value *>(GEPIndices))), 2717 }; 2718 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 2719 return CHD; 2720 } 2721 2722 llvm::GlobalVariable * 2723 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) { 2724 SmallString<256> MangledName; 2725 { 2726 llvm::raw_svector_ostream Out(MangledName); 2727 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out); 2728 } 2729 2730 // Forward-declare the base class array. 2731 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit 2732 // mode) bytes of padding. We provide a pointer sized amount of padding by 2733 // adding +1 to Classes.size(). The sections have pointer alignment and are 2734 // marked pick-any so it shouldn't matter. 2735 llvm::Type *PtrType = ABI.getImageRelativeType( 2736 ABI.getBaseClassDescriptorType()->getPointerTo()); 2737 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1); 2738 auto *BCA = new llvm::GlobalVariable( 2739 Module, ArrType, 2740 /*Constant=*/true, Linkage, /*Initializer=*/nullptr, MangledName.c_str()); 2741 2742 // Initialize the BaseClassArray. 2743 SmallVector<llvm::Constant *, 8> BaseClassArrayData; 2744 for (MSRTTIClass &Class : Classes) 2745 BaseClassArrayData.push_back( 2746 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class))); 2747 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType)); 2748 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData)); 2749 return BCA; 2750 } 2751 2752 llvm::GlobalVariable * 2753 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) { 2754 // Compute the fields for the BaseClassDescriptor. They are computed up front 2755 // because they are mangled into the name of the object. 2756 uint32_t OffsetInVBTable = 0; 2757 int32_t VBPtrOffset = -1; 2758 if (Class.VirtualRoot) { 2759 auto &VTableContext = CGM.getMicrosoftVTableContext(); 2760 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4; 2761 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity(); 2762 } 2763 2764 SmallString<256> MangledName; 2765 { 2766 llvm::raw_svector_ostream Out(MangledName); 2767 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor( 2768 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable, 2769 Class.Flags, Out); 2770 } 2771 2772 // Check to see if we've already declared this object. 2773 if (auto BCD = Module.getNamedGlobal(MangledName)) 2774 return BCD; 2775 2776 // Forward-declare the base class descriptor. 2777 auto Type = ABI.getBaseClassDescriptorType(); 2778 auto BCD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage, 2779 /*Initializer=*/nullptr, 2780 MangledName.c_str()); 2781 2782 // Initialize the BaseClassDescriptor. 2783 llvm::Constant *Fields[] = { 2784 ABI.getImageRelativeConstant( 2785 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))), 2786 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases), 2787 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase), 2788 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 2789 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable), 2790 llvm::ConstantInt::get(CGM.IntTy, Class.Flags), 2791 ABI.getImageRelativeConstant( 2792 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()), 2793 }; 2794 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 2795 return BCD; 2796 } 2797 2798 llvm::GlobalVariable * 2799 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) { 2800 SmallString<256> MangledName; 2801 { 2802 llvm::raw_svector_ostream Out(MangledName); 2803 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out); 2804 } 2805 2806 // Check to see if we've already computed this complete object locator. 2807 if (auto COL = Module.getNamedGlobal(MangledName)) 2808 return COL; 2809 2810 // Compute the fields of the complete object locator. 2811 int OffsetToTop = Info->FullOffsetInMDC.getQuantity(); 2812 int VFPtrOffset = 0; 2813 // The offset includes the vtordisp if one exists. 2814 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr()) 2815 if (Context.getASTRecordLayout(RD) 2816 .getVBaseOffsetsMap() 2817 .find(VBase) 2818 ->second.hasVtorDisp()) 2819 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4; 2820 2821 // Forward-declare the complete object locator. 2822 llvm::StructType *Type = ABI.getCompleteObjectLocatorType(); 2823 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage, 2824 /*Initializer=*/nullptr, MangledName.c_str()); 2825 2826 // Initialize the CompleteObjectLocator. 2827 llvm::Constant *Fields[] = { 2828 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()), 2829 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop), 2830 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset), 2831 ABI.getImageRelativeConstant( 2832 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))), 2833 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()), 2834 ABI.getImageRelativeConstant(COL), 2835 }; 2836 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields); 2837 if (!ABI.isImageRelative()) 2838 FieldsRef = FieldsRef.drop_back(); 2839 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef)); 2840 return COL; 2841 } 2842 2843 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a 2844 /// llvm::GlobalVariable * because different type descriptors have different 2845 /// types, and need to be abstracted. They are abstracting by casting the 2846 /// address to an Int8PtrTy. 2847 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) { 2848 SmallString<256> MangledName, TypeInfoString; 2849 { 2850 llvm::raw_svector_ostream Out(MangledName); 2851 getMangleContext().mangleCXXRTTI(Type, Out); 2852 } 2853 2854 // Check to see if we've already declared this TypeDescriptor. 2855 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 2856 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2857 2858 // Compute the fields for the TypeDescriptor. 2859 { 2860 llvm::raw_svector_ostream Out(TypeInfoString); 2861 getMangleContext().mangleCXXRTTIName(Type, Out); 2862 } 2863 2864 // Declare and initialize the TypeDescriptor. 2865 llvm::Constant *Fields[] = { 2866 getTypeInfoVTable(CGM), // VFPtr 2867 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data 2868 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)}; 2869 llvm::StructType *TypeDescriptorType = 2870 getTypeDescriptorType(TypeInfoString); 2871 return llvm::ConstantExpr::getBitCast( 2872 new llvm::GlobalVariable( 2873 CGM.getModule(), TypeDescriptorType, /*Constant=*/false, 2874 getLinkageForRTTI(Type), 2875 llvm::ConstantStruct::get(TypeDescriptorType, Fields), 2876 MangledName.c_str()), 2877 CGM.Int8PtrTy); 2878 } 2879 2880 /// \brief Gets or a creates a Microsoft CompleteObjectLocator. 2881 llvm::GlobalVariable * 2882 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD, 2883 const VPtrInfo *Info) { 2884 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info); 2885 } 2886 2887 static void emitCXXConstructor(CodeGenModule &CGM, 2888 const CXXConstructorDecl *ctor, 2889 StructorType ctorType) { 2890 // There are no constructor variants, always emit the complete destructor. 2891 CGM.codegenCXXStructor(ctor, StructorType::Complete); 2892 } 2893 2894 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor, 2895 StructorType dtorType) { 2896 // The complete destructor is equivalent to the base destructor for 2897 // classes with no virtual bases, so try to emit it as an alias. 2898 if (!dtor->getParent()->getNumVBases() && 2899 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) { 2900 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias( 2901 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true); 2902 if (ProducedAlias) { 2903 if (dtorType == StructorType::Complete) 2904 return; 2905 if (dtor->isVirtual()) 2906 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete)); 2907 } 2908 } 2909 2910 // The base destructor is equivalent to the base destructor of its 2911 // base class if there is exactly one non-virtual base class with a 2912 // non-trivial destructor, there are no fields with a non-trivial 2913 // destructor, and the body of the destructor is trivial. 2914 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor)) 2915 return; 2916 2917 CGM.codegenCXXStructor(dtor, dtorType); 2918 } 2919 2920 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 2921 StructorType Type) { 2922 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 2923 emitCXXConstructor(CGM, CD, Type); 2924 return; 2925 } 2926 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type); 2927 } 2928