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 "CodeGenModule.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 22 using namespace clang; 23 using namespace CodeGen; 24 25 namespace { 26 27 class MicrosoftCXXABI : public CGCXXABI { 28 public: 29 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {} 30 31 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const { 32 // Structures that are not C++03 PODs are always indirect. 33 return !RD->isPOD(); 34 } 35 36 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const { 37 if (RD->hasNonTrivialCopyConstructor()) 38 return RAA_DirectInMemory; 39 return RAA_Default; 40 } 41 42 StringRef GetPureVirtualCallName() { return "_purecall"; } 43 // No known support for deleted functions in MSVC yet, so this choice is 44 // arbitrary. 45 StringRef GetDeletedVirtualCallName() { return "_purecall"; } 46 47 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 48 llvm::Value *ptr, 49 QualType type); 50 51 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 52 CXXCtorType Type, 53 CanQualType &ResTy, 54 SmallVectorImpl<CanQualType> &ArgTys); 55 56 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF); 57 58 void BuildDestructorSignature(const CXXDestructorDecl *Ctor, 59 CXXDtorType Type, 60 CanQualType &ResTy, 61 SmallVectorImpl<CanQualType> &ArgTys); 62 63 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 64 QualType &ResTy, 65 FunctionArgList &Params); 66 67 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 68 69 llvm::Value *EmitConstructorCall(CodeGenFunction &CGF, 70 const CXXConstructorDecl *D, 71 CXXCtorType Type, bool ForVirtualBase, 72 bool Delegating, 73 llvm::Value *This, 74 CallExpr::const_arg_iterator ArgBeg, 75 CallExpr::const_arg_iterator ArgEnd); 76 77 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF, 78 const CXXDestructorDecl *Dtor, 79 CXXDtorType DtorType, 80 SourceLocation CallLoc, 81 ReturnValueSlot ReturnValue, 82 llvm::Value *This); 83 84 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 85 llvm::GlobalVariable *DeclPtr, 86 bool PerformInit); 87 88 // ==== Notes on array cookies ========= 89 // 90 // MSVC seems to only use cookies when the class has a destructor; a 91 // two-argument usual array deallocation function isn't sufficient. 92 // 93 // For example, this code prints "100" and "1": 94 // struct A { 95 // char x; 96 // void *operator new[](size_t sz) { 97 // printf("%u\n", sz); 98 // return malloc(sz); 99 // } 100 // void operator delete[](void *p, size_t sz) { 101 // printf("%u\n", sz); 102 // free(p); 103 // } 104 // }; 105 // int main() { 106 // A *p = new A[100]; 107 // delete[] p; 108 // } 109 // Whereas it prints "104" and "104" if you give A a destructor. 110 111 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType); 112 bool requiresArrayCookie(const CXXNewExpr *expr); 113 CharUnits getArrayCookieSizeImpl(QualType type); 114 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 115 llvm::Value *NewPtr, 116 llvm::Value *NumElements, 117 const CXXNewExpr *expr, 118 QualType ElementType); 119 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 120 llvm::Value *allocPtr, 121 CharUnits cookieSize); 122 static bool needThisReturn(GlobalDecl GD); 123 124 private: 125 llvm::Constant *getZeroInt() { 126 return llvm::ConstantInt::get(CGM.IntTy, 0); 127 } 128 129 llvm::Constant *getAllOnesInt() { 130 return llvm::Constant::getAllOnesValue(CGM.IntTy); 131 } 132 133 void 134 GetNullMemberPointerFields(const MemberPointerType *MPT, 135 llvm::SmallVectorImpl<llvm::Constant *> &fields); 136 137 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD, 138 llvm::Value *Base, 139 llvm::Value *VirtualBaseAdjustmentOffset, 140 llvm::Value *VBPtrOffset /* optional */); 141 142 public: 143 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 144 145 virtual bool isZeroInitializable(const MemberPointerType *MPT); 146 147 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 148 149 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 150 CharUnits offset); 151 152 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 153 llvm::Value *MemPtr, 154 const MemberPointerType *MPT); 155 156 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 157 llvm::Value *Base, 158 llvm::Value *MemPtr, 159 const MemberPointerType *MPT); 160 161 virtual llvm::Value * 162 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 163 llvm::Value *&This, 164 llvm::Value *MemPtr, 165 const MemberPointerType *MPT); 166 167 }; 168 169 } 170 171 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 172 llvm::Value *ptr, 173 QualType type) { 174 // FIXME: implement 175 return ptr; 176 } 177 178 bool MicrosoftCXXABI::needThisReturn(GlobalDecl GD) { 179 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl()); 180 return isa<CXXConstructorDecl>(MD); 181 } 182 183 void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 184 CXXCtorType Type, 185 CanQualType &ResTy, 186 SmallVectorImpl<CanQualType> &ArgTys) { 187 // 'this' is already in place 188 189 // Ctor returns this ptr 190 ResTy = ArgTys[0]; 191 192 const CXXRecordDecl *Class = Ctor->getParent(); 193 if (Class->getNumVBases()) { 194 // Constructors of classes with virtual bases take an implicit parameter. 195 ArgTys.push_back(CGM.getContext().IntTy); 196 } 197 } 198 199 llvm::BasicBlock *MicrosoftCXXABI::EmitCtorCompleteObjectHandler( 200 CodeGenFunction &CGF) { 201 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 202 assert(IsMostDerivedClass && 203 "ctor for a class with virtual bases must have an implicit parameter"); 204 llvm::Value *IsCompleteObject 205 = CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 206 207 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 208 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 209 CGF.Builder.CreateCondBr(IsCompleteObject, 210 CallVbaseCtorsBB, SkipVbaseCtorsBB); 211 212 CGF.EmitBlock(CallVbaseCtorsBB); 213 // FIXME: emit vbtables somewhere around here. 214 215 // CGF will put the base ctor calls in this basic block for us later. 216 217 return SkipVbaseCtorsBB; 218 } 219 220 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 221 CXXDtorType Type, 222 CanQualType &ResTy, 223 SmallVectorImpl<CanQualType> &ArgTys) { 224 // 'this' is already in place 225 // TODO: 'for base' flag 226 227 if (Type == Dtor_Deleting) { 228 // The scalar deleting destructor takes an implicit bool parameter. 229 ArgTys.push_back(CGM.getContext().BoolTy); 230 } 231 } 232 233 static bool IsDeletingDtor(GlobalDecl GD) { 234 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl()); 235 if (isa<CXXDestructorDecl>(MD)) { 236 return GD.getDtorType() == Dtor_Deleting; 237 } 238 return false; 239 } 240 241 void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 242 QualType &ResTy, 243 FunctionArgList &Params) { 244 BuildThisParam(CGF, Params); 245 if (needThisReturn(CGF.CurGD)) { 246 ResTy = Params[0]->getType(); 247 } 248 249 ASTContext &Context = getContext(); 250 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 251 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 252 ImplicitParamDecl *IsMostDerived 253 = ImplicitParamDecl::Create(Context, 0, 254 CGF.CurGD.getDecl()->getLocation(), 255 &Context.Idents.get("is_most_derived"), 256 Context.IntTy); 257 Params.push_back(IsMostDerived); 258 getStructorImplicitParamDecl(CGF) = IsMostDerived; 259 } else if (IsDeletingDtor(CGF.CurGD)) { 260 ImplicitParamDecl *ShouldDelete 261 = ImplicitParamDecl::Create(Context, 0, 262 CGF.CurGD.getDecl()->getLocation(), 263 &Context.Idents.get("should_call_delete"), 264 Context.BoolTy); 265 Params.push_back(ShouldDelete); 266 getStructorImplicitParamDecl(CGF) = ShouldDelete; 267 } 268 } 269 270 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 271 EmitThisParam(CGF); 272 if (needThisReturn(CGF.CurGD)) { 273 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 274 } 275 276 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 277 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 278 assert(getStructorImplicitParamDecl(CGF) && 279 "no implicit parameter for a constructor with virtual bases?"); 280 getStructorImplicitParamValue(CGF) 281 = CGF.Builder.CreateLoad( 282 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 283 "is_most_derived"); 284 } 285 286 if (IsDeletingDtor(CGF.CurGD)) { 287 assert(getStructorImplicitParamDecl(CGF) && 288 "no implicit parameter for a deleting destructor?"); 289 getStructorImplicitParamValue(CGF) 290 = CGF.Builder.CreateLoad( 291 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 292 "should_call_delete"); 293 } 294 } 295 296 llvm::Value *MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF, 297 const CXXConstructorDecl *D, 298 CXXCtorType Type, bool ForVirtualBase, 299 bool Delegating, 300 llvm::Value *This, 301 CallExpr::const_arg_iterator ArgBeg, 302 CallExpr::const_arg_iterator ArgEnd) { 303 assert(Type == Ctor_Complete || Type == Ctor_Base); 304 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete); 305 306 llvm::Value *ImplicitParam = 0; 307 QualType ImplicitParamTy; 308 if (D->getParent()->getNumVBases()) { 309 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 310 ImplicitParamTy = getContext().IntTy; 311 } 312 313 // FIXME: Provide a source location here. 314 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This, 315 ImplicitParam, ImplicitParamTy, 316 ArgBeg, ArgEnd); 317 return Callee; 318 } 319 320 RValue MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 321 const CXXDestructorDecl *Dtor, 322 CXXDtorType DtorType, 323 SourceLocation CallLoc, 324 ReturnValueSlot ReturnValue, 325 llvm::Value *This) { 326 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 327 328 // We have only one destructor in the vftable but can get both behaviors 329 // by passing an implicit bool parameter. 330 const CGFunctionInfo *FInfo 331 = &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting); 332 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 333 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, This, Ty); 334 335 ASTContext &Context = CGF.getContext(); 336 llvm::Value *ImplicitParam 337 = llvm::ConstantInt::get(llvm::IntegerType::getInt1Ty(CGF.getLLVMContext()), 338 DtorType == Dtor_Deleting); 339 340 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This, 341 ImplicitParam, Context.BoolTy, 0, 0); 342 } 343 344 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 345 QualType elementType) { 346 // Microsoft seems to completely ignore the possibility of a 347 // two-argument usual deallocation function. 348 return elementType.isDestructedType(); 349 } 350 351 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 352 // Microsoft seems to completely ignore the possibility of a 353 // two-argument usual deallocation function. 354 return expr->getAllocatedType().isDestructedType(); 355 } 356 357 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 358 // The array cookie is always a size_t; we then pad that out to the 359 // alignment of the element type. 360 ASTContext &Ctx = getContext(); 361 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 362 Ctx.getTypeAlignInChars(type)); 363 } 364 365 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 366 llvm::Value *allocPtr, 367 CharUnits cookieSize) { 368 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 369 llvm::Value *numElementsPtr = 370 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 371 return CGF.Builder.CreateLoad(numElementsPtr); 372 } 373 374 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 375 llvm::Value *newPtr, 376 llvm::Value *numElements, 377 const CXXNewExpr *expr, 378 QualType elementType) { 379 assert(requiresArrayCookie(expr)); 380 381 // The size of the cookie. 382 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 383 384 // Compute an offset to the cookie. 385 llvm::Value *cookiePtr = newPtr; 386 387 // Write the number of elements into the appropriate slot. 388 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 389 llvm::Value *numElementsPtr 390 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 391 CGF.Builder.CreateStore(numElements, numElementsPtr); 392 393 // Finally, compute a pointer to the actual data buffer by skipping 394 // over the cookie completely. 395 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 396 cookieSize.getQuantity()); 397 } 398 399 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 400 llvm::GlobalVariable *DeclPtr, 401 bool PerformInit) { 402 // FIXME: this code was only tested for global initialization. 403 // Not sure whether we want thread-safe static local variables as VS 404 // doesn't make them thread-safe. 405 406 if (D.getTLSKind()) 407 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 408 409 // Emit the initializer and add a global destructor if appropriate. 410 CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit); 411 } 412 413 // Member pointer helpers. 414 static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) { 415 return Inheritance == MSIM_Unspecified; 416 } 417 418 // Only member pointers to functions need a this adjustment, since it can be 419 // combined with the field offset for data pointers. 420 static bool hasNonVirtualBaseAdjustmentField(const MemberPointerType *MPT, 421 MSInheritanceModel Inheritance) { 422 return (MPT->isMemberFunctionPointer() && 423 Inheritance >= MSIM_Multiple); 424 } 425 426 static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) { 427 return Inheritance >= MSIM_Virtual; 428 } 429 430 // Use zero for the field offset of a null data member pointer if we can 431 // guarantee that zero is not a valid field offset, or if the member pointer has 432 // multiple fields. Polymorphic classes have a vfptr at offset zero, so we can 433 // use zero for null. If there are multiple fields, we can use zero even if it 434 // is a valid field offset because null-ness testing will check the other 435 // fields. 436 static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) { 437 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single; 438 } 439 440 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 441 // Null-ness for function memptrs only depends on the first field, which is 442 // the function pointer. The rest don't matter, so we can zero initialize. 443 if (MPT->isMemberFunctionPointer()) 444 return true; 445 446 // The virtual base adjustment field is always -1 for null, so if we have one 447 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 448 // valid field offset. 449 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 450 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 451 return (!hasVirtualBaseAdjustmentField(Inheritance) && 452 nullFieldOffsetIsZero(Inheritance)); 453 } 454 455 llvm::Type * 456 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 457 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 458 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 459 llvm::SmallVector<llvm::Type *, 4> fields; 460 if (MPT->isMemberFunctionPointer()) 461 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 462 else 463 fields.push_back(CGM.IntTy); // FieldOffset 464 465 if (hasVBPtrOffsetField(Inheritance)) 466 fields.push_back(CGM.IntTy); 467 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance)) 468 fields.push_back(CGM.IntTy); 469 if (hasVirtualBaseAdjustmentField(Inheritance)) 470 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 471 472 if (fields.size() == 1) 473 return fields[0]; 474 return llvm::StructType::get(CGM.getLLVMContext(), fields); 475 } 476 477 void MicrosoftCXXABI:: 478 GetNullMemberPointerFields(const MemberPointerType *MPT, 479 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 480 assert(fields.empty()); 481 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 482 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 483 if (MPT->isMemberFunctionPointer()) { 484 // FunctionPointerOrVirtualThunk 485 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 486 } else { 487 if (nullFieldOffsetIsZero(Inheritance)) 488 fields.push_back(getZeroInt()); // FieldOffset 489 else 490 fields.push_back(getAllOnesInt()); // FieldOffset 491 } 492 493 if (hasVBPtrOffsetField(Inheritance)) 494 fields.push_back(getZeroInt()); 495 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance)) 496 fields.push_back(getZeroInt()); 497 if (hasVirtualBaseAdjustmentField(Inheritance)) 498 fields.push_back(getAllOnesInt()); 499 } 500 501 llvm::Constant * 502 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 503 llvm::SmallVector<llvm::Constant *, 4> fields; 504 GetNullMemberPointerFields(MPT, fields); 505 if (fields.size() == 1) 506 return fields[0]; 507 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 508 assert(Res->getType() == ConvertMemberPointerType(MPT)); 509 return Res; 510 } 511 512 llvm::Constant * 513 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 514 CharUnits offset) { 515 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 516 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 517 llvm::SmallVector<llvm::Constant *, 4> fields; 518 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity())); 519 if (hasVBPtrOffsetField(Inheritance)) { 520 int64_t VBPtrOffset = 521 getContext().getASTRecordLayout(RD).getVBPtrOffset().getQuantity(); 522 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset)); 523 } 524 assert(!hasNonVirtualBaseAdjustmentField(MPT, Inheritance)); 525 // The virtual base field starts out zero. It is adjusted by conversions to 526 // member pointer types of a more derived class. See http://llvm.org/PR15713 527 if (hasVirtualBaseAdjustmentField(Inheritance)) 528 fields.push_back(getZeroInt()); 529 if (fields.size() == 1) 530 return fields[0]; 531 return llvm::ConstantStruct::getAnon(fields); 532 } 533 534 llvm::Value * 535 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 536 llvm::Value *MemPtr, 537 const MemberPointerType *MPT) { 538 CGBuilderTy &Builder = CGF.Builder; 539 llvm::SmallVector<llvm::Constant *, 4> fields; 540 // We only need one field for member functions. 541 if (MPT->isMemberFunctionPointer()) 542 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 543 else 544 GetNullMemberPointerFields(MPT, fields); 545 assert(!fields.empty()); 546 llvm::Value *FirstField = MemPtr; 547 if (MemPtr->getType()->isStructTy()) 548 FirstField = Builder.CreateExtractValue(MemPtr, 0); 549 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 550 551 // For function member pointers, we only need to test the function pointer 552 // field. The other fields if any can be garbage. 553 if (MPT->isMemberFunctionPointer()) 554 return Res; 555 556 // Otherwise, emit a series of compares and combine the results. 557 for (int I = 1, E = fields.size(); I < E; ++I) { 558 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 559 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 560 Res = Builder.CreateAnd(Res, Next, "memptr.tobool"); 561 } 562 return Res; 563 } 564 565 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 566 // it. 567 llvm::Value * 568 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF, 569 const CXXRecordDecl *RD, llvm::Value *Base, 570 llvm::Value *VirtualBaseAdjustmentOffset, 571 llvm::Value *VBPtrOffset) { 572 CGBuilderTy &Builder = CGF.Builder; 573 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 574 llvm::BasicBlock *OriginalBB = 0; 575 llvm::BasicBlock *SkipAdjustBB = 0; 576 llvm::BasicBlock *VBaseAdjustBB = 0; 577 578 // In the unspecified inheritance model, there might not be a vbtable at all, 579 // in which case we need to skip the virtual base lookup. If there is a 580 // vbtable, the first entry is a no-op entry that gives back the original 581 // base, so look for a virtual base adjustment offset of zero. 582 if (VBPtrOffset) { 583 OriginalBB = Builder.GetInsertBlock(); 584 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 585 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 586 llvm::Value *IsVirtual = 587 Builder.CreateICmpNE(VirtualBaseAdjustmentOffset, getZeroInt(), 588 "memptr.is_vbase"); 589 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 590 CGF.EmitBlock(VBaseAdjustBB); 591 } 592 593 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 594 // know the vbptr offset. 595 if (!VBPtrOffset) { 596 CharUnits offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 597 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 598 } 599 // Load the vbtable pointer from the vbtable offset in the instance. 600 llvm::Value *VBPtr = 601 Builder.CreateInBoundsGEP(Base, VBPtrOffset, "memptr.vbptr"); 602 llvm::Value *VBTable = 603 Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0)); 604 VBTable = Builder.CreateLoad(VBTable, "memptr.vbtable"); 605 // Load an i32 offset from the vb-table. 606 llvm::Value *VBaseOffs = 607 Builder.CreateInBoundsGEP(VBTable, VirtualBaseAdjustmentOffset); 608 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 609 VBaseOffs = Builder.CreateLoad(VBaseOffs, "memptr.vbase_offs"); 610 // Add it to VBPtr. GEP will sign extend the i32 value for us. 611 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 612 613 // Merge control flow with the case where we didn't have to adjust. 614 if (VBaseAdjustBB) { 615 Builder.CreateBr(SkipAdjustBB); 616 CGF.EmitBlock(SkipAdjustBB); 617 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 618 Phi->addIncoming(Base, OriginalBB); 619 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 620 return Phi; 621 } 622 return AdjustedBase; 623 } 624 625 llvm::Value * 626 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 627 llvm::Value *Base, 628 llvm::Value *MemPtr, 629 const MemberPointerType *MPT) { 630 assert(MPT->isMemberDataPointer()); 631 unsigned AS = Base->getType()->getPointerAddressSpace(); 632 llvm::Type *PType = 633 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 634 CGBuilderTy &Builder = CGF.Builder; 635 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 636 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 637 638 // Extract the fields we need, regardless of model. We'll apply them if we 639 // have them. 640 llvm::Value *FieldOffset = MemPtr; 641 llvm::Value *VirtualBaseAdjustmentOffset = 0; 642 llvm::Value *VBPtrOffset = 0; 643 if (MemPtr->getType()->isStructTy()) { 644 // We need to extract values. 645 unsigned I = 0; 646 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 647 if (hasVBPtrOffsetField(Inheritance)) 648 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 649 if (hasVirtualBaseAdjustmentField(Inheritance)) 650 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 651 } 652 653 if (VirtualBaseAdjustmentOffset) { 654 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset, 655 VBPtrOffset); 656 } 657 llvm::Value *Addr = 658 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 659 660 // Cast the address to the appropriate pointer type, adopting the address 661 // space of the base pointer. 662 return Builder.CreateBitCast(Addr, PType); 663 } 664 665 llvm::Value * 666 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 667 llvm::Value *&This, 668 llvm::Value *MemPtr, 669 const MemberPointerType *MPT) { 670 assert(MPT->isMemberFunctionPointer()); 671 const FunctionProtoType *FPT = 672 MPT->getPointeeType()->castAs<FunctionProtoType>(); 673 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 674 llvm::FunctionType *FTy = 675 CGM.getTypes().GetFunctionType( 676 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 677 CGBuilderTy &Builder = CGF.Builder; 678 679 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 680 681 // Extract the fields we need, regardless of model. We'll apply them if we 682 // have them. 683 llvm::Value *FunctionPointer = MemPtr; 684 llvm::Value *NonVirtualBaseAdjustment = NULL; 685 llvm::Value *VirtualBaseAdjustmentOffset = NULL; 686 llvm::Value *VBPtrOffset = NULL; 687 if (MemPtr->getType()->isStructTy()) { 688 // We need to extract values. 689 unsigned I = 0; 690 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 691 if (hasVBPtrOffsetField(Inheritance)) 692 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 693 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance)) 694 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 695 if (hasVirtualBaseAdjustmentField(Inheritance)) 696 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 697 } 698 699 if (VirtualBaseAdjustmentOffset) { 700 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset, 701 VBPtrOffset); 702 } 703 704 if (NonVirtualBaseAdjustment) { 705 // Apply the adjustment and cast back to the original struct type. 706 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 707 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 708 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 709 } 710 711 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 712 } 713 714 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 715 return new MicrosoftCXXABI(CGM); 716 } 717 718