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/StringSet.h" 24 25 using namespace clang; 26 using namespace CodeGen; 27 28 namespace { 29 30 /// Holds all the vbtable globals for a given class. 31 struct VBTableGlobals { 32 const VBTableVector *VBTables; 33 SmallVector<llvm::GlobalVariable *, 2> Globals; 34 }; 35 36 class MicrosoftCXXABI : public CGCXXABI { 37 public: 38 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {} 39 40 bool HasThisReturn(GlobalDecl GD) const; 41 42 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const { 43 // Structures that are not C++03 PODs are always indirect. 44 return !RD->isPOD(); 45 } 46 47 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const { 48 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor()) { 49 llvm::Triple::ArchType Arch = CGM.getTarget().getTriple().getArch(); 50 if (Arch == llvm::Triple::x86) 51 return RAA_DirectInMemory; 52 // On x64, pass non-trivial records indirectly. 53 // FIXME: Test other Windows architectures. 54 return RAA_Indirect; 55 } 56 return RAA_Default; 57 } 58 59 StringRef GetPureVirtualCallName() { return "_purecall"; } 60 // No known support for deleted functions in MSVC yet, so this choice is 61 // arbitrary. 62 StringRef GetDeletedVirtualCallName() { return "_purecall"; } 63 64 bool isInlineInitializedStaticDataMemberLinkOnce() { return true; } 65 66 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 67 llvm::Value *ptr, 68 QualType type); 69 70 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF, 71 llvm::Value *This, 72 const CXXRecordDecl *ClassDecl, 73 const CXXRecordDecl *BaseClassDecl); 74 75 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 76 CXXCtorType Type, 77 CanQualType &ResTy, 78 SmallVectorImpl<CanQualType> &ArgTys); 79 80 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 81 const CXXRecordDecl *RD); 82 83 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, 84 const CXXRecordDecl *RD); 85 86 void EmitCXXConstructors(const CXXConstructorDecl *D); 87 88 // Background on MSVC destructors 89 // ============================== 90 // 91 // Both Itanium and MSVC ABIs have destructor variants. The variant names 92 // roughly correspond in the following way: 93 // Itanium Microsoft 94 // Base -> no name, just ~Class 95 // Complete -> vbase destructor 96 // Deleting -> scalar deleting destructor 97 // vector deleting destructor 98 // 99 // The base and complete destructors are the same as in Itanium, although the 100 // complete destructor does not accept a VTT parameter when there are virtual 101 // bases. A separate mechanism involving vtordisps is used to ensure that 102 // virtual methods of destroyed subobjects are not called. 103 // 104 // The deleting destructors accept an i32 bitfield as a second parameter. Bit 105 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this 106 // pointer points to an array. The scalar deleting destructor assumes that 107 // bit 2 is zero, and therefore does not contain a loop. 108 // 109 // For virtual destructors, only one entry is reserved in the vftable, and it 110 // always points to the vector deleting destructor. The vector deleting 111 // destructor is the most general, so it can be used to destroy objects in 112 // place, delete single heap objects, or delete arrays. 113 // 114 // A TU defining a non-inline destructor is only guaranteed to emit a base 115 // destructor, and all of the other variants are emitted on an as-needed basis 116 // in COMDATs. Because a non-base destructor can be emitted in a TU that 117 // lacks a definition for the destructor, non-base destructors must always 118 // delegate to or alias the base destructor. 119 120 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 121 CXXDtorType Type, 122 CanQualType &ResTy, 123 SmallVectorImpl<CanQualType> &ArgTys); 124 125 /// Non-base dtors should be emitted as delegating thunks in this ABI. 126 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 127 CXXDtorType DT) const { 128 return DT != Dtor_Base; 129 } 130 131 void EmitCXXDestructors(const CXXDestructorDecl *D); 132 133 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) { 134 MD = MD->getCanonicalDecl(); 135 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { 136 MicrosoftVTableContext::MethodVFTableLocation ML = 137 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 138 // The vbases might be ordered differently in the final overrider object 139 // and the complete object, so the "this" argument may sometimes point to 140 // memory that has no particular type (e.g. past the complete object). 141 // In this case, we just use a generic pointer type. 142 // FIXME: might want to have a more precise type in the non-virtual 143 // multiple inheritance case. 144 if (ML.VBase || !ML.VFPtrOffset.isZero()) 145 return 0; 146 } 147 return MD->getParent(); 148 } 149 150 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF, 151 GlobalDecl GD, 152 llvm::Value *This); 153 154 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 155 FunctionArgList &Params); 156 157 llvm::Value *adjustThisParameterInVirtualFunctionPrologue( 158 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This); 159 160 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 161 162 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 163 const CXXConstructorDecl *D, 164 CXXCtorType Type, bool ForVirtualBase, 165 bool Delegating, CallArgList &Args); 166 167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 168 CXXDtorType Type, bool ForVirtualBase, 169 bool Delegating, llvm::Value *This); 170 171 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD); 172 173 llvm::Value *getVTableAddressPointInStructor( 174 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 175 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 176 bool &NeedsVirtualOffset); 177 178 llvm::Constant * 179 getVTableAddressPointForConstExpr(BaseSubobject Base, 180 const CXXRecordDecl *VTableClass); 181 182 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 183 CharUnits VPtrOffset); 184 185 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 186 llvm::Value *This, llvm::Type *Ty); 187 188 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 189 const CXXDestructorDecl *Dtor, 190 CXXDtorType DtorType, SourceLocation CallLoc, 191 llvm::Value *This); 192 193 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, 194 CallArgList &CallArgs) { 195 assert(GD.getDtorType() == Dtor_Deleting && 196 "Only deleting destructor thunks are available in this ABI"); 197 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)), 198 CGM.getContext().IntTy); 199 } 200 201 void emitVirtualInheritanceTables(const CXXRecordDecl *RD); 202 203 llvm::GlobalVariable * 204 getAddrOfVBTable(const VBTableInfo &VBT, const CXXRecordDecl *RD, 205 llvm::GlobalVariable::LinkageTypes Linkage); 206 207 void emitVBTableDefinition(const VBTableInfo &VBT, const CXXRecordDecl *RD, 208 llvm::GlobalVariable *GV) const; 209 210 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) { 211 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage); 212 } 213 214 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 215 const ThisAdjustment &TA); 216 217 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 218 const ReturnAdjustment &RA); 219 220 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 221 llvm::GlobalVariable *DeclPtr, 222 bool PerformInit); 223 224 // ==== Notes on array cookies ========= 225 // 226 // MSVC seems to only use cookies when the class has a destructor; a 227 // two-argument usual array deallocation function isn't sufficient. 228 // 229 // For example, this code prints "100" and "1": 230 // struct A { 231 // char x; 232 // void *operator new[](size_t sz) { 233 // printf("%u\n", sz); 234 // return malloc(sz); 235 // } 236 // void operator delete[](void *p, size_t sz) { 237 // printf("%u\n", sz); 238 // free(p); 239 // } 240 // }; 241 // int main() { 242 // A *p = new A[100]; 243 // delete[] p; 244 // } 245 // Whereas it prints "104" and "104" if you give A a destructor. 246 247 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType); 248 bool requiresArrayCookie(const CXXNewExpr *expr); 249 CharUnits getArrayCookieSizeImpl(QualType type); 250 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 251 llvm::Value *NewPtr, 252 llvm::Value *NumElements, 253 const CXXNewExpr *expr, 254 QualType ElementType); 255 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 256 llvm::Value *allocPtr, 257 CharUnits cookieSize); 258 259 private: 260 MicrosoftMangleContext &getMangleContext() { 261 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 262 } 263 264 llvm::Constant *getZeroInt() { 265 return llvm::ConstantInt::get(CGM.IntTy, 0); 266 } 267 268 llvm::Constant *getAllOnesInt() { 269 return llvm::Constant::getAllOnesValue(CGM.IntTy); 270 } 271 272 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) { 273 return C ? C : getZeroInt(); 274 } 275 276 llvm::Value *getValueOrZeroInt(llvm::Value *C) { 277 return C ? C : getZeroInt(); 278 } 279 280 void 281 GetNullMemberPointerFields(const MemberPointerType *MPT, 282 llvm::SmallVectorImpl<llvm::Constant *> &fields); 283 284 /// \brief Shared code for virtual base adjustment. Returns the offset from 285 /// the vbptr to the virtual base. Optionally returns the address of the 286 /// vbptr itself. 287 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 288 llvm::Value *Base, 289 llvm::Value *VBPtrOffset, 290 llvm::Value *VBTableOffset, 291 llvm::Value **VBPtr = 0); 292 293 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 294 llvm::Value *Base, 295 int32_t VBPtrOffset, 296 int32_t VBTableOffset, 297 llvm::Value **VBPtr = 0) { 298 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 299 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset); 300 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr); 301 } 302 303 /// \brief Performs a full virtual base adjustment. Used to dereference 304 /// pointers to members of virtual bases. 305 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD, 306 llvm::Value *Base, 307 llvm::Value *VirtualBaseAdjustmentOffset, 308 llvm::Value *VBPtrOffset /* optional */); 309 310 /// \brief Emits a full member pointer with the fields common to data and 311 /// function member pointers. 312 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField, 313 bool IsMemberFunction, 314 const CXXRecordDecl *RD, 315 CharUnits NonVirtualBaseAdjustment); 316 317 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD, 318 const CXXMethodDecl *MD, 319 CharUnits NonVirtualBaseAdjustment); 320 321 bool MemberPointerConstantIsNull(const MemberPointerType *MPT, 322 llvm::Constant *MP); 323 324 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type. 325 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD); 326 327 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables(). 328 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD); 329 330 /// \brief Generate a thunk for calling a virtual member function MD. 331 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD, 332 StringRef ThunkName); 333 334 public: 335 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 336 337 virtual bool isZeroInitializable(const MemberPointerType *MPT); 338 339 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 340 341 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 342 CharUnits offset); 343 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 344 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT); 345 346 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 347 llvm::Value *L, 348 llvm::Value *R, 349 const MemberPointerType *MPT, 350 bool Inequality); 351 352 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 353 llvm::Value *MemPtr, 354 const MemberPointerType *MPT); 355 356 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 357 llvm::Value *Base, 358 llvm::Value *MemPtr, 359 const MemberPointerType *MPT); 360 361 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 362 const CastExpr *E, 363 llvm::Value *Src); 364 365 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 366 llvm::Constant *Src); 367 368 virtual llvm::Value * 369 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 370 llvm::Value *&This, 371 llvm::Value *MemPtr, 372 const MemberPointerType *MPT); 373 374 private: 375 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy; 376 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy; 377 /// \brief All the vftables that have been referenced. 378 VFTablesMapTy VFTablesMap; 379 380 /// \brief This set holds the record decls we've deferred vtable emission for. 381 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables; 382 383 384 /// \brief All the vbtables which have been referenced. 385 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap; 386 387 /// Info on the global variable used to guard initialization of static locals. 388 /// The BitIndex field is only used for externally invisible declarations. 389 struct GuardInfo { 390 GuardInfo() : Guard(0), BitIndex(0) {} 391 llvm::GlobalVariable *Guard; 392 unsigned BitIndex; 393 }; 394 395 /// Map from DeclContext to the current guard variable. We assume that the 396 /// AST is visited in source code order. 397 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap; 398 }; 399 400 } 401 402 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 403 llvm::Value *ptr, 404 QualType type) { 405 // FIXME: implement 406 return ptr; 407 } 408 409 llvm::Value * 410 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 411 llvm::Value *This, 412 const CXXRecordDecl *ClassDecl, 413 const CXXRecordDecl *BaseClassDecl) { 414 int64_t VBPtrChars = 415 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity(); 416 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars); 417 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy); 418 CharUnits VBTableChars = 419 IntSize * 420 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl); 421 llvm::Value *VBTableOffset = 422 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity()); 423 424 llvm::Value *VBPtrToNewBase = 425 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset); 426 VBPtrToNewBase = 427 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy); 428 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase); 429 } 430 431 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const { 432 return isa<CXXConstructorDecl>(GD.getDecl()); 433 } 434 435 void MicrosoftCXXABI::BuildConstructorSignature( 436 const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy, 437 SmallVectorImpl<CanQualType> &ArgTys) { 438 439 // All parameters are already in place except is_most_derived, which goes 440 // after 'this' if it's variadic and last if it's not. 441 442 const CXXRecordDecl *Class = Ctor->getParent(); 443 const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>(); 444 if (Class->getNumVBases()) { 445 if (FPT->isVariadic()) 446 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy); 447 else 448 ArgTys.push_back(CGM.getContext().IntTy); 449 } 450 } 451 452 llvm::BasicBlock * 453 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 454 const CXXRecordDecl *RD) { 455 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 456 assert(IsMostDerivedClass && 457 "ctor for a class with virtual bases must have an implicit parameter"); 458 llvm::Value *IsCompleteObject = 459 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 460 461 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 462 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 463 CGF.Builder.CreateCondBr(IsCompleteObject, 464 CallVbaseCtorsBB, SkipVbaseCtorsBB); 465 466 CGF.EmitBlock(CallVbaseCtorsBB); 467 468 // Fill in the vbtable pointers here. 469 EmitVBPtrStores(CGF, RD); 470 471 // CGF will put the base ctor calls in this basic block for us later. 472 473 return SkipVbaseCtorsBB; 474 } 475 476 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers( 477 CodeGenFunction &CGF, const CXXRecordDecl *RD) { 478 // In most cases, an override for a vbase virtual method can adjust 479 // the "this" parameter by applying a constant offset. 480 // However, this is not enough while a constructor or a destructor of some 481 // class X is being executed if all the following conditions are met: 482 // - X has virtual bases, (1) 483 // - X overrides a virtual method M of a vbase Y, (2) 484 // - X itself is a vbase of the most derived class. 485 // 486 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X 487 // which holds the extra amount of "this" adjustment we must do when we use 488 // the X vftables (i.e. during X ctor or dtor). 489 // Outside the ctors and dtors, the values of vtorDisps are zero. 490 491 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 492 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets; 493 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap(); 494 CGBuilderTy &Builder = CGF.Builder; 495 496 unsigned AS = 497 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace(); 498 llvm::Value *Int8This = 0; // Initialize lazily. 499 500 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end(); 501 I != E; ++I) { 502 if (!I->second.hasVtorDisp()) 503 continue; 504 505 llvm::Value *VBaseOffset = 506 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first); 507 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset() 508 // just to Trunc back immediately. 509 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty); 510 uint64_t ConstantVBaseOffset = 511 Layout.getVBaseClassOffset(I->first).getQuantity(); 512 513 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase). 514 llvm::Value *VtorDispValue = Builder.CreateSub( 515 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset), 516 "vtordisp.value"); 517 518 if (!Int8This) 519 Int8This = Builder.CreateBitCast(getThisValue(CGF), 520 CGF.Int8Ty->getPointerTo(AS)); 521 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset); 522 // vtorDisp is always the 32-bits before the vbase in the class layout. 523 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4); 524 VtorDispPtr = Builder.CreateBitCast( 525 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr"); 526 527 Builder.CreateStore(VtorDispValue, VtorDispPtr); 528 } 529 } 530 531 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 532 // There's only one constructor type in this ABI. 533 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 534 } 535 536 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF, 537 const CXXRecordDecl *RD) { 538 llvm::Value *ThisInt8Ptr = 539 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8"); 540 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 541 542 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 543 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 544 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I]; 545 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 546 const ASTRecordLayout &SubobjectLayout = 547 CGM.getContext().getASTRecordLayout(VBT->BaseWithVBPtr); 548 CharUnits Offs = VBT->NonVirtualOffset; 549 Offs += SubobjectLayout.getVBPtrOffset(); 550 if (VBT->getVBaseWithVBPtr()) 551 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVBPtr()); 552 llvm::Value *VBPtr = 553 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity()); 554 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0), 555 "vbptr." + VBT->ReusingBase->getName()); 556 CGF.Builder.CreateStore(GV, VBPtr); 557 } 558 } 559 560 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 561 CXXDtorType Type, 562 CanQualType &ResTy, 563 SmallVectorImpl<CanQualType> &ArgTys) { 564 // 'this' is already in place 565 566 // TODO: 'for base' flag 567 568 if (Type == Dtor_Deleting) { 569 // The scalar deleting destructor takes an implicit int parameter. 570 ArgTys.push_back(CGM.getContext().IntTy); 571 } 572 } 573 574 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 575 // The TU defining a dtor is only guaranteed to emit a base destructor. All 576 // other destructor variants are delegating thunks. 577 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 578 } 579 580 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall( 581 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 582 GD = GD.getCanonicalDecl(); 583 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 584 // FIXME: consider splitting the vdtor vs regular method code into two 585 // functions. 586 587 GlobalDecl LookupGD = GD; 588 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 589 // Complete dtors take a pointer to the complete object, 590 // thus don't need adjustment. 591 if (GD.getDtorType() == Dtor_Complete) 592 return This; 593 594 // There's only Dtor_Deleting in vftable but it shares the this adjustment 595 // with the base one, so look up the deleting one instead. 596 LookupGD = GlobalDecl(DD, Dtor_Deleting); 597 } 598 MicrosoftVTableContext::MethodVFTableLocation ML = 599 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 600 601 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 602 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 603 CharUnits StaticOffset = ML.VFPtrOffset; 604 605 // Base destructors expect 'this' to point to the beginning of the base 606 // subobject, not the first vfptr that happens to contain the virtual dtor. 607 // However, we still need to apply the virtual base adjustment. 608 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 609 StaticOffset = CharUnits::Zero(); 610 611 if (ML.VBase) { 612 bool AvoidVirtualOffset = false; 613 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) { 614 // A base destructor can only be called from a complete destructor of the 615 // same record type or another destructor of a more derived type; 616 // or a constructor of the same record type if an exception is thrown. 617 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) || 618 isa<CXXConstructorDecl>(CGF.CurGD.getDecl())); 619 const CXXRecordDecl *CurRD = 620 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent(); 621 622 if (MD->getParent() == CurRD) { 623 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 624 assert(CGF.CurGD.getDtorType() == Dtor_Complete); 625 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl())) 626 assert(CGF.CurGD.getCtorType() == Ctor_Complete); 627 // We're calling the main base dtor from a complete structor, 628 // so we know the "this" offset statically. 629 AvoidVirtualOffset = true; 630 } else { 631 // Let's see if we try to call a destructor of a non-virtual base. 632 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(), 633 E = CurRD->bases_end(); I != E; ++I) { 634 if (I->getType()->getAsCXXRecordDecl() != MD->getParent()) 635 continue; 636 // If we call a base destructor for a non-virtual base, we statically 637 // know where it expects the vfptr and "this" to be. 638 // The total offset should reflect the adjustment done by 639 // adjustThisParameterInVirtualFunctionPrologue(). 640 AvoidVirtualOffset = true; 641 break; 642 } 643 } 644 } 645 646 if (AvoidVirtualOffset) { 647 const ASTRecordLayout &Layout = 648 CGF.getContext().getASTRecordLayout(MD->getParent()); 649 StaticOffset += Layout.getVBaseClassOffset(ML.VBase); 650 } else { 651 This = CGF.Builder.CreateBitCast(This, charPtrTy); 652 llvm::Value *VBaseOffset = 653 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase); 654 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset); 655 } 656 } 657 if (!StaticOffset.isZero()) { 658 assert(StaticOffset.isPositive()); 659 This = CGF.Builder.CreateBitCast(This, charPtrTy); 660 if (ML.VBase) { 661 // Non-virtual adjustment might result in a pointer outside the allocated 662 // object, e.g. if the final overrider class is laid out after the virtual 663 // base that declares a method in the most derived class. 664 // FIXME: Update the code that emits this adjustment in thunks prologues. 665 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity()); 666 } else { 667 This = CGF.Builder.CreateConstInBoundsGEP1_32(This, 668 StaticOffset.getQuantity()); 669 } 670 } 671 return This; 672 } 673 674 static bool IsDeletingDtor(GlobalDecl GD) { 675 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl()); 676 if (isa<CXXDestructorDecl>(MD)) { 677 return GD.getDtorType() == Dtor_Deleting; 678 } 679 return false; 680 } 681 682 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 683 QualType &ResTy, 684 FunctionArgList &Params) { 685 ASTContext &Context = getContext(); 686 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 687 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 688 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 689 ImplicitParamDecl *IsMostDerived 690 = ImplicitParamDecl::Create(Context, 0, 691 CGF.CurGD.getDecl()->getLocation(), 692 &Context.Idents.get("is_most_derived"), 693 Context.IntTy); 694 // The 'most_derived' parameter goes second if the ctor is variadic and last 695 // if it's not. Dtors can't be variadic. 696 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 697 if (FPT->isVariadic()) 698 Params.insert(Params.begin() + 1, IsMostDerived); 699 else 700 Params.push_back(IsMostDerived); 701 getStructorImplicitParamDecl(CGF) = IsMostDerived; 702 } else if (IsDeletingDtor(CGF.CurGD)) { 703 ImplicitParamDecl *ShouldDelete 704 = ImplicitParamDecl::Create(Context, 0, 705 CGF.CurGD.getDecl()->getLocation(), 706 &Context.Idents.get("should_call_delete"), 707 Context.IntTy); 708 Params.push_back(ShouldDelete); 709 getStructorImplicitParamDecl(CGF) = ShouldDelete; 710 } 711 } 712 713 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue( 714 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 715 GD = GD.getCanonicalDecl(); 716 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 717 718 GlobalDecl LookupGD = GD; 719 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 720 // Complete destructors take a pointer to the complete object as a 721 // parameter, thus don't need this adjustment. 722 if (GD.getDtorType() == Dtor_Complete) 723 return This; 724 725 // There's no Dtor_Base in vftable but it shares the this adjustment with 726 // the deleting one, so look it up instead. 727 LookupGD = GlobalDecl(DD, Dtor_Deleting); 728 } 729 730 // In this ABI, every virtual function takes a pointer to one of the 731 // subobjects that first defines it as the 'this' parameter, rather than a 732 // pointer to the final overrider subobject. Thus, we need to adjust it back 733 // to the final overrider subobject before use. 734 // See comments in the MicrosoftVFTableContext implementation for the details. 735 736 MicrosoftVTableContext::MethodVFTableLocation ML = 737 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 738 CharUnits Adjustment = ML.VFPtrOffset; 739 740 // Normal virtual instance methods need to adjust from the vfptr that first 741 // defined the virtual method to the virtual base subobject, but destructors 742 // do not. The vector deleting destructor thunk applies this adjustment for 743 // us if necessary. 744 if (isa<CXXDestructorDecl>(MD)) 745 Adjustment = CharUnits::Zero(); 746 747 if (ML.VBase) { 748 const ASTRecordLayout &DerivedLayout = 749 CGF.getContext().getASTRecordLayout(MD->getParent()); 750 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 751 } 752 753 if (Adjustment.isZero()) 754 return This; 755 756 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 757 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 758 *thisTy = This->getType(); 759 760 This = CGF.Builder.CreateBitCast(This, charPtrTy); 761 assert(Adjustment.isPositive()); 762 This = 763 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity()); 764 return CGF.Builder.CreateBitCast(This, thisTy); 765 } 766 767 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 768 EmitThisParam(CGF); 769 770 /// If this is a function that the ABI specifies returns 'this', initialize 771 /// the return slot to 'this' at the start of the function. 772 /// 773 /// Unlike the setting of return types, this is done within the ABI 774 /// implementation instead of by clients of CGCXXABI because: 775 /// 1) getThisValue is currently protected 776 /// 2) in theory, an ABI could implement 'this' returns some other way; 777 /// HasThisReturn only specifies a contract, not the implementation 778 if (HasThisReturn(CGF.CurGD)) 779 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 780 781 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 782 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 783 assert(getStructorImplicitParamDecl(CGF) && 784 "no implicit parameter for a constructor with virtual bases?"); 785 getStructorImplicitParamValue(CGF) 786 = CGF.Builder.CreateLoad( 787 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 788 "is_most_derived"); 789 } 790 791 if (IsDeletingDtor(CGF.CurGD)) { 792 assert(getStructorImplicitParamDecl(CGF) && 793 "no implicit parameter for a deleting destructor?"); 794 getStructorImplicitParamValue(CGF) 795 = CGF.Builder.CreateLoad( 796 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 797 "should_call_delete"); 798 } 799 } 800 801 unsigned MicrosoftCXXABI::addImplicitConstructorArgs( 802 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 803 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 804 assert(Type == Ctor_Complete || Type == Ctor_Base); 805 806 // Check if we need a 'most_derived' parameter. 807 if (!D->getParent()->getNumVBases()) 808 return 0; 809 810 // Add the 'most_derived' argument second if we are variadic or last if not. 811 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 812 llvm::Value *MostDerivedArg = 813 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 814 RValue RV = RValue::get(MostDerivedArg); 815 if (MostDerivedArg) { 816 if (FPT->isVariadic()) 817 Args.insert(Args.begin() + 1, 818 CallArg(RV, getContext().IntTy, /*needscopy=*/false)); 819 else 820 Args.add(RV, getContext().IntTy); 821 } 822 823 return 1; // Added one arg. 824 } 825 826 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 827 const CXXDestructorDecl *DD, 828 CXXDtorType Type, bool ForVirtualBase, 829 bool Delegating, llvm::Value *This) { 830 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 831 832 if (DD->isVirtual()) 833 This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This); 834 835 // FIXME: Provide a source location here. 836 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This, 837 /*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0); 838 } 839 840 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 841 const CXXRecordDecl *RD) { 842 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 843 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD); 844 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 845 846 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(), 847 E = VFPtrs.end(); I != E; ++I) { 848 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset); 849 if (VTable->hasInitializer()) 850 continue; 851 852 const VTableLayout &VTLayout = 853 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset); 854 llvm::Constant *Init = CGVT.CreateVTableInitializer( 855 RD, VTLayout.vtable_component_begin(), 856 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(), 857 VTLayout.getNumVTableThunks()); 858 VTable->setInitializer(Init); 859 860 VTable->setLinkage(Linkage); 861 CGM.setGlobalVisibility(VTable, RD); 862 } 863 } 864 865 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor( 866 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 867 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 868 NeedsVirtualOffset = (NearestVBase != 0); 869 870 llvm::Value *VTableAddressPoint = 871 getAddrOfVTable(VTableClass, Base.getBaseOffset()); 872 if (!VTableAddressPoint) { 873 assert(Base.getBase()->getNumVBases() && 874 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr()); 875 } 876 return VTableAddressPoint; 877 } 878 879 static void mangleVFTableName(MicrosoftMangleContext &MangleContext, 880 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr, 881 SmallString<256> &Name) { 882 llvm::raw_svector_ostream Out(Name); 883 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out); 884 } 885 886 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr( 887 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 888 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset()); 889 assert(VTable && "Couldn't find a vftable for the given base?"); 890 return VTable; 891 } 892 893 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 894 CharUnits VPtrOffset) { 895 // getAddrOfVTable may return 0 if asked to get an address of a vtable which 896 // shouldn't be used in the given record type. We want to cache this result in 897 // VFTablesMap, thus a simple zero check is not sufficient. 898 VFTableIdTy ID(RD, VPtrOffset); 899 VFTablesMapTy::iterator I; 900 bool Inserted; 901 llvm::tie(I, Inserted) = VFTablesMap.insert( 902 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0))); 903 if (!Inserted) 904 return I->second; 905 906 llvm::GlobalVariable *&VTable = I->second; 907 908 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 909 const MicrosoftVTableContext::VFPtrListTy &VFPtrs = 910 VTContext.getVFPtrOffsets(RD); 911 912 if (DeferredVFTables.insert(RD)) { 913 // We haven't processed this record type before. 914 // Queue up this v-table for possible deferred emission. 915 CGM.addDeferredVTable(RD); 916 917 #ifndef NDEBUG 918 // Create all the vftables at once in order to make sure each vftable has 919 // a unique mangled name. 920 llvm::StringSet<> ObservedMangledNames; 921 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 922 SmallString<256> Name; 923 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 924 if (!ObservedMangledNames.insert(Name.str())) 925 llvm_unreachable("Already saw this mangling before?"); 926 } 927 #endif 928 } 929 930 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 931 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset) 932 continue; 933 934 llvm::ArrayType *ArrayType = llvm::ArrayType::get( 935 CGM.Int8PtrTy, 936 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset) 937 .getNumVTableComponents()); 938 939 SmallString<256> Name; 940 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 941 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 942 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage); 943 VTable->setUnnamedAddr(true); 944 break; 945 } 946 947 return VTable; 948 } 949 950 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 951 GlobalDecl GD, 952 llvm::Value *This, 953 llvm::Type *Ty) { 954 GD = GD.getCanonicalDecl(); 955 CGBuilderTy &Builder = CGF.Builder; 956 957 Ty = Ty->getPointerTo()->getPointerTo(); 958 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This); 959 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty); 960 961 MicrosoftVTableContext::MethodVFTableLocation ML = 962 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 963 llvm::Value *VFuncPtr = 964 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 965 return Builder.CreateLoad(VFuncPtr); 966 } 967 968 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 969 const CXXDestructorDecl *Dtor, 970 CXXDtorType DtorType, 971 SourceLocation CallLoc, 972 llvm::Value *This) { 973 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 974 975 // We have only one destructor in the vftable but can get both behaviors 976 // by passing an implicit int parameter. 977 GlobalDecl GD(Dtor, Dtor_Deleting); 978 const CGFunctionInfo *FInfo = 979 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting); 980 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 981 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty); 982 983 ASTContext &Context = CGF.getContext(); 984 llvm::Value *ImplicitParam = 985 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 986 DtorType == Dtor_Deleting); 987 988 This = adjustThisArgumentForVirtualCall(CGF, GD, This); 989 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This, 990 ImplicitParam, Context.IntTy, 0, 0); 991 } 992 993 const VBTableGlobals & 994 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 995 // At this layer, we can key the cache off of a single class, which is much 996 // easier than caching each vbtable individually. 997 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 998 bool Added; 999 llvm::tie(Entry, Added) = VBTablesMap.insert(std::make_pair(RD, VBTableGlobals())); 1000 VBTableGlobals &VBGlobals = Entry->second; 1001 if (!Added) 1002 return VBGlobals; 1003 1004 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1005 VBGlobals.VBTables = &Context.enumerateVBTables(RD); 1006 1007 // Cache the globals for all vbtables so we don't have to recompute the 1008 // mangled names. 1009 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1010 for (VBTableVector::const_iterator I = VBGlobals.VBTables->begin(), 1011 E = VBGlobals.VBTables->end(); 1012 I != E; ++I) { 1013 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage)); 1014 } 1015 1016 return VBGlobals; 1017 } 1018 1019 llvm::Function * 1020 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD, 1021 StringRef ThunkName) { 1022 // If the thunk has been generated previously, just return it. 1023 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 1024 return cast<llvm::Function>(GV); 1025 1026 // Create the llvm::Function. 1027 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD); 1028 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 1029 llvm::Function *ThunkFn = 1030 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 1031 ThunkName.str(), &CGM.getModule()); 1032 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 1033 1034 ThunkFn->setLinkage(MD->isExternallyVisible() 1035 ? llvm::GlobalValue::LinkOnceODRLinkage 1036 : llvm::GlobalValue::InternalLinkage); 1037 1038 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 1039 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 1040 1041 // Start codegen. 1042 CodeGenFunction CGF(CGM); 1043 CGF.StartThunk(ThunkFn, MD, FnInfo); 1044 1045 // Get to the Callee. 1046 llvm::Value *This = CGF.LoadCXXThis(); 1047 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy); 1048 1049 // Make the call and return the result. 1050 CGF.EmitCallAndReturnForThunk(MD, Callee, 0); 1051 1052 return ThunkFn; 1053 } 1054 1055 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1056 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 1057 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 1058 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I]; 1059 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 1060 emitVBTableDefinition(*VBT, RD, GV); 1061 } 1062 } 1063 1064 llvm::GlobalVariable * 1065 MicrosoftCXXABI::getAddrOfVBTable(const VBTableInfo &VBT, 1066 const CXXRecordDecl *RD, 1067 llvm::GlobalVariable::LinkageTypes Linkage) { 1068 SmallString<256> OutName; 1069 llvm::raw_svector_ostream Out(OutName); 1070 MicrosoftMangleContext &Mangler = 1071 cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext()); 1072 Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out); 1073 Out.flush(); 1074 StringRef Name = OutName.str(); 1075 1076 llvm::ArrayType *VBTableType = 1077 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases()); 1078 1079 assert(!CGM.getModule().getNamedGlobal(Name) && 1080 "vbtable with this name already exists: mangling bug?"); 1081 llvm::GlobalVariable *GV = 1082 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage); 1083 GV->setUnnamedAddr(true); 1084 return GV; 1085 } 1086 1087 void MicrosoftCXXABI::emitVBTableDefinition(const VBTableInfo &VBT, 1088 const CXXRecordDecl *RD, 1089 llvm::GlobalVariable *GV) const { 1090 const CXXRecordDecl *ReusingBase = VBT.ReusingBase; 1091 1092 assert(RD->getNumVBases() && ReusingBase->getNumVBases() && 1093 "should only emit vbtables for classes with vbtables"); 1094 1095 const ASTRecordLayout &BaseLayout = 1096 CGM.getContext().getASTRecordLayout(VBT.BaseWithVBPtr); 1097 const ASTRecordLayout &DerivedLayout = 1098 CGM.getContext().getASTRecordLayout(RD); 1099 1100 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 0); 1101 1102 // The offset from ReusingBase's vbptr to itself always leads. 1103 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 1104 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 1105 1106 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1107 for (CXXRecordDecl::base_class_const_iterator I = ReusingBase->vbases_begin(), 1108 E = ReusingBase->vbases_end(); 1109 I != E; ++I) { 1110 const CXXRecordDecl *VBase = I->getType()->getAsCXXRecordDecl(); 1111 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 1112 assert(!Offset.isNegative()); 1113 1114 // Make it relative to the subobject vbptr. 1115 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 1116 if (VBT.getVBaseWithVBPtr()) 1117 CompleteVBPtrOffset += 1118 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVBPtr()); 1119 Offset -= CompleteVBPtrOffset; 1120 1121 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase); 1122 assert(Offsets[VBIndex] == 0 && "The same vbindex seen twice?"); 1123 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 1124 } 1125 1126 assert(Offsets.size() == 1127 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 1128 ->getElementType())->getNumElements()); 1129 llvm::ArrayType *VBTableType = 1130 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 1131 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 1132 GV->setInitializer(Init); 1133 1134 // Set the right visibility. 1135 CGM.setGlobalVisibility(GV, RD); 1136 } 1137 1138 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1139 llvm::Value *This, 1140 const ThisAdjustment &TA) { 1141 if (TA.isEmpty()) 1142 return This; 1143 1144 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy); 1145 1146 if (!TA.Virtual.isEmpty()) { 1147 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 1148 // Adjust the this argument based on the vtordisp value. 1149 llvm::Value *VtorDispPtr = 1150 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset); 1151 VtorDispPtr = 1152 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo()); 1153 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 1154 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp)); 1155 1156 if (TA.Virtual.Microsoft.VBPtrOffset) { 1157 // If the final overrider is defined in a virtual base other than the one 1158 // that holds the vfptr, we have to use a vtordispex thunk which looks up 1159 // the vbtable of the derived class. 1160 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 1161 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 1162 llvm::Value *VBPtr; 1163 llvm::Value *VBaseOffset = 1164 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset, 1165 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 1166 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1167 } 1168 } 1169 1170 if (TA.NonVirtual) { 1171 // Non-virtual adjustment might result in a pointer outside the allocated 1172 // object, e.g. if the final overrider class is laid out after the virtual 1173 // base that declares a method in the most derived class. 1174 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 1175 } 1176 1177 // Don't need to bitcast back, the call CodeGen will handle this. 1178 return V; 1179 } 1180 1181 llvm::Value * 1182 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1183 const ReturnAdjustment &RA) { 1184 if (RA.isEmpty()) 1185 return Ret; 1186 1187 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy); 1188 1189 if (RA.Virtual.Microsoft.VBIndex) { 1190 assert(RA.Virtual.Microsoft.VBIndex > 0); 1191 int32_t IntSize = 1192 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity(); 1193 llvm::Value *VBPtr; 1194 llvm::Value *VBaseOffset = 1195 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset, 1196 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 1197 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1198 } 1199 1200 if (RA.NonVirtual) 1201 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual); 1202 1203 // Cast back to the original type. 1204 return CGF.Builder.CreateBitCast(V, Ret->getType()); 1205 } 1206 1207 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 1208 QualType elementType) { 1209 // Microsoft seems to completely ignore the possibility of a 1210 // two-argument usual deallocation function. 1211 return elementType.isDestructedType(); 1212 } 1213 1214 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 1215 // Microsoft seems to completely ignore the possibility of a 1216 // two-argument usual deallocation function. 1217 return expr->getAllocatedType().isDestructedType(); 1218 } 1219 1220 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 1221 // The array cookie is always a size_t; we then pad that out to the 1222 // alignment of the element type. 1223 ASTContext &Ctx = getContext(); 1224 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 1225 Ctx.getTypeAlignInChars(type)); 1226 } 1227 1228 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1229 llvm::Value *allocPtr, 1230 CharUnits cookieSize) { 1231 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1232 llvm::Value *numElementsPtr = 1233 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 1234 return CGF.Builder.CreateLoad(numElementsPtr); 1235 } 1236 1237 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1238 llvm::Value *newPtr, 1239 llvm::Value *numElements, 1240 const CXXNewExpr *expr, 1241 QualType elementType) { 1242 assert(requiresArrayCookie(expr)); 1243 1244 // The size of the cookie. 1245 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 1246 1247 // Compute an offset to the cookie. 1248 llvm::Value *cookiePtr = newPtr; 1249 1250 // Write the number of elements into the appropriate slot. 1251 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1252 llvm::Value *numElementsPtr 1253 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 1254 CGF.Builder.CreateStore(numElements, numElementsPtr); 1255 1256 // Finally, compute a pointer to the actual data buffer by skipping 1257 // over the cookie completely. 1258 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1259 cookieSize.getQuantity()); 1260 } 1261 1262 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 1263 llvm::GlobalVariable *GV, 1264 bool PerformInit) { 1265 // MSVC always uses an i32 bitfield to guard initialization, which is *not* 1266 // threadsafe. Since the user may be linking in inline functions compiled by 1267 // cl.exe, there's no reason to provide a false sense of security by using 1268 // critical sections here. 1269 1270 if (D.getTLSKind()) 1271 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 1272 1273 CGBuilderTy &Builder = CGF.Builder; 1274 llvm::IntegerType *GuardTy = CGF.Int32Ty; 1275 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 1276 1277 // Get the guard variable for this function if we have one already. 1278 GuardInfo &GI = GuardVariableMap[D.getDeclContext()]; 1279 1280 unsigned BitIndex; 1281 if (D.isExternallyVisible()) { 1282 // Externally visible variables have to be numbered in Sema to properly 1283 // handle unreachable VarDecls. 1284 BitIndex = getContext().getManglingNumber(&D); 1285 assert(BitIndex > 0); 1286 BitIndex--; 1287 } else { 1288 // Non-externally visible variables are numbered here in CodeGen. 1289 BitIndex = GI.BitIndex++; 1290 } 1291 1292 if (BitIndex >= 32) { 1293 if (D.isExternallyVisible()) 1294 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 1295 BitIndex %= 32; 1296 GI.Guard = 0; 1297 } 1298 1299 // Lazily create the i32 bitfield for this function. 1300 if (!GI.Guard) { 1301 // Mangle the name for the guard. 1302 SmallString<256> GuardName; 1303 { 1304 llvm::raw_svector_ostream Out(GuardName); 1305 getMangleContext().mangleStaticGuardVariable(&D, Out); 1306 Out.flush(); 1307 } 1308 1309 // Create the guard variable with a zero-initializer. Just absorb linkage 1310 // and visibility from the guarded variable. 1311 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false, 1312 GV->getLinkage(), Zero, GuardName.str()); 1313 GI.Guard->setVisibility(GV->getVisibility()); 1314 } else { 1315 assert(GI.Guard->getLinkage() == GV->getLinkage() && 1316 "static local from the same function had different linkage"); 1317 } 1318 1319 // Pseudo code for the test: 1320 // if (!(GuardVar & MyGuardBit)) { 1321 // GuardVar |= MyGuardBit; 1322 // ... initialize the object ...; 1323 // } 1324 1325 // Test our bit from the guard variable. 1326 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex); 1327 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard); 1328 llvm::Value *IsInitialized = 1329 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero); 1330 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1331 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1332 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock); 1333 1334 // Set our bit in the guard variable and emit the initializer and add a global 1335 // destructor if appropriate. 1336 CGF.EmitBlock(InitBlock); 1337 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard); 1338 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 1339 Builder.CreateBr(EndBlock); 1340 1341 // Continue. 1342 CGF.EmitBlock(EndBlock); 1343 } 1344 1345 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 1346 // Null-ness for function memptrs only depends on the first field, which is 1347 // the function pointer. The rest don't matter, so we can zero initialize. 1348 if (MPT->isMemberFunctionPointer()) 1349 return true; 1350 1351 // The virtual base adjustment field is always -1 for null, so if we have one 1352 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 1353 // valid field offset. 1354 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1355 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1356 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) && 1357 RD->nullFieldOffsetIsZero()); 1358 } 1359 1360 llvm::Type * 1361 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 1362 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1363 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1364 llvm::SmallVector<llvm::Type *, 4> fields; 1365 if (MPT->isMemberFunctionPointer()) 1366 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 1367 else 1368 fields.push_back(CGM.IntTy); // FieldOffset 1369 1370 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1371 Inheritance)) 1372 fields.push_back(CGM.IntTy); 1373 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1374 fields.push_back(CGM.IntTy); 1375 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1376 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 1377 1378 if (fields.size() == 1) 1379 return fields[0]; 1380 return llvm::StructType::get(CGM.getLLVMContext(), fields); 1381 } 1382 1383 void MicrosoftCXXABI:: 1384 GetNullMemberPointerFields(const MemberPointerType *MPT, 1385 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 1386 assert(fields.empty()); 1387 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1388 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1389 if (MPT->isMemberFunctionPointer()) { 1390 // FunctionPointerOrVirtualThunk 1391 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1392 } else { 1393 if (RD->nullFieldOffsetIsZero()) 1394 fields.push_back(getZeroInt()); // FieldOffset 1395 else 1396 fields.push_back(getAllOnesInt()); // FieldOffset 1397 } 1398 1399 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1400 Inheritance)) 1401 fields.push_back(getZeroInt()); 1402 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1403 fields.push_back(getZeroInt()); 1404 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1405 fields.push_back(getAllOnesInt()); 1406 } 1407 1408 llvm::Constant * 1409 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 1410 llvm::SmallVector<llvm::Constant *, 4> fields; 1411 GetNullMemberPointerFields(MPT, fields); 1412 if (fields.size() == 1) 1413 return fields[0]; 1414 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 1415 assert(Res->getType() == ConvertMemberPointerType(MPT)); 1416 return Res; 1417 } 1418 1419 llvm::Constant * 1420 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 1421 bool IsMemberFunction, 1422 const CXXRecordDecl *RD, 1423 CharUnits NonVirtualBaseAdjustment) 1424 { 1425 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1426 1427 // Single inheritance class member pointer are represented as scalars instead 1428 // of aggregates. 1429 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance)) 1430 return FirstField; 1431 1432 llvm::SmallVector<llvm::Constant *, 4> fields; 1433 fields.push_back(FirstField); 1434 1435 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance)) 1436 fields.push_back(llvm::ConstantInt::get( 1437 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 1438 1439 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) { 1440 CharUnits Offs = CharUnits::Zero(); 1441 if (RD->getNumVBases()) 1442 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1443 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 1444 } 1445 1446 // The rest of the fields are adjusted by conversions to a more derived class. 1447 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1448 fields.push_back(getZeroInt()); 1449 1450 return llvm::ConstantStruct::getAnon(fields); 1451 } 1452 1453 llvm::Constant * 1454 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 1455 CharUnits offset) { 1456 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1457 llvm::Constant *FirstField = 1458 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 1459 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 1460 CharUnits::Zero()); 1461 } 1462 1463 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 1464 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero()); 1465 } 1466 1467 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 1468 QualType MPType) { 1469 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 1470 const ValueDecl *MPD = MP.getMemberPointerDecl(); 1471 if (!MPD) 1472 return EmitNullMemberPointer(MPT); 1473 1474 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 1475 1476 // FIXME PR15713: Support virtual inheritance paths. 1477 1478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 1479 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD, 1480 ThisAdjustment); 1481 1482 CharUnits FieldOffset = 1483 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 1484 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 1485 } 1486 1487 llvm::Constant * 1488 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD, 1489 const CXXMethodDecl *MD, 1490 CharUnits NonVirtualBaseAdjustment) { 1491 assert(MD->isInstance() && "Member function must not be static!"); 1492 MD = MD->getCanonicalDecl(); 1493 RD = RD->getMostRecentDecl(); 1494 CodeGenTypes &Types = CGM.getTypes(); 1495 1496 llvm::Constant *FirstField; 1497 if (!MD->isVirtual()) { 1498 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1499 llvm::Type *Ty; 1500 // Check whether the function has a computable LLVM signature. 1501 if (Types.isFuncTypeConvertible(FPT)) { 1502 // The function has a computable LLVM signature; use the correct type. 1503 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 1504 } else { 1505 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 1506 // function type is incomplete. 1507 Ty = CGM.PtrDiffTy; 1508 } 1509 FirstField = CGM.GetAddrOfFunction(MD, Ty); 1510 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 1511 } else { 1512 MicrosoftVTableContext::MethodVFTableLocation ML = 1513 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 1514 if (MD->isVariadic()) { 1515 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function"); 1516 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1517 } else if (!CGM.getTypes().isFuncTypeConvertible( 1518 MD->getType()->castAs<FunctionType>())) { 1519 CGM.ErrorUnsupported(MD, "pointer to virtual member function with " 1520 "incomplete return or parameter type"); 1521 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1522 } else if (ML.VBase) { 1523 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding " 1524 "member function in virtual base class"); 1525 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1526 } else { 1527 SmallString<256> ThunkName; 1528 llvm::raw_svector_ostream Out(ThunkName); 1529 getMangleContext().mangleVirtualMemPtrThunk(MD, Out); 1530 Out.flush(); 1531 1532 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str()); 1533 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy); 1534 } 1535 } 1536 1537 // The rest of the fields are common with data member pointers. 1538 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 1539 NonVirtualBaseAdjustment); 1540 } 1541 1542 /// Member pointers are the same if they're either bitwise identical *or* both 1543 /// null. Null-ness for function members is determined by the first field, 1544 /// while for data member pointers we must compare all fields. 1545 llvm::Value * 1546 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 1547 llvm::Value *L, 1548 llvm::Value *R, 1549 const MemberPointerType *MPT, 1550 bool Inequality) { 1551 CGBuilderTy &Builder = CGF.Builder; 1552 1553 // Handle != comparisons by switching the sense of all boolean operations. 1554 llvm::ICmpInst::Predicate Eq; 1555 llvm::Instruction::BinaryOps And, Or; 1556 if (Inequality) { 1557 Eq = llvm::ICmpInst::ICMP_NE; 1558 And = llvm::Instruction::Or; 1559 Or = llvm::Instruction::And; 1560 } else { 1561 Eq = llvm::ICmpInst::ICMP_EQ; 1562 And = llvm::Instruction::And; 1563 Or = llvm::Instruction::Or; 1564 } 1565 1566 // If this is a single field member pointer (single inheritance), this is a 1567 // single icmp. 1568 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1569 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1570 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(), 1571 Inheritance)) 1572 return Builder.CreateICmp(Eq, L, R); 1573 1574 // Compare the first field. 1575 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 1576 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 1577 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 1578 1579 // Compare everything other than the first field. 1580 llvm::Value *Res = 0; 1581 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 1582 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 1583 llvm::Value *LF = Builder.CreateExtractValue(L, I); 1584 llvm::Value *RF = Builder.CreateExtractValue(R, I); 1585 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 1586 if (Res) 1587 Res = Builder.CreateBinOp(And, Res, Cmp); 1588 else 1589 Res = Cmp; 1590 } 1591 1592 // Check if the first field is 0 if this is a function pointer. 1593 if (MPT->isMemberFunctionPointer()) { 1594 // (l1 == r1 && ...) || l0 == 0 1595 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 1596 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 1597 Res = Builder.CreateBinOp(Or, Res, IsZero); 1598 } 1599 1600 // Combine the comparison of the first field, which must always be true for 1601 // this comparison to succeeed. 1602 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 1603 } 1604 1605 llvm::Value * 1606 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 1607 llvm::Value *MemPtr, 1608 const MemberPointerType *MPT) { 1609 CGBuilderTy &Builder = CGF.Builder; 1610 llvm::SmallVector<llvm::Constant *, 4> fields; 1611 // We only need one field for member functions. 1612 if (MPT->isMemberFunctionPointer()) 1613 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1614 else 1615 GetNullMemberPointerFields(MPT, fields); 1616 assert(!fields.empty()); 1617 llvm::Value *FirstField = MemPtr; 1618 if (MemPtr->getType()->isStructTy()) 1619 FirstField = Builder.CreateExtractValue(MemPtr, 0); 1620 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 1621 1622 // For function member pointers, we only need to test the function pointer 1623 // field. The other fields if any can be garbage. 1624 if (MPT->isMemberFunctionPointer()) 1625 return Res; 1626 1627 // Otherwise, emit a series of compares and combine the results. 1628 for (int I = 1, E = fields.size(); I < E; ++I) { 1629 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 1630 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 1631 Res = Builder.CreateAnd(Res, Next, "memptr.tobool"); 1632 } 1633 return Res; 1634 } 1635 1636 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 1637 llvm::Constant *Val) { 1638 // Function pointers are null if the pointer in the first field is null. 1639 if (MPT->isMemberFunctionPointer()) { 1640 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 1641 Val->getAggregateElement(0U) : Val; 1642 return FirstField->isNullValue(); 1643 } 1644 1645 // If it's not a function pointer and it's zero initializable, we can easily 1646 // check zero. 1647 if (isZeroInitializable(MPT) && Val->isNullValue()) 1648 return true; 1649 1650 // Otherwise, break down all the fields for comparison. Hopefully these 1651 // little Constants are reused, while a big null struct might not be. 1652 llvm::SmallVector<llvm::Constant *, 4> Fields; 1653 GetNullMemberPointerFields(MPT, Fields); 1654 if (Fields.size() == 1) { 1655 assert(Val->getType()->isIntegerTy()); 1656 return Val == Fields[0]; 1657 } 1658 1659 unsigned I, E; 1660 for (I = 0, E = Fields.size(); I != E; ++I) { 1661 if (Val->getAggregateElement(I) != Fields[I]) 1662 break; 1663 } 1664 return I == E; 1665 } 1666 1667 llvm::Value * 1668 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 1669 llvm::Value *This, 1670 llvm::Value *VBPtrOffset, 1671 llvm::Value *VBTableOffset, 1672 llvm::Value **VBPtrOut) { 1673 CGBuilderTy &Builder = CGF.Builder; 1674 // Load the vbtable pointer from the vbptr in the instance. 1675 This = Builder.CreateBitCast(This, CGM.Int8PtrTy); 1676 llvm::Value *VBPtr = 1677 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr"); 1678 if (VBPtrOut) *VBPtrOut = VBPtr; 1679 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0)); 1680 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable"); 1681 1682 // Load an i32 offset from the vb-table. 1683 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset); 1684 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 1685 return Builder.CreateLoad(VBaseOffs, "vbase_offs"); 1686 } 1687 1688 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 1689 // it. 1690 llvm::Value * 1691 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF, 1692 const CXXRecordDecl *RD, llvm::Value *Base, 1693 llvm::Value *VBTableOffset, 1694 llvm::Value *VBPtrOffset) { 1695 CGBuilderTy &Builder = CGF.Builder; 1696 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 1697 llvm::BasicBlock *OriginalBB = 0; 1698 llvm::BasicBlock *SkipAdjustBB = 0; 1699 llvm::BasicBlock *VBaseAdjustBB = 0; 1700 1701 // In the unspecified inheritance model, there might not be a vbtable at all, 1702 // in which case we need to skip the virtual base lookup. If there is a 1703 // vbtable, the first entry is a no-op entry that gives back the original 1704 // base, so look for a virtual base adjustment offset of zero. 1705 if (VBPtrOffset) { 1706 OriginalBB = Builder.GetInsertBlock(); 1707 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 1708 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 1709 llvm::Value *IsVirtual = 1710 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 1711 "memptr.is_vbase"); 1712 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 1713 CGF.EmitBlock(VBaseAdjustBB); 1714 } 1715 1716 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 1717 // know the vbptr offset. 1718 if (!VBPtrOffset) { 1719 CharUnits offs = CharUnits::Zero(); 1720 if (RD->getNumVBases()) 1721 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1722 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 1723 } 1724 llvm::Value *VBPtr = 0; 1725 llvm::Value *VBaseOffs = 1726 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 1727 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 1728 1729 // Merge control flow with the case where we didn't have to adjust. 1730 if (VBaseAdjustBB) { 1731 Builder.CreateBr(SkipAdjustBB); 1732 CGF.EmitBlock(SkipAdjustBB); 1733 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 1734 Phi->addIncoming(Base, OriginalBB); 1735 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 1736 return Phi; 1737 } 1738 return AdjustedBase; 1739 } 1740 1741 llvm::Value * 1742 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 1743 llvm::Value *Base, 1744 llvm::Value *MemPtr, 1745 const MemberPointerType *MPT) { 1746 assert(MPT->isMemberDataPointer()); 1747 unsigned AS = Base->getType()->getPointerAddressSpace(); 1748 llvm::Type *PType = 1749 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 1750 CGBuilderTy &Builder = CGF.Builder; 1751 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1752 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1753 1754 // Extract the fields we need, regardless of model. We'll apply them if we 1755 // have them. 1756 llvm::Value *FieldOffset = MemPtr; 1757 llvm::Value *VirtualBaseAdjustmentOffset = 0; 1758 llvm::Value *VBPtrOffset = 0; 1759 if (MemPtr->getType()->isStructTy()) { 1760 // We need to extract values. 1761 unsigned I = 0; 1762 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 1763 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1764 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 1765 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1766 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 1767 } 1768 1769 if (VirtualBaseAdjustmentOffset) { 1770 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset, 1771 VBPtrOffset); 1772 } 1773 1774 // Cast to char*. 1775 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 1776 1777 // Apply the offset, which we assume is non-null. 1778 llvm::Value *Addr = 1779 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 1780 1781 // Cast the address to the appropriate pointer type, adopting the address 1782 // space of the base pointer. 1783 return Builder.CreateBitCast(Addr, PType); 1784 } 1785 1786 static MSInheritanceAttr::Spelling 1787 getInheritanceFromMemptr(const MemberPointerType *MPT) { 1788 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel(); 1789 } 1790 1791 llvm::Value * 1792 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 1793 const CastExpr *E, 1794 llvm::Value *Src) { 1795 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 1796 E->getCastKind() == CK_BaseToDerivedMemberPointer || 1797 E->getCastKind() == CK_ReinterpretMemberPointer); 1798 1799 // Use constant emission if we can. 1800 if (isa<llvm::Constant>(Src)) 1801 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 1802 1803 // We may be adding or dropping fields from the member pointer, so we need 1804 // both types and the inheritance models of both records. 1805 const MemberPointerType *SrcTy = 1806 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 1807 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 1808 bool IsFunc = SrcTy->isMemberFunctionPointer(); 1809 1810 // If the classes use the same null representation, reinterpret_cast is a nop. 1811 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 1812 if (IsReinterpret && IsFunc) 1813 return Src; 1814 1815 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 1816 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 1817 if (IsReinterpret && 1818 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 1819 return Src; 1820 1821 CGBuilderTy &Builder = CGF.Builder; 1822 1823 // Branch past the conversion if Src is null. 1824 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 1825 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 1826 1827 // C++ 5.2.10p9: The null member pointer value is converted to the null member 1828 // pointer value of the destination type. 1829 if (IsReinterpret) { 1830 // For reinterpret casts, sema ensures that src and dst are both functions 1831 // or data and have the same size, which means the LLVM types should match. 1832 assert(Src->getType() == DstNull->getType()); 1833 return Builder.CreateSelect(IsNotNull, Src, DstNull); 1834 } 1835 1836 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 1837 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 1838 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 1839 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 1840 CGF.EmitBlock(ConvertBB); 1841 1842 // Decompose src. 1843 llvm::Value *FirstField = Src; 1844 llvm::Value *NonVirtualBaseAdjustment = 0; 1845 llvm::Value *VirtualBaseAdjustmentOffset = 0; 1846 llvm::Value *VBPtrOffset = 0; 1847 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel(); 1848 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 1849 // We need to extract values. 1850 unsigned I = 0; 1851 FirstField = Builder.CreateExtractValue(Src, I++); 1852 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 1853 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 1854 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 1855 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 1856 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 1857 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 1858 } 1859 1860 // For data pointers, we adjust the field offset directly. For functions, we 1861 // have a separate field. 1862 llvm::Constant *Adj = getMemberPointerAdjustment(E); 1863 if (Adj) { 1864 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 1865 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 1866 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 1867 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 1868 NVAdjustField = getZeroInt(); 1869 if (isDerivedToBase) 1870 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj"); 1871 else 1872 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj"); 1873 } 1874 1875 // FIXME PR15713: Support conversions through virtually derived classes. 1876 1877 // Recompose dst from the null struct and the adjusted fields from src. 1878 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel(); 1879 llvm::Value *Dst; 1880 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) { 1881 Dst = FirstField; 1882 } else { 1883 Dst = llvm::UndefValue::get(DstNull->getType()); 1884 unsigned Idx = 0; 1885 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 1886 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 1887 Dst = Builder.CreateInsertValue( 1888 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++); 1889 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 1890 Dst = Builder.CreateInsertValue( 1891 Dst, getValueOrZeroInt(VBPtrOffset), Idx++); 1892 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 1893 Dst = Builder.CreateInsertValue( 1894 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++); 1895 } 1896 Builder.CreateBr(ContinueBB); 1897 1898 // In the continuation, choose between DstNull and Dst. 1899 CGF.EmitBlock(ContinueBB); 1900 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 1901 Phi->addIncoming(DstNull, OriginalBB); 1902 Phi->addIncoming(Dst, ConvertBB); 1903 return Phi; 1904 } 1905 1906 llvm::Constant * 1907 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 1908 llvm::Constant *Src) { 1909 const MemberPointerType *SrcTy = 1910 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 1911 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 1912 1913 // If src is null, emit a new null for dst. We can't return src because dst 1914 // might have a new representation. 1915 if (MemberPointerConstantIsNull(SrcTy, Src)) 1916 return EmitNullMemberPointer(DstTy); 1917 1918 // We don't need to do anything for reinterpret_casts of non-null member 1919 // pointers. We should only get here when the two type representations have 1920 // the same size. 1921 if (E->getCastKind() == CK_ReinterpretMemberPointer) 1922 return Src; 1923 1924 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy); 1925 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy); 1926 1927 // Decompose src. 1928 llvm::Constant *FirstField = Src; 1929 llvm::Constant *NonVirtualBaseAdjustment = 0; 1930 llvm::Constant *VirtualBaseAdjustmentOffset = 0; 1931 llvm::Constant *VBPtrOffset = 0; 1932 bool IsFunc = SrcTy->isMemberFunctionPointer(); 1933 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 1934 // We need to extract values. 1935 unsigned I = 0; 1936 FirstField = Src->getAggregateElement(I++); 1937 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 1938 NonVirtualBaseAdjustment = Src->getAggregateElement(I++); 1939 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 1940 VBPtrOffset = Src->getAggregateElement(I++); 1941 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 1942 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++); 1943 } 1944 1945 // For data pointers, we adjust the field offset directly. For functions, we 1946 // have a separate field. 1947 llvm::Constant *Adj = getMemberPointerAdjustment(E); 1948 if (Adj) { 1949 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 1950 llvm::Constant *&NVAdjustField = 1951 IsFunc ? NonVirtualBaseAdjustment : FirstField; 1952 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 1953 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 1954 NVAdjustField = getZeroInt(); 1955 if (IsDerivedToBase) 1956 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj); 1957 else 1958 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj); 1959 } 1960 1961 // FIXME PR15713: Support conversions through virtually derived classes. 1962 1963 // Recompose dst from the null struct and the adjusted fields from src. 1964 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) 1965 return FirstField; 1966 1967 llvm::SmallVector<llvm::Constant *, 4> Fields; 1968 Fields.push_back(FirstField); 1969 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 1970 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment)); 1971 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 1972 Fields.push_back(getConstantOrZeroInt(VBPtrOffset)); 1973 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 1974 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset)); 1975 return llvm::ConstantStruct::getAnon(Fields); 1976 } 1977 1978 llvm::Value * 1979 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 1980 llvm::Value *&This, 1981 llvm::Value *MemPtr, 1982 const MemberPointerType *MPT) { 1983 assert(MPT->isMemberFunctionPointer()); 1984 const FunctionProtoType *FPT = 1985 MPT->getPointeeType()->castAs<FunctionProtoType>(); 1986 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1987 llvm::FunctionType *FTy = 1988 CGM.getTypes().GetFunctionType( 1989 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 1990 CGBuilderTy &Builder = CGF.Builder; 1991 1992 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1993 1994 // Extract the fields we need, regardless of model. We'll apply them if we 1995 // have them. 1996 llvm::Value *FunctionPointer = MemPtr; 1997 llvm::Value *NonVirtualBaseAdjustment = NULL; 1998 llvm::Value *VirtualBaseAdjustmentOffset = NULL; 1999 llvm::Value *VBPtrOffset = NULL; 2000 if (MemPtr->getType()->isStructTy()) { 2001 // We need to extract values. 2002 unsigned I = 0; 2003 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 2004 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance)) 2005 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 2006 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 2007 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 2008 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 2009 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 2010 } 2011 2012 if (VirtualBaseAdjustmentOffset) { 2013 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset, 2014 VBPtrOffset); 2015 } 2016 2017 if (NonVirtualBaseAdjustment) { 2018 // Apply the adjustment and cast back to the original struct type. 2019 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 2020 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 2021 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 2022 } 2023 2024 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 2025 } 2026 2027 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 2028 return new MicrosoftCXXABI(CGM); 2029 } 2030