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 VPtrInfoVector *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 VPtrInfo &VBT, const CXXRecordDecl *RD, 205 llvm::GlobalVariable::LinkageTypes Linkage); 206 207 void emitVBTableDefinition(const VPtrInfo &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 Expr *E, 306 const CXXRecordDecl *RD, 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( 332 const CXXMethodDecl *MD, 333 const MicrosoftVTableContext::MethodVFTableLocation &ML); 334 335 public: 336 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 337 338 virtual bool isZeroInitializable(const MemberPointerType *MPT); 339 340 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 341 342 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 343 CharUnits offset); 344 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 345 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT); 346 347 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 348 llvm::Value *L, 349 llvm::Value *R, 350 const MemberPointerType *MPT, 351 bool Inequality); 352 353 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 354 llvm::Value *MemPtr, 355 const MemberPointerType *MPT); 356 357 virtual llvm::Value * 358 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 359 llvm::Value *Base, llvm::Value *MemPtr, 360 const MemberPointerType *MPT); 361 362 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 363 const CastExpr *E, 364 llvm::Value *Src); 365 366 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 367 llvm::Constant *Src); 368 369 virtual llvm::Value * 370 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, 371 llvm::Value *&This, 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 VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 545 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 546 const ASTRecordLayout &SubobjectLayout = 547 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr); 548 CharUnits Offs = VBT->NonVirtualOffset; 549 Offs += SubobjectLayout.getVBPtrOffset(); 550 if (VBT->getVBaseWithVPtr()) 551 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr()); 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 VPtrInfoVector VFPtrs = VFTContext.getVFPtrOffsets(RD); 844 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 845 846 for (VPtrInfoVector::iterator I = VFPtrs.begin(), E = VFPtrs.end(); I != E; 847 ++I) { 848 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, (*I)->FullOffsetInMDC); 849 if (VTable->hasInitializer()) 850 continue; 851 852 const VTableLayout &VTLayout = 853 VFTContext.getVFTableLayout(RD, (*I)->FullOffsetInMDC); 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 VPtrInfo *VFPtr, 881 SmallString<256> &Name) { 882 llvm::raw_svector_ostream Out(Name); 883 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, 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 std::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 VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD); 910 911 if (DeferredVFTables.insert(RD)) { 912 // We haven't processed this record type before. 913 // Queue up this v-table for possible deferred emission. 914 CGM.addDeferredVTable(RD); 915 916 #ifndef NDEBUG 917 // Create all the vftables at once in order to make sure each vftable has 918 // a unique mangled name. 919 llvm::StringSet<> ObservedMangledNames; 920 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 921 SmallString<256> Name; 922 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 923 if (!ObservedMangledNames.insert(Name.str())) 924 llvm_unreachable("Already saw this mangling before?"); 925 } 926 #endif 927 } 928 929 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 930 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset) 931 continue; 932 933 llvm::ArrayType *ArrayType = llvm::ArrayType::get( 934 CGM.Int8PtrTy, 935 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC) 936 .getNumVTableComponents()); 937 938 SmallString<256> Name; 939 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 940 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 941 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage); 942 VTable->setUnnamedAddr(true); 943 break; 944 } 945 946 return VTable; 947 } 948 949 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 950 GlobalDecl GD, 951 llvm::Value *This, 952 llvm::Type *Ty) { 953 GD = GD.getCanonicalDecl(); 954 CGBuilderTy &Builder = CGF.Builder; 955 956 Ty = Ty->getPointerTo()->getPointerTo(); 957 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This); 958 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty); 959 960 MicrosoftVTableContext::MethodVFTableLocation ML = 961 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 962 llvm::Value *VFuncPtr = 963 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 964 return Builder.CreateLoad(VFuncPtr); 965 } 966 967 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 968 const CXXDestructorDecl *Dtor, 969 CXXDtorType DtorType, 970 SourceLocation CallLoc, 971 llvm::Value *This) { 972 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 973 974 // We have only one destructor in the vftable but can get both behaviors 975 // by passing an implicit int parameter. 976 GlobalDecl GD(Dtor, Dtor_Deleting); 977 const CGFunctionInfo *FInfo = 978 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting); 979 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 980 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty); 981 982 ASTContext &Context = CGF.getContext(); 983 llvm::Value *ImplicitParam = 984 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 985 DtorType == Dtor_Deleting); 986 987 This = adjustThisArgumentForVirtualCall(CGF, GD, This); 988 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This, 989 ImplicitParam, Context.IntTy, 0, 0); 990 } 991 992 const VBTableGlobals & 993 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 994 // At this layer, we can key the cache off of a single class, which is much 995 // easier than caching each vbtable individually. 996 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 997 bool Added; 998 std::tie(Entry, Added) = 999 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 (VPtrInfoVector::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 *MicrosoftCXXABI::EmitVirtualMemPtrThunk( 1020 const CXXMethodDecl *MD, 1021 const MicrosoftVTableContext::MethodVFTableLocation &ML) { 1022 // Calculate the mangled name. 1023 SmallString<256> ThunkName; 1024 llvm::raw_svector_ostream Out(ThunkName); 1025 getMangleContext().mangleVirtualMemPtrThunk(MD, Out); 1026 Out.flush(); 1027 1028 // If the thunk has been generated previously, just return it. 1029 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 1030 return cast<llvm::Function>(GV); 1031 1032 // Create the llvm::Function. 1033 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD); 1034 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 1035 llvm::Function *ThunkFn = 1036 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 1037 ThunkName.str(), &CGM.getModule()); 1038 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 1039 1040 ThunkFn->setLinkage(MD->isExternallyVisible() 1041 ? llvm::GlobalValue::LinkOnceODRLinkage 1042 : llvm::GlobalValue::InternalLinkage); 1043 1044 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 1045 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 1046 1047 // Start codegen. 1048 CodeGenFunction CGF(CGM); 1049 CGF.StartThunk(ThunkFn, MD, FnInfo); 1050 1051 // Load the vfptr and then callee from the vftable. The callee should have 1052 // adjusted 'this' so that the vfptr is at offset zero. 1053 llvm::Value *This = CGF.LoadCXXThis(); 1054 llvm::Value *VTable = 1055 CGF.GetVTablePtr(This, ThunkTy->getPointerTo()->getPointerTo()); 1056 llvm::Value *VFuncPtr = 1057 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1058 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr); 1059 1060 // Make the call and return the result. 1061 CGF.EmitCallAndReturnForThunk(MD, Callee, 0); 1062 1063 return ThunkFn; 1064 } 1065 1066 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1067 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 1068 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 1069 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 1070 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 1071 emitVBTableDefinition(*VBT, RD, GV); 1072 } 1073 } 1074 1075 llvm::GlobalVariable * 1076 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 1077 llvm::GlobalVariable::LinkageTypes Linkage) { 1078 SmallString<256> OutName; 1079 llvm::raw_svector_ostream Out(OutName); 1080 MicrosoftMangleContext &Mangler = 1081 cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext()); 1082 Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out); 1083 Out.flush(); 1084 StringRef Name = OutName.str(); 1085 1086 llvm::ArrayType *VBTableType = 1087 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases()); 1088 1089 assert(!CGM.getModule().getNamedGlobal(Name) && 1090 "vbtable with this name already exists: mangling bug?"); 1091 llvm::GlobalVariable *GV = 1092 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage); 1093 GV->setUnnamedAddr(true); 1094 return GV; 1095 } 1096 1097 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT, 1098 const CXXRecordDecl *RD, 1099 llvm::GlobalVariable *GV) const { 1100 const CXXRecordDecl *ReusingBase = VBT.ReusingBase; 1101 1102 assert(RD->getNumVBases() && ReusingBase->getNumVBases() && 1103 "should only emit vbtables for classes with vbtables"); 1104 1105 const ASTRecordLayout &BaseLayout = 1106 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr); 1107 const ASTRecordLayout &DerivedLayout = 1108 CGM.getContext().getASTRecordLayout(RD); 1109 1110 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 0); 1111 1112 // The offset from ReusingBase's vbptr to itself always leads. 1113 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 1114 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 1115 1116 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1117 for (CXXRecordDecl::base_class_const_iterator I = ReusingBase->vbases_begin(), 1118 E = ReusingBase->vbases_end(); 1119 I != E; ++I) { 1120 const CXXRecordDecl *VBase = I->getType()->getAsCXXRecordDecl(); 1121 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 1122 assert(!Offset.isNegative()); 1123 1124 // Make it relative to the subobject vbptr. 1125 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 1126 if (VBT.getVBaseWithVPtr()) 1127 CompleteVBPtrOffset += 1128 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr()); 1129 Offset -= CompleteVBPtrOffset; 1130 1131 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase); 1132 assert(Offsets[VBIndex] == 0 && "The same vbindex seen twice?"); 1133 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 1134 } 1135 1136 assert(Offsets.size() == 1137 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 1138 ->getElementType())->getNumElements()); 1139 llvm::ArrayType *VBTableType = 1140 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 1141 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 1142 GV->setInitializer(Init); 1143 1144 // Set the right visibility. 1145 CGM.setGlobalVisibility(GV, RD); 1146 } 1147 1148 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1149 llvm::Value *This, 1150 const ThisAdjustment &TA) { 1151 if (TA.isEmpty()) 1152 return This; 1153 1154 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy); 1155 1156 if (!TA.Virtual.isEmpty()) { 1157 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 1158 // Adjust the this argument based on the vtordisp value. 1159 llvm::Value *VtorDispPtr = 1160 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset); 1161 VtorDispPtr = 1162 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo()); 1163 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 1164 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp)); 1165 1166 if (TA.Virtual.Microsoft.VBPtrOffset) { 1167 // If the final overrider is defined in a virtual base other than the one 1168 // that holds the vfptr, we have to use a vtordispex thunk which looks up 1169 // the vbtable of the derived class. 1170 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 1171 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 1172 llvm::Value *VBPtr; 1173 llvm::Value *VBaseOffset = 1174 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset, 1175 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 1176 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1177 } 1178 } 1179 1180 if (TA.NonVirtual) { 1181 // Non-virtual adjustment might result in a pointer outside the allocated 1182 // object, e.g. if the final overrider class is laid out after the virtual 1183 // base that declares a method in the most derived class. 1184 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 1185 } 1186 1187 // Don't need to bitcast back, the call CodeGen will handle this. 1188 return V; 1189 } 1190 1191 llvm::Value * 1192 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1193 const ReturnAdjustment &RA) { 1194 if (RA.isEmpty()) 1195 return Ret; 1196 1197 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy); 1198 1199 if (RA.Virtual.Microsoft.VBIndex) { 1200 assert(RA.Virtual.Microsoft.VBIndex > 0); 1201 int32_t IntSize = 1202 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity(); 1203 llvm::Value *VBPtr; 1204 llvm::Value *VBaseOffset = 1205 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset, 1206 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 1207 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1208 } 1209 1210 if (RA.NonVirtual) 1211 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual); 1212 1213 // Cast back to the original type. 1214 return CGF.Builder.CreateBitCast(V, Ret->getType()); 1215 } 1216 1217 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 1218 QualType elementType) { 1219 // Microsoft seems to completely ignore the possibility of a 1220 // two-argument usual deallocation function. 1221 return elementType.isDestructedType(); 1222 } 1223 1224 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 1225 // Microsoft seems to completely ignore the possibility of a 1226 // two-argument usual deallocation function. 1227 return expr->getAllocatedType().isDestructedType(); 1228 } 1229 1230 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 1231 // The array cookie is always a size_t; we then pad that out to the 1232 // alignment of the element type. 1233 ASTContext &Ctx = getContext(); 1234 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 1235 Ctx.getTypeAlignInChars(type)); 1236 } 1237 1238 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1239 llvm::Value *allocPtr, 1240 CharUnits cookieSize) { 1241 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1242 llvm::Value *numElementsPtr = 1243 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 1244 return CGF.Builder.CreateLoad(numElementsPtr); 1245 } 1246 1247 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1248 llvm::Value *newPtr, 1249 llvm::Value *numElements, 1250 const CXXNewExpr *expr, 1251 QualType elementType) { 1252 assert(requiresArrayCookie(expr)); 1253 1254 // The size of the cookie. 1255 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 1256 1257 // Compute an offset to the cookie. 1258 llvm::Value *cookiePtr = newPtr; 1259 1260 // Write the number of elements into the appropriate slot. 1261 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1262 llvm::Value *numElementsPtr 1263 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 1264 CGF.Builder.CreateStore(numElements, numElementsPtr); 1265 1266 // Finally, compute a pointer to the actual data buffer by skipping 1267 // over the cookie completely. 1268 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1269 cookieSize.getQuantity()); 1270 } 1271 1272 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 1273 llvm::GlobalVariable *GV, 1274 bool PerformInit) { 1275 // MSVC always uses an i32 bitfield to guard initialization, which is *not* 1276 // threadsafe. Since the user may be linking in inline functions compiled by 1277 // cl.exe, there's no reason to provide a false sense of security by using 1278 // critical sections here. 1279 1280 if (D.getTLSKind()) 1281 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 1282 1283 CGBuilderTy &Builder = CGF.Builder; 1284 llvm::IntegerType *GuardTy = CGF.Int32Ty; 1285 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 1286 1287 // Get the guard variable for this function if we have one already. 1288 GuardInfo &GI = GuardVariableMap[D.getDeclContext()]; 1289 1290 unsigned BitIndex; 1291 if (D.isExternallyVisible()) { 1292 // Externally visible variables have to be numbered in Sema to properly 1293 // handle unreachable VarDecls. 1294 BitIndex = getContext().getStaticLocalNumber(&D); 1295 assert(BitIndex > 0); 1296 BitIndex--; 1297 } else { 1298 // Non-externally visible variables are numbered here in CodeGen. 1299 BitIndex = GI.BitIndex++; 1300 } 1301 1302 if (BitIndex >= 32) { 1303 if (D.isExternallyVisible()) 1304 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 1305 BitIndex %= 32; 1306 GI.Guard = 0; 1307 } 1308 1309 // Lazily create the i32 bitfield for this function. 1310 if (!GI.Guard) { 1311 // Mangle the name for the guard. 1312 SmallString<256> GuardName; 1313 { 1314 llvm::raw_svector_ostream Out(GuardName); 1315 getMangleContext().mangleStaticGuardVariable(&D, Out); 1316 Out.flush(); 1317 } 1318 1319 // Create the guard variable with a zero-initializer. Just absorb linkage 1320 // and visibility from the guarded variable. 1321 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false, 1322 GV->getLinkage(), Zero, GuardName.str()); 1323 GI.Guard->setVisibility(GV->getVisibility()); 1324 } else { 1325 assert(GI.Guard->getLinkage() == GV->getLinkage() && 1326 "static local from the same function had different linkage"); 1327 } 1328 1329 // Pseudo code for the test: 1330 // if (!(GuardVar & MyGuardBit)) { 1331 // GuardVar |= MyGuardBit; 1332 // ... initialize the object ...; 1333 // } 1334 1335 // Test our bit from the guard variable. 1336 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex); 1337 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard); 1338 llvm::Value *IsInitialized = 1339 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero); 1340 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1341 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1342 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock); 1343 1344 // Set our bit in the guard variable and emit the initializer and add a global 1345 // destructor if appropriate. 1346 CGF.EmitBlock(InitBlock); 1347 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard); 1348 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 1349 Builder.CreateBr(EndBlock); 1350 1351 // Continue. 1352 CGF.EmitBlock(EndBlock); 1353 } 1354 1355 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 1356 // Null-ness for function memptrs only depends on the first field, which is 1357 // the function pointer. The rest don't matter, so we can zero initialize. 1358 if (MPT->isMemberFunctionPointer()) 1359 return true; 1360 1361 // The virtual base adjustment field is always -1 for null, so if we have one 1362 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 1363 // valid field offset. 1364 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1365 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1366 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) && 1367 RD->nullFieldOffsetIsZero()); 1368 } 1369 1370 llvm::Type * 1371 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 1372 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1373 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1374 llvm::SmallVector<llvm::Type *, 4> fields; 1375 if (MPT->isMemberFunctionPointer()) 1376 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 1377 else 1378 fields.push_back(CGM.IntTy); // FieldOffset 1379 1380 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1381 Inheritance)) 1382 fields.push_back(CGM.IntTy); 1383 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1384 fields.push_back(CGM.IntTy); 1385 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1386 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 1387 1388 if (fields.size() == 1) 1389 return fields[0]; 1390 return llvm::StructType::get(CGM.getLLVMContext(), fields); 1391 } 1392 1393 void MicrosoftCXXABI:: 1394 GetNullMemberPointerFields(const MemberPointerType *MPT, 1395 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 1396 assert(fields.empty()); 1397 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1398 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1399 if (MPT->isMemberFunctionPointer()) { 1400 // FunctionPointerOrVirtualThunk 1401 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1402 } else { 1403 if (RD->nullFieldOffsetIsZero()) 1404 fields.push_back(getZeroInt()); // FieldOffset 1405 else 1406 fields.push_back(getAllOnesInt()); // FieldOffset 1407 } 1408 1409 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1410 Inheritance)) 1411 fields.push_back(getZeroInt()); 1412 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1413 fields.push_back(getZeroInt()); 1414 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1415 fields.push_back(getAllOnesInt()); 1416 } 1417 1418 llvm::Constant * 1419 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 1420 llvm::SmallVector<llvm::Constant *, 4> fields; 1421 GetNullMemberPointerFields(MPT, fields); 1422 if (fields.size() == 1) 1423 return fields[0]; 1424 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 1425 assert(Res->getType() == ConvertMemberPointerType(MPT)); 1426 return Res; 1427 } 1428 1429 llvm::Constant * 1430 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 1431 bool IsMemberFunction, 1432 const CXXRecordDecl *RD, 1433 CharUnits NonVirtualBaseAdjustment) 1434 { 1435 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1436 1437 // Single inheritance class member pointer are represented as scalars instead 1438 // of aggregates. 1439 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance)) 1440 return FirstField; 1441 1442 llvm::SmallVector<llvm::Constant *, 4> fields; 1443 fields.push_back(FirstField); 1444 1445 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance)) 1446 fields.push_back(llvm::ConstantInt::get( 1447 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 1448 1449 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) { 1450 CharUnits Offs = CharUnits::Zero(); 1451 if (RD->getNumVBases()) 1452 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1453 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 1454 } 1455 1456 // The rest of the fields are adjusted by conversions to a more derived class. 1457 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1458 fields.push_back(getZeroInt()); 1459 1460 return llvm::ConstantStruct::getAnon(fields); 1461 } 1462 1463 llvm::Constant * 1464 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 1465 CharUnits offset) { 1466 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1467 llvm::Constant *FirstField = 1468 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 1469 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 1470 CharUnits::Zero()); 1471 } 1472 1473 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 1474 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero()); 1475 } 1476 1477 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 1478 QualType MPType) { 1479 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 1480 const ValueDecl *MPD = MP.getMemberPointerDecl(); 1481 if (!MPD) 1482 return EmitNullMemberPointer(MPT); 1483 1484 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 1485 1486 // FIXME PR15713: Support virtual inheritance paths. 1487 1488 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 1489 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD, 1490 ThisAdjustment); 1491 1492 CharUnits FieldOffset = 1493 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 1494 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 1495 } 1496 1497 llvm::Constant * 1498 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD, 1499 const CXXMethodDecl *MD, 1500 CharUnits NonVirtualBaseAdjustment) { 1501 assert(MD->isInstance() && "Member function must not be static!"); 1502 MD = MD->getCanonicalDecl(); 1503 RD = RD->getMostRecentDecl(); 1504 CodeGenTypes &Types = CGM.getTypes(); 1505 1506 llvm::Constant *FirstField; 1507 if (!MD->isVirtual()) { 1508 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1509 llvm::Type *Ty; 1510 // Check whether the function has a computable LLVM signature. 1511 if (Types.isFuncTypeConvertible(FPT)) { 1512 // The function has a computable LLVM signature; use the correct type. 1513 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 1514 } else { 1515 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 1516 // function type is incomplete. 1517 Ty = CGM.PtrDiffTy; 1518 } 1519 FirstField = CGM.GetAddrOfFunction(MD, Ty); 1520 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 1521 } else { 1522 MicrosoftVTableContext::MethodVFTableLocation ML = 1523 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 1524 if (MD->isVariadic()) { 1525 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function"); 1526 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1527 } else if (!CGM.getTypes().isFuncTypeConvertible( 1528 MD->getType()->castAs<FunctionType>())) { 1529 CGM.ErrorUnsupported(MD, "pointer to virtual member function with " 1530 "incomplete return or parameter type"); 1531 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1532 } else if (ML.VBase) { 1533 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding " 1534 "member function in virtual base class"); 1535 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1536 } else { 1537 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML); 1538 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy); 1539 // Include the vfptr adjustment if the method is in a non-primary vftable. 1540 NonVirtualBaseAdjustment += ML.VFPtrOffset; 1541 } 1542 } 1543 1544 // The rest of the fields are common with data member pointers. 1545 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 1546 NonVirtualBaseAdjustment); 1547 } 1548 1549 /// Member pointers are the same if they're either bitwise identical *or* both 1550 /// null. Null-ness for function members is determined by the first field, 1551 /// while for data member pointers we must compare all fields. 1552 llvm::Value * 1553 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 1554 llvm::Value *L, 1555 llvm::Value *R, 1556 const MemberPointerType *MPT, 1557 bool Inequality) { 1558 CGBuilderTy &Builder = CGF.Builder; 1559 1560 // Handle != comparisons by switching the sense of all boolean operations. 1561 llvm::ICmpInst::Predicate Eq; 1562 llvm::Instruction::BinaryOps And, Or; 1563 if (Inequality) { 1564 Eq = llvm::ICmpInst::ICMP_NE; 1565 And = llvm::Instruction::Or; 1566 Or = llvm::Instruction::And; 1567 } else { 1568 Eq = llvm::ICmpInst::ICMP_EQ; 1569 And = llvm::Instruction::And; 1570 Or = llvm::Instruction::Or; 1571 } 1572 1573 // If this is a single field member pointer (single inheritance), this is a 1574 // single icmp. 1575 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1576 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1577 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(), 1578 Inheritance)) 1579 return Builder.CreateICmp(Eq, L, R); 1580 1581 // Compare the first field. 1582 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 1583 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 1584 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 1585 1586 // Compare everything other than the first field. 1587 llvm::Value *Res = 0; 1588 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 1589 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 1590 llvm::Value *LF = Builder.CreateExtractValue(L, I); 1591 llvm::Value *RF = Builder.CreateExtractValue(R, I); 1592 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 1593 if (Res) 1594 Res = Builder.CreateBinOp(And, Res, Cmp); 1595 else 1596 Res = Cmp; 1597 } 1598 1599 // Check if the first field is 0 if this is a function pointer. 1600 if (MPT->isMemberFunctionPointer()) { 1601 // (l1 == r1 && ...) || l0 == 0 1602 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 1603 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 1604 Res = Builder.CreateBinOp(Or, Res, IsZero); 1605 } 1606 1607 // Combine the comparison of the first field, which must always be true for 1608 // this comparison to succeeed. 1609 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 1610 } 1611 1612 llvm::Value * 1613 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 1614 llvm::Value *MemPtr, 1615 const MemberPointerType *MPT) { 1616 CGBuilderTy &Builder = CGF.Builder; 1617 llvm::SmallVector<llvm::Constant *, 4> fields; 1618 // We only need one field for member functions. 1619 if (MPT->isMemberFunctionPointer()) 1620 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1621 else 1622 GetNullMemberPointerFields(MPT, fields); 1623 assert(!fields.empty()); 1624 llvm::Value *FirstField = MemPtr; 1625 if (MemPtr->getType()->isStructTy()) 1626 FirstField = Builder.CreateExtractValue(MemPtr, 0); 1627 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 1628 1629 // For function member pointers, we only need to test the function pointer 1630 // field. The other fields if any can be garbage. 1631 if (MPT->isMemberFunctionPointer()) 1632 return Res; 1633 1634 // Otherwise, emit a series of compares and combine the results. 1635 for (int I = 1, E = fields.size(); I < E; ++I) { 1636 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 1637 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 1638 Res = Builder.CreateAnd(Res, Next, "memptr.tobool"); 1639 } 1640 return Res; 1641 } 1642 1643 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 1644 llvm::Constant *Val) { 1645 // Function pointers are null if the pointer in the first field is null. 1646 if (MPT->isMemberFunctionPointer()) { 1647 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 1648 Val->getAggregateElement(0U) : Val; 1649 return FirstField->isNullValue(); 1650 } 1651 1652 // If it's not a function pointer and it's zero initializable, we can easily 1653 // check zero. 1654 if (isZeroInitializable(MPT) && Val->isNullValue()) 1655 return true; 1656 1657 // Otherwise, break down all the fields for comparison. Hopefully these 1658 // little Constants are reused, while a big null struct might not be. 1659 llvm::SmallVector<llvm::Constant *, 4> Fields; 1660 GetNullMemberPointerFields(MPT, Fields); 1661 if (Fields.size() == 1) { 1662 assert(Val->getType()->isIntegerTy()); 1663 return Val == Fields[0]; 1664 } 1665 1666 unsigned I, E; 1667 for (I = 0, E = Fields.size(); I != E; ++I) { 1668 if (Val->getAggregateElement(I) != Fields[I]) 1669 break; 1670 } 1671 return I == E; 1672 } 1673 1674 llvm::Value * 1675 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 1676 llvm::Value *This, 1677 llvm::Value *VBPtrOffset, 1678 llvm::Value *VBTableOffset, 1679 llvm::Value **VBPtrOut) { 1680 CGBuilderTy &Builder = CGF.Builder; 1681 // Load the vbtable pointer from the vbptr in the instance. 1682 This = Builder.CreateBitCast(This, CGM.Int8PtrTy); 1683 llvm::Value *VBPtr = 1684 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr"); 1685 if (VBPtrOut) *VBPtrOut = VBPtr; 1686 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0)); 1687 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable"); 1688 1689 // Load an i32 offset from the vb-table. 1690 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset); 1691 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 1692 return Builder.CreateLoad(VBaseOffs, "vbase_offs"); 1693 } 1694 1695 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 1696 // it. 1697 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase( 1698 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD, 1699 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) { 1700 CGBuilderTy &Builder = CGF.Builder; 1701 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 1702 llvm::BasicBlock *OriginalBB = 0; 1703 llvm::BasicBlock *SkipAdjustBB = 0; 1704 llvm::BasicBlock *VBaseAdjustBB = 0; 1705 1706 // In the unspecified inheritance model, there might not be a vbtable at all, 1707 // in which case we need to skip the virtual base lookup. If there is a 1708 // vbtable, the first entry is a no-op entry that gives back the original 1709 // base, so look for a virtual base adjustment offset of zero. 1710 if (VBPtrOffset) { 1711 OriginalBB = Builder.GetInsertBlock(); 1712 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 1713 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 1714 llvm::Value *IsVirtual = 1715 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 1716 "memptr.is_vbase"); 1717 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 1718 CGF.EmitBlock(VBaseAdjustBB); 1719 } 1720 1721 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 1722 // know the vbptr offset. 1723 if (!VBPtrOffset) { 1724 CharUnits offs = CharUnits::Zero(); 1725 if (!RD->hasDefinition()) { 1726 DiagnosticsEngine &Diags = CGF.CGM.getDiags(); 1727 unsigned DiagID = Diags.getCustomDiagID( 1728 DiagnosticsEngine::Error, 1729 "member pointer representation requires a " 1730 "complete class type for %0 to perform this expression"); 1731 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange(); 1732 } else if (RD->getNumVBases()) 1733 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1734 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 1735 } 1736 llvm::Value *VBPtr = 0; 1737 llvm::Value *VBaseOffs = 1738 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 1739 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 1740 1741 // Merge control flow with the case where we didn't have to adjust. 1742 if (VBaseAdjustBB) { 1743 Builder.CreateBr(SkipAdjustBB); 1744 CGF.EmitBlock(SkipAdjustBB); 1745 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 1746 Phi->addIncoming(Base, OriginalBB); 1747 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 1748 return Phi; 1749 } 1750 return AdjustedBase; 1751 } 1752 1753 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress( 1754 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr, 1755 const MemberPointerType *MPT) { 1756 assert(MPT->isMemberDataPointer()); 1757 unsigned AS = Base->getType()->getPointerAddressSpace(); 1758 llvm::Type *PType = 1759 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 1760 CGBuilderTy &Builder = CGF.Builder; 1761 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1762 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1763 1764 // Extract the fields we need, regardless of model. We'll apply them if we 1765 // have them. 1766 llvm::Value *FieldOffset = MemPtr; 1767 llvm::Value *VirtualBaseAdjustmentOffset = 0; 1768 llvm::Value *VBPtrOffset = 0; 1769 if (MemPtr->getType()->isStructTy()) { 1770 // We need to extract values. 1771 unsigned I = 0; 1772 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 1773 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1774 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 1775 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1776 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 1777 } 1778 1779 if (VirtualBaseAdjustmentOffset) { 1780 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset, 1781 VBPtrOffset); 1782 } 1783 1784 // Cast to char*. 1785 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 1786 1787 // Apply the offset, which we assume is non-null. 1788 llvm::Value *Addr = 1789 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 1790 1791 // Cast the address to the appropriate pointer type, adopting the address 1792 // space of the base pointer. 1793 return Builder.CreateBitCast(Addr, PType); 1794 } 1795 1796 static MSInheritanceAttr::Spelling 1797 getInheritanceFromMemptr(const MemberPointerType *MPT) { 1798 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel(); 1799 } 1800 1801 llvm::Value * 1802 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 1803 const CastExpr *E, 1804 llvm::Value *Src) { 1805 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 1806 E->getCastKind() == CK_BaseToDerivedMemberPointer || 1807 E->getCastKind() == CK_ReinterpretMemberPointer); 1808 1809 // Use constant emission if we can. 1810 if (isa<llvm::Constant>(Src)) 1811 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 1812 1813 // We may be adding or dropping fields from the member pointer, so we need 1814 // both types and the inheritance models of both records. 1815 const MemberPointerType *SrcTy = 1816 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 1817 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 1818 bool IsFunc = SrcTy->isMemberFunctionPointer(); 1819 1820 // If the classes use the same null representation, reinterpret_cast is a nop. 1821 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 1822 if (IsReinterpret && IsFunc) 1823 return Src; 1824 1825 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 1826 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 1827 if (IsReinterpret && 1828 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 1829 return Src; 1830 1831 CGBuilderTy &Builder = CGF.Builder; 1832 1833 // Branch past the conversion if Src is null. 1834 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 1835 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 1836 1837 // C++ 5.2.10p9: The null member pointer value is converted to the null member 1838 // pointer value of the destination type. 1839 if (IsReinterpret) { 1840 // For reinterpret casts, sema ensures that src and dst are both functions 1841 // or data and have the same size, which means the LLVM types should match. 1842 assert(Src->getType() == DstNull->getType()); 1843 return Builder.CreateSelect(IsNotNull, Src, DstNull); 1844 } 1845 1846 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 1847 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 1848 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 1849 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 1850 CGF.EmitBlock(ConvertBB); 1851 1852 // Decompose src. 1853 llvm::Value *FirstField = Src; 1854 llvm::Value *NonVirtualBaseAdjustment = 0; 1855 llvm::Value *VirtualBaseAdjustmentOffset = 0; 1856 llvm::Value *VBPtrOffset = 0; 1857 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel(); 1858 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 1859 // We need to extract values. 1860 unsigned I = 0; 1861 FirstField = Builder.CreateExtractValue(Src, I++); 1862 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 1863 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 1864 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 1865 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 1866 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 1867 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 1868 } 1869 1870 // For data pointers, we adjust the field offset directly. For functions, we 1871 // have a separate field. 1872 llvm::Constant *Adj = getMemberPointerAdjustment(E); 1873 if (Adj) { 1874 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 1875 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 1876 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 1877 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 1878 NVAdjustField = getZeroInt(); 1879 if (isDerivedToBase) 1880 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj"); 1881 else 1882 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj"); 1883 } 1884 1885 // FIXME PR15713: Support conversions through virtually derived classes. 1886 1887 // Recompose dst from the null struct and the adjusted fields from src. 1888 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel(); 1889 llvm::Value *Dst; 1890 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) { 1891 Dst = FirstField; 1892 } else { 1893 Dst = llvm::UndefValue::get(DstNull->getType()); 1894 unsigned Idx = 0; 1895 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 1896 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 1897 Dst = Builder.CreateInsertValue( 1898 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++); 1899 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 1900 Dst = Builder.CreateInsertValue( 1901 Dst, getValueOrZeroInt(VBPtrOffset), Idx++); 1902 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 1903 Dst = Builder.CreateInsertValue( 1904 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++); 1905 } 1906 Builder.CreateBr(ContinueBB); 1907 1908 // In the continuation, choose between DstNull and Dst. 1909 CGF.EmitBlock(ContinueBB); 1910 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 1911 Phi->addIncoming(DstNull, OriginalBB); 1912 Phi->addIncoming(Dst, ConvertBB); 1913 return Phi; 1914 } 1915 1916 llvm::Constant * 1917 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 1918 llvm::Constant *Src) { 1919 const MemberPointerType *SrcTy = 1920 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 1921 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 1922 1923 // If src is null, emit a new null for dst. We can't return src because dst 1924 // might have a new representation. 1925 if (MemberPointerConstantIsNull(SrcTy, Src)) 1926 return EmitNullMemberPointer(DstTy); 1927 1928 // We don't need to do anything for reinterpret_casts of non-null member 1929 // pointers. We should only get here when the two type representations have 1930 // the same size. 1931 if (E->getCastKind() == CK_ReinterpretMemberPointer) 1932 return Src; 1933 1934 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy); 1935 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy); 1936 1937 // Decompose src. 1938 llvm::Constant *FirstField = Src; 1939 llvm::Constant *NonVirtualBaseAdjustment = 0; 1940 llvm::Constant *VirtualBaseAdjustmentOffset = 0; 1941 llvm::Constant *VBPtrOffset = 0; 1942 bool IsFunc = SrcTy->isMemberFunctionPointer(); 1943 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 1944 // We need to extract values. 1945 unsigned I = 0; 1946 FirstField = Src->getAggregateElement(I++); 1947 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 1948 NonVirtualBaseAdjustment = Src->getAggregateElement(I++); 1949 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 1950 VBPtrOffset = Src->getAggregateElement(I++); 1951 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 1952 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++); 1953 } 1954 1955 // For data pointers, we adjust the field offset directly. For functions, we 1956 // have a separate field. 1957 llvm::Constant *Adj = getMemberPointerAdjustment(E); 1958 if (Adj) { 1959 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 1960 llvm::Constant *&NVAdjustField = 1961 IsFunc ? NonVirtualBaseAdjustment : FirstField; 1962 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 1963 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 1964 NVAdjustField = getZeroInt(); 1965 if (IsDerivedToBase) 1966 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj); 1967 else 1968 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj); 1969 } 1970 1971 // FIXME PR15713: Support conversions through virtually derived classes. 1972 1973 // Recompose dst from the null struct and the adjusted fields from src. 1974 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) 1975 return FirstField; 1976 1977 llvm::SmallVector<llvm::Constant *, 4> Fields; 1978 Fields.push_back(FirstField); 1979 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 1980 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment)); 1981 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 1982 Fields.push_back(getConstantOrZeroInt(VBPtrOffset)); 1983 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 1984 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset)); 1985 return llvm::ConstantStruct::getAnon(Fields); 1986 } 1987 1988 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer( 1989 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This, 1990 llvm::Value *MemPtr, const MemberPointerType *MPT) { 1991 assert(MPT->isMemberFunctionPointer()); 1992 const FunctionProtoType *FPT = 1993 MPT->getPointeeType()->castAs<FunctionProtoType>(); 1994 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1995 llvm::FunctionType *FTy = 1996 CGM.getTypes().GetFunctionType( 1997 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 1998 CGBuilderTy &Builder = CGF.Builder; 1999 2000 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 2001 2002 // Extract the fields we need, regardless of model. We'll apply them if we 2003 // have them. 2004 llvm::Value *FunctionPointer = MemPtr; 2005 llvm::Value *NonVirtualBaseAdjustment = NULL; 2006 llvm::Value *VirtualBaseAdjustmentOffset = NULL; 2007 llvm::Value *VBPtrOffset = NULL; 2008 if (MemPtr->getType()->isStructTy()) { 2009 // We need to extract values. 2010 unsigned I = 0; 2011 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 2012 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance)) 2013 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 2014 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 2015 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 2016 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 2017 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 2018 } 2019 2020 if (VirtualBaseAdjustmentOffset) { 2021 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset, 2022 VBPtrOffset); 2023 } 2024 2025 if (NonVirtualBaseAdjustment) { 2026 // Apply the adjustment and cast back to the original struct type. 2027 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 2028 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 2029 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 2030 } 2031 2032 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 2033 } 2034 2035 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 2036 return new MicrosoftCXXABI(CGM); 2037 } 2038