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