1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This provides C++ code generation targeting the Microsoft Visual C++ ABI. 10 // The class in this file generates structures that follow the Microsoft 11 // Visual C++ ABI, which is actually not very well documented at all outside 12 // of Microsoft. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "CGCXXABI.h" 17 #include "CGCleanup.h" 18 #include "CGVTables.h" 19 #include "CodeGenModule.h" 20 #include "CodeGenTypes.h" 21 #include "TargetInfo.h" 22 #include "clang/AST/CXXInheritance.h" 23 #include "clang/AST/Decl.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/AST/StmtCXX.h" 26 #include "clang/AST/VTableBuilder.h" 27 #include "clang/CodeGen/ConstantInitBuilder.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/ADT/StringSet.h" 30 #include "llvm/IR/Intrinsics.h" 31 32 using namespace clang; 33 using namespace CodeGen; 34 35 namespace { 36 37 /// Holds all the vbtable globals for a given class. 38 struct VBTableGlobals { 39 const VPtrInfoVector *VBTables; 40 SmallVector<llvm::GlobalVariable *, 2> Globals; 41 }; 42 43 class MicrosoftCXXABI : public CGCXXABI { 44 public: 45 MicrosoftCXXABI(CodeGenModule &CGM) 46 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr), 47 ClassHierarchyDescriptorType(nullptr), 48 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr), 49 ThrowInfoType(nullptr) {} 50 51 bool HasThisReturn(GlobalDecl GD) const override; 52 bool hasMostDerivedReturn(GlobalDecl GD) const override; 53 54 bool classifyReturnType(CGFunctionInfo &FI) const override; 55 56 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override; 57 58 bool isSRetParameterAfterThis() const override { return true; } 59 60 bool isThisCompleteObject(GlobalDecl GD) const override { 61 // The Microsoft ABI doesn't use separate complete-object vs. 62 // base-object variants of constructors, but it does of destructors. 63 if (isa<CXXDestructorDecl>(GD.getDecl())) { 64 switch (GD.getDtorType()) { 65 case Dtor_Complete: 66 case Dtor_Deleting: 67 return true; 68 69 case Dtor_Base: 70 return false; 71 72 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?"); 73 } 74 llvm_unreachable("bad dtor kind"); 75 } 76 77 // No other kinds. 78 return false; 79 } 80 81 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD, 82 FunctionArgList &Args) const override { 83 assert(Args.size() >= 2 && 84 "expected the arglist to have at least two args!"); 85 // The 'most_derived' parameter goes second if the ctor is variadic and 86 // has v-bases. 87 if (CD->getParent()->getNumVBases() > 0 && 88 CD->getType()->castAs<FunctionProtoType>()->isVariadic()) 89 return 2; 90 return 1; 91 } 92 93 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override { 94 std::vector<CharUnits> VBPtrOffsets; 95 const ASTContext &Context = getContext(); 96 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 97 98 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 99 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) { 100 const ASTRecordLayout &SubobjectLayout = 101 Context.getASTRecordLayout(VBT->IntroducingObject); 102 CharUnits Offs = VBT->NonVirtualOffset; 103 Offs += SubobjectLayout.getVBPtrOffset(); 104 if (VBT->getVBaseWithVPtr()) 105 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr()); 106 VBPtrOffsets.push_back(Offs); 107 } 108 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end()); 109 return VBPtrOffsets; 110 } 111 112 StringRef GetPureVirtualCallName() override { return "_purecall"; } 113 StringRef GetDeletedVirtualCallName() override { return "_purecall"; } 114 115 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, 116 Address Ptr, QualType ElementType, 117 const CXXDestructorDecl *Dtor) override; 118 119 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override; 120 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override; 121 122 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override; 123 124 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD, 125 const VPtrInfo &Info); 126 127 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 128 CatchTypeInfo 129 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override; 130 131 /// MSVC needs an extra flag to indicate a catchall. 132 CatchTypeInfo getCatchAllTypeInfo() override { 133 return CatchTypeInfo{nullptr, 0x40}; 134 } 135 136 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 137 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 138 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 139 Address ThisPtr, 140 llvm::Type *StdTypeInfoPtrTy) override; 141 142 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 143 QualType SrcRecordTy) override; 144 145 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value, 146 QualType SrcRecordTy, QualType DestTy, 147 QualType DestRecordTy, 148 llvm::BasicBlock *CastEnd) override; 149 150 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, 151 QualType SrcRecordTy, 152 QualType DestTy) override; 153 154 bool EmitBadCastCall(CodeGenFunction &CGF) override; 155 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override { 156 return false; 157 } 158 159 llvm::Value * 160 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, 161 const CXXRecordDecl *ClassDecl, 162 const CXXRecordDecl *BaseClassDecl) override; 163 164 llvm::BasicBlock * 165 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 166 const CXXRecordDecl *RD) override; 167 168 llvm::BasicBlock * 169 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF); 170 171 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, 172 const CXXRecordDecl *RD) override; 173 174 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 175 176 // Background on MSVC destructors 177 // ============================== 178 // 179 // Both Itanium and MSVC ABIs have destructor variants. The variant names 180 // roughly correspond in the following way: 181 // Itanium Microsoft 182 // Base -> no name, just ~Class 183 // Complete -> vbase destructor 184 // Deleting -> scalar deleting destructor 185 // vector deleting destructor 186 // 187 // The base and complete destructors are the same as in Itanium, although the 188 // complete destructor does not accept a VTT parameter when there are virtual 189 // bases. A separate mechanism involving vtordisps is used to ensure that 190 // virtual methods of destroyed subobjects are not called. 191 // 192 // The deleting destructors accept an i32 bitfield as a second parameter. Bit 193 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this 194 // pointer points to an array. The scalar deleting destructor assumes that 195 // bit 2 is zero, and therefore does not contain a loop. 196 // 197 // For virtual destructors, only one entry is reserved in the vftable, and it 198 // always points to the vector deleting destructor. The vector deleting 199 // destructor is the most general, so it can be used to destroy objects in 200 // place, delete single heap objects, or delete arrays. 201 // 202 // A TU defining a non-inline destructor is only guaranteed to emit a base 203 // destructor, and all of the other variants are emitted on an as-needed basis 204 // in COMDATs. Because a non-base destructor can be emitted in a TU that 205 // lacks a definition for the destructor, non-base destructors must always 206 // delegate to or alias the base destructor. 207 208 AddedStructorArgs 209 buildStructorSignature(GlobalDecl GD, 210 SmallVectorImpl<CanQualType> &ArgTys) override; 211 212 /// Non-base dtors should be emitted as delegating thunks in this ABI. 213 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 214 CXXDtorType DT) const override { 215 return DT != Dtor_Base; 216 } 217 218 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, 219 const CXXDestructorDecl *Dtor, 220 CXXDtorType DT) const override; 221 222 llvm::GlobalValue::LinkageTypes 223 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, 224 CXXDtorType DT) const override; 225 226 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 227 228 const CXXRecordDecl * 229 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override { 230 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { 231 MethodVFTableLocation ML = 232 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 233 // The vbases might be ordered differently in the final overrider object 234 // and the complete object, so the "this" argument may sometimes point to 235 // memory that has no particular type (e.g. past the complete object). 236 // In this case, we just use a generic pointer type. 237 // FIXME: might want to have a more precise type in the non-virtual 238 // multiple inheritance case. 239 if (ML.VBase || !ML.VFPtrOffset.isZero()) 240 return nullptr; 241 } 242 return MD->getParent(); 243 } 244 245 Address 246 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, 247 Address This, 248 bool VirtualCall) override; 249 250 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 251 FunctionArgList &Params) override; 252 253 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 254 255 AddedStructorArgs 256 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D, 257 CXXCtorType Type, bool ForVirtualBase, 258 bool Delegating, CallArgList &Args) override; 259 260 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 261 CXXDtorType Type, bool ForVirtualBase, 262 bool Delegating, Address This, 263 QualType ThisTy) override; 264 265 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD, 266 llvm::GlobalVariable *VTable); 267 268 void emitVTableDefinitions(CodeGenVTables &CGVT, 269 const CXXRecordDecl *RD) override; 270 271 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF, 272 CodeGenFunction::VPtr Vptr) override; 273 274 /// Don't initialize vptrs if dynamic class 275 /// is marked with with the 'novtable' attribute. 276 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override { 277 return !VTableClass->hasAttr<MSNoVTableAttr>(); 278 } 279 280 llvm::Constant * 281 getVTableAddressPoint(BaseSubobject Base, 282 const CXXRecordDecl *VTableClass) override; 283 284 llvm::Value *getVTableAddressPointInStructor( 285 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 286 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override; 287 288 llvm::Constant * 289 getVTableAddressPointForConstExpr(BaseSubobject Base, 290 const CXXRecordDecl *VTableClass) override; 291 292 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 293 CharUnits VPtrOffset) override; 294 295 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 296 Address This, llvm::Type *Ty, 297 SourceLocation Loc) override; 298 299 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF, 300 const CXXDestructorDecl *Dtor, 301 CXXDtorType DtorType, Address This, 302 DeleteOrMemberCallExpr E) override; 303 304 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, 305 CallArgList &CallArgs) override { 306 assert(GD.getDtorType() == Dtor_Deleting && 307 "Only deleting destructor thunks are available in this ABI"); 308 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)), 309 getContext().IntTy); 310 } 311 312 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 313 314 llvm::GlobalVariable * 315 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 316 llvm::GlobalVariable::LinkageTypes Linkage); 317 318 llvm::GlobalVariable * 319 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD, 320 const CXXRecordDecl *DstRD) { 321 SmallString<256> OutName; 322 llvm::raw_svector_ostream Out(OutName); 323 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out); 324 StringRef MangledName = OutName.str(); 325 326 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName)) 327 return VDispMap; 328 329 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 330 unsigned NumEntries = 1 + SrcRD->getNumVBases(); 331 SmallVector<llvm::Constant *, 4> Map(NumEntries, 332 llvm::UndefValue::get(CGM.IntTy)); 333 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0); 334 bool AnyDifferent = false; 335 for (const auto &I : SrcRD->vbases()) { 336 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl(); 337 if (!DstRD->isVirtuallyDerivedFrom(VBase)) 338 continue; 339 340 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase); 341 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase); 342 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4); 343 AnyDifferent |= SrcVBIndex != DstVBIndex; 344 } 345 // This map would be useless, don't use it. 346 if (!AnyDifferent) 347 return nullptr; 348 349 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size()); 350 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map); 351 llvm::GlobalValue::LinkageTypes Linkage = 352 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible() 353 ? llvm::GlobalValue::LinkOnceODRLinkage 354 : llvm::GlobalValue::InternalLinkage; 355 auto *VDispMap = new llvm::GlobalVariable( 356 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage, 357 /*Initializer=*/Init, MangledName); 358 return VDispMap; 359 } 360 361 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD, 362 llvm::GlobalVariable *GV) const; 363 364 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, 365 GlobalDecl GD, bool ReturnAdjustment) override { 366 GVALinkage Linkage = 367 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl())); 368 369 if (Linkage == GVA_Internal) 370 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage); 371 else if (ReturnAdjustment) 372 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage); 373 else 374 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 375 } 376 377 bool exportThunk() override { return false; } 378 379 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This, 380 const ThisAdjustment &TA) override; 381 382 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 383 const ReturnAdjustment &RA) override; 384 385 void EmitThreadLocalInitFuncs( 386 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals, 387 ArrayRef<llvm::Function *> CXXThreadLocalInits, 388 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override; 389 390 bool usesThreadWrapperFunction(const VarDecl *VD) const override { 391 return false; 392 } 393 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, 394 QualType LValType) override; 395 396 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 397 llvm::GlobalVariable *DeclPtr, 398 bool PerformInit) override; 399 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 400 llvm::FunctionCallee Dtor, 401 llvm::Constant *Addr) override; 402 403 // ==== Notes on array cookies ========= 404 // 405 // MSVC seems to only use cookies when the class has a destructor; a 406 // two-argument usual array deallocation function isn't sufficient. 407 // 408 // For example, this code prints "100" and "1": 409 // struct A { 410 // char x; 411 // void *operator new[](size_t sz) { 412 // printf("%u\n", sz); 413 // return malloc(sz); 414 // } 415 // void operator delete[](void *p, size_t sz) { 416 // printf("%u\n", sz); 417 // free(p); 418 // } 419 // }; 420 // int main() { 421 // A *p = new A[100]; 422 // delete[] p; 423 // } 424 // Whereas it prints "104" and "104" if you give A a destructor. 425 426 bool requiresArrayCookie(const CXXDeleteExpr *expr, 427 QualType elementType) override; 428 bool requiresArrayCookie(const CXXNewExpr *expr) override; 429 CharUnits getArrayCookieSizeImpl(QualType type) override; 430 Address InitializeArrayCookie(CodeGenFunction &CGF, 431 Address NewPtr, 432 llvm::Value *NumElements, 433 const CXXNewExpr *expr, 434 QualType ElementType) override; 435 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 436 Address allocPtr, 437 CharUnits cookieSize) override; 438 439 friend struct MSRTTIBuilder; 440 441 bool isImageRelative() const { 442 return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64; 443 } 444 445 // 5 routines for constructing the llvm types for MS RTTI structs. 446 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) { 447 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor"); 448 TDTypeName += llvm::utostr(TypeInfoString.size()); 449 llvm::StructType *&TypeDescriptorType = 450 TypeDescriptorTypeMap[TypeInfoString.size()]; 451 if (TypeDescriptorType) 452 return TypeDescriptorType; 453 llvm::Type *FieldTypes[] = { 454 CGM.Int8PtrPtrTy, 455 CGM.Int8PtrTy, 456 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)}; 457 TypeDescriptorType = 458 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName); 459 return TypeDescriptorType; 460 } 461 462 llvm::Type *getImageRelativeType(llvm::Type *PtrType) { 463 if (!isImageRelative()) 464 return PtrType; 465 return CGM.IntTy; 466 } 467 468 llvm::StructType *getBaseClassDescriptorType() { 469 if (BaseClassDescriptorType) 470 return BaseClassDescriptorType; 471 llvm::Type *FieldTypes[] = { 472 getImageRelativeType(CGM.Int8PtrTy), 473 CGM.IntTy, 474 CGM.IntTy, 475 CGM.IntTy, 476 CGM.IntTy, 477 CGM.IntTy, 478 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()), 479 }; 480 BaseClassDescriptorType = llvm::StructType::create( 481 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor"); 482 return BaseClassDescriptorType; 483 } 484 485 llvm::StructType *getClassHierarchyDescriptorType() { 486 if (ClassHierarchyDescriptorType) 487 return ClassHierarchyDescriptorType; 488 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle. 489 ClassHierarchyDescriptorType = llvm::StructType::create( 490 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor"); 491 llvm::Type *FieldTypes[] = { 492 CGM.IntTy, 493 CGM.IntTy, 494 CGM.IntTy, 495 getImageRelativeType( 496 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()), 497 }; 498 ClassHierarchyDescriptorType->setBody(FieldTypes); 499 return ClassHierarchyDescriptorType; 500 } 501 502 llvm::StructType *getCompleteObjectLocatorType() { 503 if (CompleteObjectLocatorType) 504 return CompleteObjectLocatorType; 505 CompleteObjectLocatorType = llvm::StructType::create( 506 CGM.getLLVMContext(), "rtti.CompleteObjectLocator"); 507 llvm::Type *FieldTypes[] = { 508 CGM.IntTy, 509 CGM.IntTy, 510 CGM.IntTy, 511 getImageRelativeType(CGM.Int8PtrTy), 512 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()), 513 getImageRelativeType(CompleteObjectLocatorType), 514 }; 515 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes); 516 if (!isImageRelative()) 517 FieldTypesRef = FieldTypesRef.drop_back(); 518 CompleteObjectLocatorType->setBody(FieldTypesRef); 519 return CompleteObjectLocatorType; 520 } 521 522 llvm::GlobalVariable *getImageBase() { 523 StringRef Name = "__ImageBase"; 524 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name)) 525 return GV; 526 527 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, 528 /*isConstant=*/true, 529 llvm::GlobalValue::ExternalLinkage, 530 /*Initializer=*/nullptr, Name); 531 CGM.setDSOLocal(GV); 532 return GV; 533 } 534 535 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) { 536 if (!isImageRelative()) 537 return PtrVal; 538 539 if (PtrVal->isNullValue()) 540 return llvm::Constant::getNullValue(CGM.IntTy); 541 542 llvm::Constant *ImageBaseAsInt = 543 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy); 544 llvm::Constant *PtrValAsInt = 545 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy); 546 llvm::Constant *Diff = 547 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt, 548 /*HasNUW=*/true, /*HasNSW=*/true); 549 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy); 550 } 551 552 private: 553 MicrosoftMangleContext &getMangleContext() { 554 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 555 } 556 557 llvm::Constant *getZeroInt() { 558 return llvm::ConstantInt::get(CGM.IntTy, 0); 559 } 560 561 llvm::Constant *getAllOnesInt() { 562 return llvm::Constant::getAllOnesValue(CGM.IntTy); 563 } 564 565 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override; 566 567 void 568 GetNullMemberPointerFields(const MemberPointerType *MPT, 569 llvm::SmallVectorImpl<llvm::Constant *> &fields); 570 571 /// Shared code for virtual base adjustment. Returns the offset from 572 /// the vbptr to the virtual base. Optionally returns the address of the 573 /// vbptr itself. 574 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 575 Address Base, 576 llvm::Value *VBPtrOffset, 577 llvm::Value *VBTableOffset, 578 llvm::Value **VBPtr = nullptr); 579 580 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 581 Address Base, 582 int32_t VBPtrOffset, 583 int32_t VBTableOffset, 584 llvm::Value **VBPtr = nullptr) { 585 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s"); 586 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 587 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset); 588 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr); 589 } 590 591 std::tuple<Address, llvm::Value *, const CXXRecordDecl *> 592 performBaseAdjustment(CodeGenFunction &CGF, Address Value, 593 QualType SrcRecordTy); 594 595 /// Performs a full virtual base adjustment. Used to dereference 596 /// pointers to members of virtual bases. 597 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E, 598 const CXXRecordDecl *RD, Address Base, 599 llvm::Value *VirtualBaseAdjustmentOffset, 600 llvm::Value *VBPtrOffset /* optional */); 601 602 /// Emits a full member pointer with the fields common to data and 603 /// function member pointers. 604 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField, 605 bool IsMemberFunction, 606 const CXXRecordDecl *RD, 607 CharUnits NonVirtualBaseAdjustment, 608 unsigned VBTableIndex); 609 610 bool MemberPointerConstantIsNull(const MemberPointerType *MPT, 611 llvm::Constant *MP); 612 613 /// - Initialize all vbptrs of 'this' with RD as the complete type. 614 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD); 615 616 /// Caching wrapper around VBTableBuilder::enumerateVBTables(). 617 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD); 618 619 /// Generate a thunk for calling a virtual member function MD. 620 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD, 621 const MethodVFTableLocation &ML); 622 623 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD, 624 CharUnits offset); 625 626 public: 627 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 628 629 bool isZeroInitializable(const MemberPointerType *MPT) override; 630 631 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override { 632 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 633 return RD->hasAttr<MSInheritanceAttr>(); 634 } 635 636 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 637 638 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 639 CharUnits offset) override; 640 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override; 641 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 642 643 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 644 llvm::Value *L, 645 llvm::Value *R, 646 const MemberPointerType *MPT, 647 bool Inequality) override; 648 649 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 650 llvm::Value *MemPtr, 651 const MemberPointerType *MPT) override; 652 653 llvm::Value * 654 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 655 Address Base, llvm::Value *MemPtr, 656 const MemberPointerType *MPT) override; 657 658 llvm::Value *EmitNonNullMemberPointerConversion( 659 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, 660 CastKind CK, CastExpr::path_const_iterator PathBegin, 661 CastExpr::path_const_iterator PathEnd, llvm::Value *Src, 662 CGBuilderTy &Builder); 663 664 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 665 const CastExpr *E, 666 llvm::Value *Src) override; 667 668 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 669 llvm::Constant *Src) override; 670 671 llvm::Constant *EmitMemberPointerConversion( 672 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, 673 CastKind CK, CastExpr::path_const_iterator PathBegin, 674 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src); 675 676 CGCallee 677 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, 678 Address This, llvm::Value *&ThisPtrForCall, 679 llvm::Value *MemPtr, 680 const MemberPointerType *MPT) override; 681 682 void emitCXXStructor(GlobalDecl GD) override; 683 684 llvm::StructType *getCatchableTypeType() { 685 if (CatchableTypeType) 686 return CatchableTypeType; 687 llvm::Type *FieldTypes[] = { 688 CGM.IntTy, // Flags 689 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor 690 CGM.IntTy, // NonVirtualAdjustment 691 CGM.IntTy, // OffsetToVBPtr 692 CGM.IntTy, // VBTableIndex 693 CGM.IntTy, // Size 694 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor 695 }; 696 CatchableTypeType = llvm::StructType::create( 697 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType"); 698 return CatchableTypeType; 699 } 700 701 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) { 702 llvm::StructType *&CatchableTypeArrayType = 703 CatchableTypeArrayTypeMap[NumEntries]; 704 if (CatchableTypeArrayType) 705 return CatchableTypeArrayType; 706 707 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray."); 708 CTATypeName += llvm::utostr(NumEntries); 709 llvm::Type *CTType = 710 getImageRelativeType(getCatchableTypeType()->getPointerTo()); 711 llvm::Type *FieldTypes[] = { 712 CGM.IntTy, // NumEntries 713 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes 714 }; 715 CatchableTypeArrayType = 716 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName); 717 return CatchableTypeArrayType; 718 } 719 720 llvm::StructType *getThrowInfoType() { 721 if (ThrowInfoType) 722 return ThrowInfoType; 723 llvm::Type *FieldTypes[] = { 724 CGM.IntTy, // Flags 725 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn 726 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat 727 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray 728 }; 729 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, 730 "eh.ThrowInfo"); 731 return ThrowInfoType; 732 } 733 734 llvm::FunctionCallee getThrowFn() { 735 // _CxxThrowException is passed an exception object and a ThrowInfo object 736 // which describes the exception. 737 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()}; 738 llvm::FunctionType *FTy = 739 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false); 740 llvm::FunctionCallee Throw = 741 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"); 742 // _CxxThrowException is stdcall on 32-bit x86 platforms. 743 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) { 744 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee())) 745 Fn->setCallingConv(llvm::CallingConv::X86_StdCall); 746 } 747 return Throw; 748 } 749 750 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD, 751 CXXCtorType CT); 752 753 llvm::Constant *getCatchableType(QualType T, 754 uint32_t NVOffset = 0, 755 int32_t VBPtrOffset = -1, 756 uint32_t VBIndex = 0); 757 758 llvm::GlobalVariable *getCatchableTypeArray(QualType T); 759 760 llvm::GlobalVariable *getThrowInfo(QualType T) override; 761 762 std::pair<llvm::Value *, const CXXRecordDecl *> 763 LoadVTablePtr(CodeGenFunction &CGF, Address This, 764 const CXXRecordDecl *RD) override; 765 766 private: 767 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy; 768 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy; 769 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy; 770 /// All the vftables that have been referenced. 771 VFTablesMapTy VFTablesMap; 772 VTablesMapTy VTablesMap; 773 774 /// This set holds the record decls we've deferred vtable emission for. 775 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables; 776 777 778 /// All the vbtables which have been referenced. 779 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap; 780 781 /// Info on the global variable used to guard initialization of static locals. 782 /// The BitIndex field is only used for externally invisible declarations. 783 struct GuardInfo { 784 GuardInfo() : Guard(nullptr), BitIndex(0) {} 785 llvm::GlobalVariable *Guard; 786 unsigned BitIndex; 787 }; 788 789 /// Map from DeclContext to the current guard variable. We assume that the 790 /// AST is visited in source code order. 791 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap; 792 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap; 793 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap; 794 795 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap; 796 llvm::StructType *BaseClassDescriptorType; 797 llvm::StructType *ClassHierarchyDescriptorType; 798 llvm::StructType *CompleteObjectLocatorType; 799 800 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays; 801 802 llvm::StructType *CatchableTypeType; 803 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap; 804 llvm::StructType *ThrowInfoType; 805 }; 806 807 } 808 809 CGCXXABI::RecordArgABI 810 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const { 811 switch (CGM.getTarget().getTriple().getArch()) { 812 default: 813 // FIXME: Implement for other architectures. 814 return RAA_Default; 815 816 case llvm::Triple::thumb: 817 // Use the simple Itanium rules for now. 818 // FIXME: This is incompatible with MSVC for arguments with a dtor and no 819 // copy ctor. 820 return !RD->canPassInRegisters() ? RAA_Indirect : RAA_Default; 821 822 case llvm::Triple::x86: 823 // All record arguments are passed in memory on x86. Decide whether to 824 // construct the object directly in argument memory, or to construct the 825 // argument elsewhere and copy the bytes during the call. 826 827 // If C++ prohibits us from making a copy, construct the arguments directly 828 // into argument memory. 829 if (!RD->canPassInRegisters()) 830 return RAA_DirectInMemory; 831 832 // Otherwise, construct the argument into a temporary and copy the bytes 833 // into the outgoing argument memory. 834 return RAA_Default; 835 836 case llvm::Triple::x86_64: 837 case llvm::Triple::aarch64: 838 return !RD->canPassInRegisters() ? RAA_Indirect : RAA_Default; 839 } 840 841 llvm_unreachable("invalid enum"); 842 } 843 844 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF, 845 const CXXDeleteExpr *DE, 846 Address Ptr, 847 QualType ElementType, 848 const CXXDestructorDecl *Dtor) { 849 // FIXME: Provide a source location here even though there's no 850 // CXXMemberCallExpr for dtor call. 851 bool UseGlobalDelete = DE->isGlobalDelete(); 852 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting; 853 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE); 854 if (UseGlobalDelete) 855 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType); 856 } 857 858 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) { 859 llvm::Value *Args[] = { 860 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), 861 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())}; 862 llvm::FunctionCallee Fn = getThrowFn(); 863 if (isNoReturn) 864 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args); 865 else 866 CGF.EmitRuntimeCallOrInvoke(Fn, Args); 867 } 868 869 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF, 870 const CXXCatchStmt *S) { 871 // In the MS ABI, the runtime handles the copy, and the catch handler is 872 // responsible for destruction. 873 VarDecl *CatchParam = S->getExceptionDecl(); 874 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock(); 875 llvm::CatchPadInst *CPI = 876 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI()); 877 CGF.CurrentFuncletPad = CPI; 878 879 // If this is a catch-all or the catch parameter is unnamed, we don't need to 880 // emit an alloca to the object. 881 if (!CatchParam || !CatchParam->getDeclName()) { 882 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI); 883 return; 884 } 885 886 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); 887 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer()); 888 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI); 889 CGF.EmitAutoVarCleanups(var); 890 } 891 892 /// We need to perform a generic polymorphic operation (like a typeid 893 /// or a cast), which requires an object with a vfptr. Adjust the 894 /// address to point to an object with a vfptr. 895 std::tuple<Address, llvm::Value *, const CXXRecordDecl *> 896 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value, 897 QualType SrcRecordTy) { 898 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy); 899 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 900 const ASTContext &Context = getContext(); 901 902 // If the class itself has a vfptr, great. This check implicitly 903 // covers non-virtual base subobjects: a class with its own virtual 904 // functions would be a candidate to be a primary base. 905 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr()) 906 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0), 907 SrcDecl); 908 909 // Okay, one of the vbases must have a vfptr, or else this isn't 910 // actually a polymorphic class. 911 const CXXRecordDecl *PolymorphicBase = nullptr; 912 for (auto &Base : SrcDecl->vbases()) { 913 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl(); 914 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) { 915 PolymorphicBase = BaseDecl; 916 break; 917 } 918 } 919 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?"); 920 921 llvm::Value *Offset = 922 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase); 923 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset); 924 CharUnits VBaseAlign = 925 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase); 926 return std::make_tuple(Address(Ptr, VBaseAlign), Offset, PolymorphicBase); 927 } 928 929 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 930 QualType SrcRecordTy) { 931 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 932 return IsDeref && 933 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 934 } 935 936 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF, 937 llvm::Value *Argument) { 938 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 939 llvm::FunctionType *FTy = 940 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false); 941 llvm::Value *Args[] = {Argument}; 942 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid"); 943 return CGF.EmitRuntimeCallOrInvoke(Fn, Args); 944 } 945 946 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 947 llvm::CallBase *Call = 948 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy)); 949 Call->setDoesNotReturn(); 950 CGF.Builder.CreateUnreachable(); 951 } 952 953 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF, 954 QualType SrcRecordTy, 955 Address ThisPtr, 956 llvm::Type *StdTypeInfoPtrTy) { 957 std::tie(ThisPtr, std::ignore, std::ignore) = 958 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy); 959 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer()); 960 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy); 961 } 962 963 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 964 QualType SrcRecordTy) { 965 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 966 return SrcIsPtr && 967 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 968 } 969 970 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall( 971 CodeGenFunction &CGF, Address This, QualType SrcRecordTy, 972 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 973 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 974 975 llvm::Value *SrcRTTI = 976 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 977 llvm::Value *DestRTTI = 978 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 979 980 llvm::Value *Offset; 981 std::tie(This, Offset, std::ignore) = 982 performBaseAdjustment(CGF, This, SrcRecordTy); 983 llvm::Value *ThisPtr = This.getPointer(); 984 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty); 985 986 // PVOID __RTDynamicCast( 987 // PVOID inptr, 988 // LONG VfDelta, 989 // PVOID SrcType, 990 // PVOID TargetType, 991 // BOOL isReference) 992 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy, 993 CGF.Int8PtrTy, CGF.Int32Ty}; 994 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction( 995 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 996 "__RTDynamicCast"); 997 llvm::Value *Args[] = { 998 ThisPtr, Offset, SrcRTTI, DestRTTI, 999 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())}; 1000 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args); 1001 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy); 1002 } 1003 1004 llvm::Value * 1005 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, 1006 QualType SrcRecordTy, 1007 QualType DestTy) { 1008 std::tie(Value, std::ignore, std::ignore) = 1009 performBaseAdjustment(CGF, Value, SrcRecordTy); 1010 1011 // PVOID __RTCastToVoid( 1012 // PVOID inptr) 1013 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 1014 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction( 1015 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 1016 "__RTCastToVoid"); 1017 llvm::Value *Args[] = {Value.getPointer()}; 1018 return CGF.EmitRuntimeCall(Function, Args); 1019 } 1020 1021 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 1022 return false; 1023 } 1024 1025 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset( 1026 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl, 1027 const CXXRecordDecl *BaseClassDecl) { 1028 const ASTContext &Context = getContext(); 1029 int64_t VBPtrChars = 1030 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity(); 1031 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars); 1032 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy); 1033 CharUnits VBTableChars = 1034 IntSize * 1035 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl); 1036 llvm::Value *VBTableOffset = 1037 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity()); 1038 1039 llvm::Value *VBPtrToNewBase = 1040 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset); 1041 VBPtrToNewBase = 1042 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy); 1043 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase); 1044 } 1045 1046 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const { 1047 return isa<CXXConstructorDecl>(GD.getDecl()); 1048 } 1049 1050 static bool isDeletingDtor(GlobalDecl GD) { 1051 return isa<CXXDestructorDecl>(GD.getDecl()) && 1052 GD.getDtorType() == Dtor_Deleting; 1053 } 1054 1055 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const { 1056 return isDeletingDtor(GD); 1057 } 1058 1059 static bool IsSizeGreaterThan128(const CXXRecordDecl *RD) { 1060 return RD->getASTContext().getTypeSize(RD->getTypeForDecl()) > 128; 1061 } 1062 1063 static bool hasMicrosoftABIRestrictions(const CXXRecordDecl *RD) { 1064 // For AArch64, we use the C++14 definition of an aggregate, so we also 1065 // check for: 1066 // No private or protected non static data members. 1067 // No base classes 1068 // No virtual functions 1069 // Additionally, we need to ensure that there is a trivial copy assignment 1070 // operator, a trivial destructor and no user-provided constructors. 1071 if (RD->hasProtectedFields() || RD->hasPrivateFields()) 1072 return true; 1073 if (RD->getNumBases() > 0) 1074 return true; 1075 if (RD->isPolymorphic()) 1076 return true; 1077 if (RD->hasNonTrivialCopyAssignment()) 1078 return true; 1079 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1080 if (Ctor->isUserProvided()) 1081 return true; 1082 if (RD->hasNonTrivialDestructor()) 1083 return true; 1084 return false; 1085 } 1086 1087 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 1088 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 1089 if (!RD) 1090 return false; 1091 1092 bool isAArch64 = CGM.getTarget().getTriple().isAArch64(); 1093 bool isSimple = !isAArch64 || !hasMicrosoftABIRestrictions(RD); 1094 bool isIndirectReturn = 1095 isAArch64 ? (!RD->canPassInRegisters() || 1096 IsSizeGreaterThan128(RD)) 1097 : !RD->isPOD(); 1098 bool isInstanceMethod = FI.isInstanceMethod(); 1099 1100 if (isIndirectReturn || !isSimple || isInstanceMethod) { 1101 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType()); 1102 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 1103 FI.getReturnInfo().setSRetAfterThis(isInstanceMethod); 1104 1105 FI.getReturnInfo().setInReg(isAArch64 && 1106 !(isSimple && IsSizeGreaterThan128(RD))); 1107 1108 return true; 1109 } 1110 1111 // Otherwise, use the C ABI rules. 1112 return false; 1113 } 1114 1115 llvm::BasicBlock * 1116 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 1117 const CXXRecordDecl *RD) { 1118 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 1119 assert(IsMostDerivedClass && 1120 "ctor for a class with virtual bases must have an implicit parameter"); 1121 llvm::Value *IsCompleteObject = 1122 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 1123 1124 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 1125 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 1126 CGF.Builder.CreateCondBr(IsCompleteObject, 1127 CallVbaseCtorsBB, SkipVbaseCtorsBB); 1128 1129 CGF.EmitBlock(CallVbaseCtorsBB); 1130 1131 // Fill in the vbtable pointers here. 1132 EmitVBPtrStores(CGF, RD); 1133 1134 // CGF will put the base ctor calls in this basic block for us later. 1135 1136 return SkipVbaseCtorsBB; 1137 } 1138 1139 llvm::BasicBlock * 1140 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) { 1141 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 1142 assert(IsMostDerivedClass && 1143 "ctor for a class with virtual bases must have an implicit parameter"); 1144 llvm::Value *IsCompleteObject = 1145 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 1146 1147 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases"); 1148 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases"); 1149 CGF.Builder.CreateCondBr(IsCompleteObject, 1150 CallVbaseDtorsBB, SkipVbaseDtorsBB); 1151 1152 CGF.EmitBlock(CallVbaseDtorsBB); 1153 // CGF will put the base dtor calls in this basic block for us later. 1154 1155 return SkipVbaseDtorsBB; 1156 } 1157 1158 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers( 1159 CodeGenFunction &CGF, const CXXRecordDecl *RD) { 1160 // In most cases, an override for a vbase virtual method can adjust 1161 // the "this" parameter by applying a constant offset. 1162 // However, this is not enough while a constructor or a destructor of some 1163 // class X is being executed if all the following conditions are met: 1164 // - X has virtual bases, (1) 1165 // - X overrides a virtual method M of a vbase Y, (2) 1166 // - X itself is a vbase of the most derived class. 1167 // 1168 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X 1169 // which holds the extra amount of "this" adjustment we must do when we use 1170 // the X vftables (i.e. during X ctor or dtor). 1171 // Outside the ctors and dtors, the values of vtorDisps are zero. 1172 1173 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1174 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets; 1175 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap(); 1176 CGBuilderTy &Builder = CGF.Builder; 1177 1178 unsigned AS = getThisAddress(CGF).getAddressSpace(); 1179 llvm::Value *Int8This = nullptr; // Initialize lazily. 1180 1181 for (const CXXBaseSpecifier &S : RD->vbases()) { 1182 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl(); 1183 auto I = VBaseMap.find(VBase); 1184 assert(I != VBaseMap.end()); 1185 if (!I->second.hasVtorDisp()) 1186 continue; 1187 1188 llvm::Value *VBaseOffset = 1189 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase); 1190 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity(); 1191 1192 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase). 1193 llvm::Value *VtorDispValue = Builder.CreateSub( 1194 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset), 1195 "vtordisp.value"); 1196 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty); 1197 1198 if (!Int8This) 1199 Int8This = Builder.CreateBitCast(getThisValue(CGF), 1200 CGF.Int8Ty->getPointerTo(AS)); 1201 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset); 1202 // vtorDisp is always the 32-bits before the vbase in the class layout. 1203 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4); 1204 VtorDispPtr = Builder.CreateBitCast( 1205 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr"); 1206 1207 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr, 1208 CharUnits::fromQuantity(4)); 1209 } 1210 } 1211 1212 static bool hasDefaultCXXMethodCC(ASTContext &Context, 1213 const CXXMethodDecl *MD) { 1214 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention( 1215 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 1216 CallingConv ActualCallingConv = 1217 MD->getType()->castAs<FunctionProtoType>()->getCallConv(); 1218 return ExpectedCallingConv == ActualCallingConv; 1219 } 1220 1221 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 1222 // There's only one constructor type in this ABI. 1223 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 1224 1225 // Exported default constructors either have a simple call-site where they use 1226 // the typical calling convention and have a single 'this' pointer for an 1227 // argument -or- they get a wrapper function which appropriately thunks to the 1228 // real default constructor. This thunk is the default constructor closure. 1229 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor()) 1230 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) { 1231 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure); 1232 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage); 1233 CGM.setGVProperties(Fn, D); 1234 } 1235 } 1236 1237 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF, 1238 const CXXRecordDecl *RD) { 1239 Address This = getThisAddress(CGF); 1240 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8"); 1241 const ASTContext &Context = getContext(); 1242 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1243 1244 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 1245 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 1246 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I]; 1247 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 1248 const ASTRecordLayout &SubobjectLayout = 1249 Context.getASTRecordLayout(VBT->IntroducingObject); 1250 CharUnits Offs = VBT->NonVirtualOffset; 1251 Offs += SubobjectLayout.getVBPtrOffset(); 1252 if (VBT->getVBaseWithVPtr()) 1253 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr()); 1254 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs); 1255 llvm::Value *GVPtr = 1256 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0); 1257 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(), 1258 "vbptr." + VBT->ObjectWithVPtr->getName()); 1259 CGF.Builder.CreateStore(GVPtr, VBPtr); 1260 } 1261 } 1262 1263 CGCXXABI::AddedStructorArgs 1264 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD, 1265 SmallVectorImpl<CanQualType> &ArgTys) { 1266 AddedStructorArgs Added; 1267 // TODO: 'for base' flag 1268 if (isa<CXXDestructorDecl>(GD.getDecl()) && 1269 GD.getDtorType() == Dtor_Deleting) { 1270 // The scalar deleting destructor takes an implicit int parameter. 1271 ArgTys.push_back(getContext().IntTy); 1272 ++Added.Suffix; 1273 } 1274 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl()); 1275 if (!CD) 1276 return Added; 1277 1278 // All parameters are already in place except is_most_derived, which goes 1279 // after 'this' if it's variadic and last if it's not. 1280 1281 const CXXRecordDecl *Class = CD->getParent(); 1282 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>(); 1283 if (Class->getNumVBases()) { 1284 if (FPT->isVariadic()) { 1285 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy); 1286 ++Added.Prefix; 1287 } else { 1288 ArgTys.push_back(getContext().IntTy); 1289 ++Added.Suffix; 1290 } 1291 } 1292 1293 return Added; 1294 } 1295 1296 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV, 1297 const CXXDestructorDecl *Dtor, 1298 CXXDtorType DT) const { 1299 // Deleting destructor variants are never imported or exported. Give them the 1300 // default storage class. 1301 if (DT == Dtor_Deleting) { 1302 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1303 } else { 1304 const NamedDecl *ND = Dtor; 1305 CGM.setDLLImportDLLExport(GV, ND); 1306 } 1307 } 1308 1309 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage( 1310 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const { 1311 // Internal things are always internal, regardless of attributes. After this, 1312 // we know the thunk is externally visible. 1313 if (Linkage == GVA_Internal) 1314 return llvm::GlobalValue::InternalLinkage; 1315 1316 switch (DT) { 1317 case Dtor_Base: 1318 // The base destructor most closely tracks the user-declared constructor, so 1319 // we delegate back to the normal declarator case. 1320 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage, 1321 /*IsConstantVariable=*/false); 1322 case Dtor_Complete: 1323 // The complete destructor is like an inline function, but it may be 1324 // imported and therefore must be exported as well. This requires changing 1325 // the linkage if a DLL attribute is present. 1326 if (Dtor->hasAttr<DLLExportAttr>()) 1327 return llvm::GlobalValue::WeakODRLinkage; 1328 if (Dtor->hasAttr<DLLImportAttr>()) 1329 return llvm::GlobalValue::AvailableExternallyLinkage; 1330 return llvm::GlobalValue::LinkOnceODRLinkage; 1331 case Dtor_Deleting: 1332 // Deleting destructors are like inline functions. They have vague linkage 1333 // and are emitted everywhere they are used. They are internal if the class 1334 // is internal. 1335 return llvm::GlobalValue::LinkOnceODRLinkage; 1336 case Dtor_Comdat: 1337 llvm_unreachable("MS C++ ABI does not support comdat dtors"); 1338 } 1339 llvm_unreachable("invalid dtor type"); 1340 } 1341 1342 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 1343 // The TU defining a dtor is only guaranteed to emit a base destructor. All 1344 // other destructor variants are delegating thunks. 1345 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 1346 1347 // If the class is dllexported, emit the complete (vbase) destructor wherever 1348 // the base dtor is emitted. 1349 // FIXME: To match MSVC, this should only be done when the class is exported 1350 // with -fdllexport-inlines enabled. 1351 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>()) 1352 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 1353 } 1354 1355 CharUnits 1356 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) { 1357 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1358 1359 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1360 // Complete destructors take a pointer to the complete object as a 1361 // parameter, thus don't need this adjustment. 1362 if (GD.getDtorType() == Dtor_Complete) 1363 return CharUnits(); 1364 1365 // There's no Dtor_Base in vftable but it shares the this adjustment with 1366 // the deleting one, so look it up instead. 1367 GD = GlobalDecl(DD, Dtor_Deleting); 1368 } 1369 1370 MethodVFTableLocation ML = 1371 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 1372 CharUnits Adjustment = ML.VFPtrOffset; 1373 1374 // Normal virtual instance methods need to adjust from the vfptr that first 1375 // defined the virtual method to the virtual base subobject, but destructors 1376 // do not. The vector deleting destructor thunk applies this adjustment for 1377 // us if necessary. 1378 if (isa<CXXDestructorDecl>(MD)) 1379 Adjustment = CharUnits::Zero(); 1380 1381 if (ML.VBase) { 1382 const ASTRecordLayout &DerivedLayout = 1383 getContext().getASTRecordLayout(MD->getParent()); 1384 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 1385 } 1386 1387 return Adjustment; 1388 } 1389 1390 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( 1391 CodeGenFunction &CGF, GlobalDecl GD, Address This, 1392 bool VirtualCall) { 1393 if (!VirtualCall) { 1394 // If the call of a virtual function is not virtual, we just have to 1395 // compensate for the adjustment the virtual function does in its prologue. 1396 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 1397 if (Adjustment.isZero()) 1398 return This; 1399 1400 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty); 1401 assert(Adjustment.isPositive()); 1402 return CGF.Builder.CreateConstByteGEP(This, Adjustment); 1403 } 1404 1405 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1406 1407 GlobalDecl LookupGD = GD; 1408 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1409 // Complete dtors take a pointer to the complete object, 1410 // thus don't need adjustment. 1411 if (GD.getDtorType() == Dtor_Complete) 1412 return This; 1413 1414 // There's only Dtor_Deleting in vftable but it shares the this adjustment 1415 // with the base one, so look up the deleting one instead. 1416 LookupGD = GlobalDecl(DD, Dtor_Deleting); 1417 } 1418 MethodVFTableLocation ML = 1419 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 1420 1421 CharUnits StaticOffset = ML.VFPtrOffset; 1422 1423 // Base destructors expect 'this' to point to the beginning of the base 1424 // subobject, not the first vfptr that happens to contain the virtual dtor. 1425 // However, we still need to apply the virtual base adjustment. 1426 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 1427 StaticOffset = CharUnits::Zero(); 1428 1429 Address Result = This; 1430 if (ML.VBase) { 1431 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty); 1432 1433 const CXXRecordDecl *Derived = MD->getParent(); 1434 const CXXRecordDecl *VBase = ML.VBase; 1435 llvm::Value *VBaseOffset = 1436 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase); 1437 llvm::Value *VBasePtr = 1438 CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset); 1439 CharUnits VBaseAlign = 1440 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase); 1441 Result = Address(VBasePtr, VBaseAlign); 1442 } 1443 if (!StaticOffset.isZero()) { 1444 assert(StaticOffset.isPositive()); 1445 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty); 1446 if (ML.VBase) { 1447 // Non-virtual adjustment might result in a pointer outside the allocated 1448 // object, e.g. if the final overrider class is laid out after the virtual 1449 // base that declares a method in the most derived class. 1450 // FIXME: Update the code that emits this adjustment in thunks prologues. 1451 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset); 1452 } else { 1453 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset); 1454 } 1455 } 1456 return Result; 1457 } 1458 1459 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1460 QualType &ResTy, 1461 FunctionArgList &Params) { 1462 ASTContext &Context = getContext(); 1463 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1464 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1465 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 1466 auto *IsMostDerived = ImplicitParamDecl::Create( 1467 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(), 1468 &Context.Idents.get("is_most_derived"), Context.IntTy, 1469 ImplicitParamDecl::Other); 1470 // The 'most_derived' parameter goes second if the ctor is variadic and last 1471 // if it's not. Dtors can't be variadic. 1472 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1473 if (FPT->isVariadic()) 1474 Params.insert(Params.begin() + 1, IsMostDerived); 1475 else 1476 Params.push_back(IsMostDerived); 1477 getStructorImplicitParamDecl(CGF) = IsMostDerived; 1478 } else if (isDeletingDtor(CGF.CurGD)) { 1479 auto *ShouldDelete = ImplicitParamDecl::Create( 1480 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(), 1481 &Context.Idents.get("should_call_delete"), Context.IntTy, 1482 ImplicitParamDecl::Other); 1483 Params.push_back(ShouldDelete); 1484 getStructorImplicitParamDecl(CGF) = ShouldDelete; 1485 } 1486 } 1487 1488 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1489 // Naked functions have no prolog. 1490 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>()) 1491 return; 1492 1493 // Overridden virtual methods of non-primary bases need to adjust the incoming 1494 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract 1495 // sizeof(void*) to adjust from B* to C*: 1496 // struct A { virtual void a(); }; 1497 // struct B { virtual void b(); }; 1498 // struct C : A, B { virtual void b(); }; 1499 // 1500 // Leave the value stored in the 'this' alloca unadjusted, so that the 1501 // debugger sees the unadjusted value. Microsoft debuggers require this, and 1502 // will apply the ThisAdjustment in the method type information. 1503 // FIXME: Do something better for DWARF debuggers, which won't expect this, 1504 // without making our codegen depend on debug info settings. 1505 llvm::Value *This = loadIncomingCXXThis(CGF); 1506 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1507 if (!CGF.CurFuncIsThunk && MD->isVirtual()) { 1508 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD); 1509 if (!Adjustment.isZero()) { 1510 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 1511 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 1512 *thisTy = This->getType(); 1513 This = CGF.Builder.CreateBitCast(This, charPtrTy); 1514 assert(Adjustment.isPositive()); 1515 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This, 1516 -Adjustment.getQuantity()); 1517 This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted"); 1518 } 1519 } 1520 setCXXABIThisValue(CGF, This); 1521 1522 // If this is a function that the ABI specifies returns 'this', initialize 1523 // the return slot to 'this' at the start of the function. 1524 // 1525 // Unlike the setting of return types, this is done within the ABI 1526 // implementation instead of by clients of CGCXXABI because: 1527 // 1) getThisValue is currently protected 1528 // 2) in theory, an ABI could implement 'this' returns some other way; 1529 // HasThisReturn only specifies a contract, not the implementation 1530 if (HasThisReturn(CGF.CurGD)) 1531 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1532 else if (hasMostDerivedReturn(CGF.CurGD)) 1533 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)), 1534 CGF.ReturnValue); 1535 1536 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 1537 assert(getStructorImplicitParamDecl(CGF) && 1538 "no implicit parameter for a constructor with virtual bases?"); 1539 getStructorImplicitParamValue(CGF) 1540 = CGF.Builder.CreateLoad( 1541 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1542 "is_most_derived"); 1543 } 1544 1545 if (isDeletingDtor(CGF.CurGD)) { 1546 assert(getStructorImplicitParamDecl(CGF) && 1547 "no implicit parameter for a deleting destructor?"); 1548 getStructorImplicitParamValue(CGF) 1549 = CGF.Builder.CreateLoad( 1550 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1551 "should_call_delete"); 1552 } 1553 } 1554 1555 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::addImplicitConstructorArgs( 1556 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1557 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1558 assert(Type == Ctor_Complete || Type == Ctor_Base); 1559 1560 // Check if we need a 'most_derived' parameter. 1561 if (!D->getParent()->getNumVBases()) 1562 return AddedStructorArgs{}; 1563 1564 // Add the 'most_derived' argument second if we are variadic or last if not. 1565 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1566 llvm::Value *MostDerivedArg; 1567 if (Delegating) { 1568 MostDerivedArg = getStructorImplicitParamValue(CGF); 1569 } else { 1570 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 1571 } 1572 RValue RV = RValue::get(MostDerivedArg); 1573 if (FPT->isVariadic()) { 1574 Args.insert(Args.begin() + 1, CallArg(RV, getContext().IntTy)); 1575 return AddedStructorArgs::prefix(1); 1576 } 1577 Args.add(RV, getContext().IntTy); 1578 return AddedStructorArgs::suffix(1); 1579 } 1580 1581 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1582 const CXXDestructorDecl *DD, 1583 CXXDtorType Type, bool ForVirtualBase, 1584 bool Delegating, Address This, 1585 QualType ThisTy) { 1586 // Use the base destructor variant in place of the complete destructor variant 1587 // if the class has no virtual bases. This effectively implements some of the 1588 // -mconstructor-aliases optimization, but as part of the MS C++ ABI. 1589 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0) 1590 Type = Dtor_Base; 1591 1592 GlobalDecl GD(DD, Type); 1593 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD); 1594 1595 if (DD->isVirtual()) { 1596 assert(Type != CXXDtorType::Dtor_Deleting && 1597 "The deleting destructor should only be called via a virtual call"); 1598 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), 1599 This, false); 1600 } 1601 1602 llvm::BasicBlock *BaseDtorEndBB = nullptr; 1603 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) { 1604 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF); 1605 } 1606 1607 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, 1608 /*ImplicitParam=*/nullptr, 1609 /*ImplicitParamTy=*/QualType(), nullptr); 1610 if (BaseDtorEndBB) { 1611 // Complete object handler should continue to be the remaining 1612 CGF.Builder.CreateBr(BaseDtorEndBB); 1613 CGF.EmitBlock(BaseDtorEndBB); 1614 } 1615 } 1616 1617 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info, 1618 const CXXRecordDecl *RD, 1619 llvm::GlobalVariable *VTable) { 1620 if (!CGM.getCodeGenOpts().LTOUnit) 1621 return; 1622 1623 // The location of the first virtual function pointer in the virtual table, 1624 // aka the "address point" on Itanium. This is at offset 0 if RTTI is 1625 // disabled, or sizeof(void*) if RTTI is enabled. 1626 CharUnits AddressPoint = 1627 getContext().getLangOpts().RTTIData 1628 ? getContext().toCharUnitsFromBits( 1629 getContext().getTargetInfo().getPointerWidth(0)) 1630 : CharUnits::Zero(); 1631 1632 if (Info.PathToIntroducingObject.empty()) { 1633 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD); 1634 return; 1635 } 1636 1637 // Add a bitset entry for the least derived base belonging to this vftable. 1638 CGM.AddVTableTypeMetadata(VTable, AddressPoint, 1639 Info.PathToIntroducingObject.back()); 1640 1641 // Add a bitset entry for each derived class that is laid out at the same 1642 // offset as the least derived base. 1643 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) { 1644 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1]; 1645 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I]; 1646 1647 const ASTRecordLayout &Layout = 1648 getContext().getASTRecordLayout(DerivedRD); 1649 CharUnits Offset; 1650 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD); 1651 if (VBI == Layout.getVBaseOffsetsMap().end()) 1652 Offset = Layout.getBaseClassOffset(BaseRD); 1653 else 1654 Offset = VBI->second.VBaseOffset; 1655 if (!Offset.isZero()) 1656 return; 1657 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD); 1658 } 1659 1660 // Finally do the same for the most derived class. 1661 if (Info.FullOffsetInMDC.isZero()) 1662 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD); 1663 } 1664 1665 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1666 const CXXRecordDecl *RD) { 1667 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 1668 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD); 1669 1670 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) { 1671 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC); 1672 if (VTable->hasInitializer()) 1673 continue; 1674 1675 const VTableLayout &VTLayout = 1676 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC); 1677 1678 llvm::Constant *RTTI = nullptr; 1679 if (any_of(VTLayout.vtable_components(), 1680 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); })) 1681 RTTI = getMSCompleteObjectLocator(RD, *Info); 1682 1683 ConstantInitBuilder Builder(CGM); 1684 auto Components = Builder.beginStruct(); 1685 CGVT.createVTableInitializer(Components, VTLayout, RTTI); 1686 Components.finishAndSetAsInitializer(VTable); 1687 1688 emitVTableTypeMetadata(*Info, RD, VTable); 1689 } 1690 } 1691 1692 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField( 1693 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) { 1694 return Vptr.NearestVBase != nullptr; 1695 } 1696 1697 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor( 1698 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1699 const CXXRecordDecl *NearestVBase) { 1700 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass); 1701 if (!VTableAddressPoint) { 1702 assert(Base.getBase()->getNumVBases() && 1703 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr()); 1704 } 1705 return VTableAddressPoint; 1706 } 1707 1708 static void mangleVFTableName(MicrosoftMangleContext &MangleContext, 1709 const CXXRecordDecl *RD, const VPtrInfo &VFPtr, 1710 SmallString<256> &Name) { 1711 llvm::raw_svector_ostream Out(Name); 1712 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out); 1713 } 1714 1715 llvm::Constant * 1716 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base, 1717 const CXXRecordDecl *VTableClass) { 1718 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset()); 1719 VFTableIdTy ID(VTableClass, Base.getBaseOffset()); 1720 return VFTablesMap[ID]; 1721 } 1722 1723 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr( 1724 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1725 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass); 1726 assert(VFTable && "Couldn't find a vftable for the given base?"); 1727 return VFTable; 1728 } 1729 1730 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1731 CharUnits VPtrOffset) { 1732 // getAddrOfVTable may return 0 if asked to get an address of a vtable which 1733 // shouldn't be used in the given record type. We want to cache this result in 1734 // VFTablesMap, thus a simple zero check is not sufficient. 1735 1736 VFTableIdTy ID(RD, VPtrOffset); 1737 VTablesMapTy::iterator I; 1738 bool Inserted; 1739 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr)); 1740 if (!Inserted) 1741 return I->second; 1742 1743 llvm::GlobalVariable *&VTable = I->second; 1744 1745 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 1746 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD); 1747 1748 if (DeferredVFTables.insert(RD).second) { 1749 // We haven't processed this record type before. 1750 // Queue up this vtable for possible deferred emission. 1751 CGM.addDeferredVTable(RD); 1752 1753 #ifndef NDEBUG 1754 // Create all the vftables at once in order to make sure each vftable has 1755 // a unique mangled name. 1756 llvm::StringSet<> ObservedMangledNames; 1757 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 1758 SmallString<256> Name; 1759 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name); 1760 if (!ObservedMangledNames.insert(Name.str()).second) 1761 llvm_unreachable("Already saw this mangling before?"); 1762 } 1763 #endif 1764 } 1765 1766 const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if( 1767 VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) { 1768 return VPI->FullOffsetInMDC == VPtrOffset; 1769 }); 1770 if (VFPtrI == VFPtrs.end()) { 1771 VFTablesMap[ID] = nullptr; 1772 return nullptr; 1773 } 1774 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI; 1775 1776 SmallString<256> VFTableName; 1777 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName); 1778 1779 // Classes marked __declspec(dllimport) need vftables generated on the 1780 // import-side in order to support features like constexpr. No other 1781 // translation unit relies on the emission of the local vftable, translation 1782 // units are expected to generate them as needed. 1783 // 1784 // Because of this unique behavior, we maintain this logic here instead of 1785 // getVTableLinkage. 1786 llvm::GlobalValue::LinkageTypes VFTableLinkage = 1787 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage 1788 : CGM.getVTableLinkage(RD); 1789 bool VFTableComesFromAnotherTU = 1790 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) || 1791 llvm::GlobalValue::isExternalLinkage(VFTableLinkage); 1792 bool VTableAliasIsRequred = 1793 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData; 1794 1795 if (llvm::GlobalValue *VFTable = 1796 CGM.getModule().getNamedGlobal(VFTableName)) { 1797 VFTablesMap[ID] = VFTable; 1798 VTable = VTableAliasIsRequred 1799 ? cast<llvm::GlobalVariable>( 1800 cast<llvm::GlobalAlias>(VFTable)->getBaseObject()) 1801 : cast<llvm::GlobalVariable>(VFTable); 1802 return VTable; 1803 } 1804 1805 const VTableLayout &VTLayout = 1806 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC); 1807 llvm::GlobalValue::LinkageTypes VTableLinkage = 1808 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage; 1809 1810 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str(); 1811 1812 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout); 1813 1814 // Create a backing variable for the contents of VTable. The VTable may 1815 // or may not include space for a pointer to RTTI data. 1816 llvm::GlobalValue *VFTable; 1817 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType, 1818 /*isConstant=*/true, VTableLinkage, 1819 /*Initializer=*/nullptr, VTableName); 1820 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1821 1822 llvm::Comdat *C = nullptr; 1823 if (!VFTableComesFromAnotherTU && 1824 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) || 1825 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) && 1826 VTableAliasIsRequred))) 1827 C = CGM.getModule().getOrInsertComdat(VFTableName.str()); 1828 1829 // Only insert a pointer into the VFTable for RTTI data if we are not 1830 // importing it. We never reference the RTTI data directly so there is no 1831 // need to make room for it. 1832 if (VTableAliasIsRequred) { 1833 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0), 1834 llvm::ConstantInt::get(CGM.Int32Ty, 0), 1835 llvm::ConstantInt::get(CGM.Int32Ty, 1)}; 1836 // Create a GEP which points just after the first entry in the VFTable, 1837 // this should be the location of the first virtual method. 1838 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr( 1839 VTable->getValueType(), VTable, GEPIndices); 1840 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) { 1841 VFTableLinkage = llvm::GlobalValue::ExternalLinkage; 1842 if (C) 1843 C->setSelectionKind(llvm::Comdat::Largest); 1844 } 1845 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy, 1846 /*AddressSpace=*/0, VFTableLinkage, 1847 VFTableName.str(), VTableGEP, 1848 &CGM.getModule()); 1849 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1850 } else { 1851 // We don't need a GlobalAlias to be a symbol for the VTable if we won't 1852 // be referencing any RTTI data. 1853 // The GlobalVariable will end up being an appropriate definition of the 1854 // VFTable. 1855 VFTable = VTable; 1856 } 1857 if (C) 1858 VTable->setComdat(C); 1859 1860 if (RD->hasAttr<DLLExportAttr>()) 1861 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1862 1863 VFTablesMap[ID] = VFTable; 1864 return VTable; 1865 } 1866 1867 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1868 GlobalDecl GD, 1869 Address This, 1870 llvm::Type *Ty, 1871 SourceLocation Loc) { 1872 CGBuilderTy &Builder = CGF.Builder; 1873 1874 Ty = Ty->getPointerTo()->getPointerTo(); 1875 Address VPtr = 1876 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1877 1878 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl()); 1879 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent()); 1880 1881 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 1882 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD); 1883 1884 // Compute the identity of the most derived class whose virtual table is 1885 // located at the MethodVFTableLocation ML. 1886 auto getObjectWithVPtr = [&] { 1887 return llvm::find_if(VFTContext.getVFPtrOffsets( 1888 ML.VBase ? ML.VBase : MethodDecl->getParent()), 1889 [&](const std::unique_ptr<VPtrInfo> &Info) { 1890 return Info->FullOffsetInMDC == ML.VFPtrOffset; 1891 }) 1892 ->get() 1893 ->ObjectWithVPtr; 1894 }; 1895 1896 llvm::Value *VFunc; 1897 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) { 1898 VFunc = CGF.EmitVTableTypeCheckedLoad( 1899 getObjectWithVPtr(), VTable, 1900 ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8); 1901 } else { 1902 if (CGM.getCodeGenOpts().PrepareForLTO) 1903 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc); 1904 1905 llvm::Value *VFuncPtr = 1906 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1907 VFunc = Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); 1908 } 1909 1910 CGCallee Callee(GD, VFunc); 1911 return Callee; 1912 } 1913 1914 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall( 1915 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, 1916 Address This, DeleteOrMemberCallExpr E) { 1917 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>(); 1918 auto *D = E.dyn_cast<const CXXDeleteExpr *>(); 1919 assert((CE != nullptr) ^ (D != nullptr)); 1920 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1921 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1922 1923 // We have only one destructor in the vftable but can get both behaviors 1924 // by passing an implicit int parameter. 1925 GlobalDecl GD(Dtor, Dtor_Deleting); 1926 const CGFunctionInfo *FInfo = 1927 &CGM.getTypes().arrangeCXXStructorDeclaration(GD); 1928 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1929 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty); 1930 1931 ASTContext &Context = getContext(); 1932 llvm::Value *ImplicitParam = llvm::ConstantInt::get( 1933 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 1934 DtorType == Dtor_Deleting); 1935 1936 QualType ThisTy; 1937 if (CE) { 1938 ThisTy = CE->getObjectType(); 1939 } else { 1940 ThisTy = D->getDestroyedType(); 1941 } 1942 1943 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1944 RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, 1945 ImplicitParam, Context.IntTy, CE); 1946 return RV.getScalarVal(); 1947 } 1948 1949 const VBTableGlobals & 1950 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 1951 // At this layer, we can key the cache off of a single class, which is much 1952 // easier than caching each vbtable individually. 1953 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 1954 bool Added; 1955 std::tie(Entry, Added) = 1956 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals())); 1957 VBTableGlobals &VBGlobals = Entry->second; 1958 if (!Added) 1959 return VBGlobals; 1960 1961 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1962 VBGlobals.VBTables = &Context.enumerateVBTables(RD); 1963 1964 // Cache the globals for all vbtables so we don't have to recompute the 1965 // mangled names. 1966 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1967 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(), 1968 E = VBGlobals.VBTables->end(); 1969 I != E; ++I) { 1970 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage)); 1971 } 1972 1973 return VBGlobals; 1974 } 1975 1976 llvm::Function * 1977 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD, 1978 const MethodVFTableLocation &ML) { 1979 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) && 1980 "can't form pointers to ctors or virtual dtors"); 1981 1982 // Calculate the mangled name. 1983 SmallString<256> ThunkName; 1984 llvm::raw_svector_ostream Out(ThunkName); 1985 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out); 1986 1987 // If the thunk has been generated previously, just return it. 1988 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 1989 return cast<llvm::Function>(GV); 1990 1991 // Create the llvm::Function. 1992 const CGFunctionInfo &FnInfo = 1993 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD); 1994 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 1995 llvm::Function *ThunkFn = 1996 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 1997 ThunkName.str(), &CGM.getModule()); 1998 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 1999 2000 ThunkFn->setLinkage(MD->isExternallyVisible() 2001 ? llvm::GlobalValue::LinkOnceODRLinkage 2002 : llvm::GlobalValue::InternalLinkage); 2003 if (MD->isExternallyVisible()) 2004 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName())); 2005 2006 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 2007 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 2008 2009 // Add the "thunk" attribute so that LLVM knows that the return type is 2010 // meaningless. These thunks can be used to call functions with differing 2011 // return types, and the caller is required to cast the prototype 2012 // appropriately to extract the correct value. 2013 ThunkFn->addFnAttr("thunk"); 2014 2015 // These thunks can be compared, so they are not unnamed. 2016 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None); 2017 2018 // Start codegen. 2019 CodeGenFunction CGF(CGM); 2020 CGF.CurGD = GlobalDecl(MD); 2021 CGF.CurFuncIsThunk = true; 2022 2023 // Build FunctionArgs, but only include the implicit 'this' parameter 2024 // declaration. 2025 FunctionArgList FunctionArgs; 2026 buildThisParam(CGF, FunctionArgs); 2027 2028 // Start defining the function. 2029 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo, 2030 FunctionArgs, MD->getLocation(), SourceLocation()); 2031 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF)); 2032 2033 // Load the vfptr and then callee from the vftable. The callee should have 2034 // adjusted 'this' so that the vfptr is at offset zero. 2035 llvm::Value *VTable = CGF.GetVTablePtr( 2036 getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent()); 2037 2038 llvm::Value *VFuncPtr = 2039 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 2040 llvm::Value *Callee = 2041 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); 2042 2043 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee}); 2044 2045 return ThunkFn; 2046 } 2047 2048 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 2049 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 2050 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 2051 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I]; 2052 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 2053 if (GV->isDeclaration()) 2054 emitVBTableDefinition(*VBT, RD, GV); 2055 } 2056 } 2057 2058 llvm::GlobalVariable * 2059 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 2060 llvm::GlobalVariable::LinkageTypes Linkage) { 2061 SmallString<256> OutName; 2062 llvm::raw_svector_ostream Out(OutName); 2063 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out); 2064 StringRef Name = OutName.str(); 2065 2066 llvm::ArrayType *VBTableType = 2067 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases()); 2068 2069 assert(!CGM.getModule().getNamedGlobal(Name) && 2070 "vbtable with this name already exists: mangling bug?"); 2071 CharUnits Alignment = 2072 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy); 2073 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable( 2074 Name, VBTableType, Linkage, Alignment.getQuantity()); 2075 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2076 2077 if (RD->hasAttr<DLLImportAttr>()) 2078 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 2079 else if (RD->hasAttr<DLLExportAttr>()) 2080 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2081 2082 if (!GV->hasExternalLinkage()) 2083 emitVBTableDefinition(VBT, RD, GV); 2084 2085 return GV; 2086 } 2087 2088 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT, 2089 const CXXRecordDecl *RD, 2090 llvm::GlobalVariable *GV) const { 2091 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr; 2092 2093 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() && 2094 "should only emit vbtables for classes with vbtables"); 2095 2096 const ASTRecordLayout &BaseLayout = 2097 getContext().getASTRecordLayout(VBT.IntroducingObject); 2098 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD); 2099 2100 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(), 2101 nullptr); 2102 2103 // The offset from ObjectWithVPtr's vbptr to itself always leads. 2104 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 2105 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 2106 2107 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 2108 for (const auto &I : ObjectWithVPtr->vbases()) { 2109 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl(); 2110 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 2111 assert(!Offset.isNegative()); 2112 2113 // Make it relative to the subobject vbptr. 2114 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 2115 if (VBT.getVBaseWithVPtr()) 2116 CompleteVBPtrOffset += 2117 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr()); 2118 Offset -= CompleteVBPtrOffset; 2119 2120 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase); 2121 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?"); 2122 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 2123 } 2124 2125 assert(Offsets.size() == 2126 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 2127 ->getElementType())->getNumElements()); 2128 llvm::ArrayType *VBTableType = 2129 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 2130 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 2131 GV->setInitializer(Init); 2132 2133 if (RD->hasAttr<DLLImportAttr>()) 2134 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage); 2135 } 2136 2137 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 2138 Address This, 2139 const ThisAdjustment &TA) { 2140 if (TA.isEmpty()) 2141 return This.getPointer(); 2142 2143 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty); 2144 2145 llvm::Value *V; 2146 if (TA.Virtual.isEmpty()) { 2147 V = This.getPointer(); 2148 } else { 2149 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 2150 // Adjust the this argument based on the vtordisp value. 2151 Address VtorDispPtr = 2152 CGF.Builder.CreateConstInBoundsByteGEP(This, 2153 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset)); 2154 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty); 2155 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 2156 V = CGF.Builder.CreateGEP(This.getPointer(), 2157 CGF.Builder.CreateNeg(VtorDisp)); 2158 2159 // Unfortunately, having applied the vtordisp means that we no 2160 // longer really have a known alignment for the vbptr step. 2161 // We'll assume the vbptr is pointer-aligned. 2162 2163 if (TA.Virtual.Microsoft.VBPtrOffset) { 2164 // If the final overrider is defined in a virtual base other than the one 2165 // that holds the vfptr, we have to use a vtordispex thunk which looks up 2166 // the vbtable of the derived class. 2167 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 2168 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 2169 llvm::Value *VBPtr; 2170 llvm::Value *VBaseOffset = 2171 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()), 2172 -TA.Virtual.Microsoft.VBPtrOffset, 2173 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 2174 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 2175 } 2176 } 2177 2178 if (TA.NonVirtual) { 2179 // Non-virtual adjustment might result in a pointer outside the allocated 2180 // object, e.g. if the final overrider class is laid out after the virtual 2181 // base that declares a method in the most derived class. 2182 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 2183 } 2184 2185 // Don't need to bitcast back, the call CodeGen will handle this. 2186 return V; 2187 } 2188 2189 llvm::Value * 2190 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 2191 const ReturnAdjustment &RA) { 2192 if (RA.isEmpty()) 2193 return Ret.getPointer(); 2194 2195 auto OrigTy = Ret.getType(); 2196 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty); 2197 2198 llvm::Value *V = Ret.getPointer(); 2199 if (RA.Virtual.Microsoft.VBIndex) { 2200 assert(RA.Virtual.Microsoft.VBIndex > 0); 2201 int32_t IntSize = CGF.getIntSize().getQuantity(); 2202 llvm::Value *VBPtr; 2203 llvm::Value *VBaseOffset = 2204 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset, 2205 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 2206 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 2207 } 2208 2209 if (RA.NonVirtual) 2210 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual); 2211 2212 // Cast back to the original type. 2213 return CGF.Builder.CreateBitCast(V, OrigTy); 2214 } 2215 2216 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 2217 QualType elementType) { 2218 // Microsoft seems to completely ignore the possibility of a 2219 // two-argument usual deallocation function. 2220 return elementType.isDestructedType(); 2221 } 2222 2223 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 2224 // Microsoft seems to completely ignore the possibility of a 2225 // two-argument usual deallocation function. 2226 return expr->getAllocatedType().isDestructedType(); 2227 } 2228 2229 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 2230 // The array cookie is always a size_t; we then pad that out to the 2231 // alignment of the element type. 2232 ASTContext &Ctx = getContext(); 2233 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 2234 Ctx.getTypeAlignInChars(type)); 2235 } 2236 2237 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 2238 Address allocPtr, 2239 CharUnits cookieSize) { 2240 Address numElementsPtr = 2241 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy); 2242 return CGF.Builder.CreateLoad(numElementsPtr); 2243 } 2244 2245 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 2246 Address newPtr, 2247 llvm::Value *numElements, 2248 const CXXNewExpr *expr, 2249 QualType elementType) { 2250 assert(requiresArrayCookie(expr)); 2251 2252 // The size of the cookie. 2253 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 2254 2255 // Compute an offset to the cookie. 2256 Address cookiePtr = newPtr; 2257 2258 // Write the number of elements into the appropriate slot. 2259 Address numElementsPtr 2260 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy); 2261 CGF.Builder.CreateStore(numElements, numElementsPtr); 2262 2263 // Finally, compute a pointer to the actual data buffer by skipping 2264 // over the cookie completely. 2265 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize); 2266 } 2267 2268 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD, 2269 llvm::FunctionCallee Dtor, 2270 llvm::Constant *Addr) { 2271 // Create a function which calls the destructor. 2272 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr); 2273 2274 // extern "C" int __tlregdtor(void (*f)(void)); 2275 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get( 2276 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false); 2277 2278 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction( 2279 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true); 2280 if (llvm::Function *TLRegDtorFn = 2281 dyn_cast<llvm::Function>(TLRegDtor.getCallee())) 2282 TLRegDtorFn->setDoesNotThrow(); 2283 2284 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub); 2285 } 2286 2287 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 2288 llvm::FunctionCallee Dtor, 2289 llvm::Constant *Addr) { 2290 if (D.isNoDestroy(CGM.getContext())) 2291 return; 2292 2293 if (D.getTLSKind()) 2294 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr); 2295 2296 // The default behavior is to use atexit. 2297 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr); 2298 } 2299 2300 void MicrosoftCXXABI::EmitThreadLocalInitFuncs( 2301 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals, 2302 ArrayRef<llvm::Function *> CXXThreadLocalInits, 2303 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) { 2304 if (CXXThreadLocalInits.empty()) 2305 return; 2306 2307 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() == 2308 llvm::Triple::x86 2309 ? "/include:___dyn_tls_init@12" 2310 : "/include:__dyn_tls_init"); 2311 2312 // This will create a GV in the .CRT$XDU section. It will point to our 2313 // initialization function. The CRT will call all of these function 2314 // pointers at start-up time and, eventually, at thread-creation time. 2315 auto AddToXDU = [&CGM](llvm::Function *InitFunc) { 2316 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable( 2317 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true, 2318 llvm::GlobalVariable::InternalLinkage, InitFunc, 2319 Twine(InitFunc->getName(), "$initializer$")); 2320 InitFuncPtr->setSection(".CRT$XDU"); 2321 // This variable has discardable linkage, we have to add it to @llvm.used to 2322 // ensure it won't get discarded. 2323 CGM.addUsedGlobal(InitFuncPtr); 2324 return InitFuncPtr; 2325 }; 2326 2327 std::vector<llvm::Function *> NonComdatInits; 2328 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) { 2329 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>( 2330 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I]))); 2331 llvm::Function *F = CXXThreadLocalInits[I]; 2332 2333 // If the GV is already in a comdat group, then we have to join it. 2334 if (llvm::Comdat *C = GV->getComdat()) 2335 AddToXDU(F)->setComdat(C); 2336 else 2337 NonComdatInits.push_back(F); 2338 } 2339 2340 if (!NonComdatInits.empty()) { 2341 llvm::FunctionType *FTy = 2342 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 2343 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction( 2344 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(), 2345 SourceLocation(), /*TLS=*/true); 2346 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits); 2347 2348 AddToXDU(InitFunc); 2349 } 2350 } 2351 2352 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2353 const VarDecl *VD, 2354 QualType LValType) { 2355 CGF.CGM.ErrorUnsupported(VD, "thread wrappers"); 2356 return LValue(); 2357 } 2358 2359 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) { 2360 StringRef VarName("_Init_thread_epoch"); 2361 CharUnits Align = CGM.getIntAlign(); 2362 if (auto *GV = CGM.getModule().getNamedGlobal(VarName)) 2363 return ConstantAddress(GV, Align); 2364 auto *GV = new llvm::GlobalVariable( 2365 CGM.getModule(), CGM.IntTy, 2366 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage, 2367 /*Initializer=*/nullptr, VarName, 2368 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel); 2369 GV->setAlignment(Align.getAsAlign()); 2370 return ConstantAddress(GV, Align); 2371 } 2372 2373 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) { 2374 llvm::FunctionType *FTy = 2375 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2376 CGM.IntTy->getPointerTo(), /*isVarArg=*/false); 2377 return CGM.CreateRuntimeFunction( 2378 FTy, "_Init_thread_header", 2379 llvm::AttributeList::get(CGM.getLLVMContext(), 2380 llvm::AttributeList::FunctionIndex, 2381 llvm::Attribute::NoUnwind), 2382 /*Local=*/true); 2383 } 2384 2385 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) { 2386 llvm::FunctionType *FTy = 2387 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2388 CGM.IntTy->getPointerTo(), /*isVarArg=*/false); 2389 return CGM.CreateRuntimeFunction( 2390 FTy, "_Init_thread_footer", 2391 llvm::AttributeList::get(CGM.getLLVMContext(), 2392 llvm::AttributeList::FunctionIndex, 2393 llvm::Attribute::NoUnwind), 2394 /*Local=*/true); 2395 } 2396 2397 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) { 2398 llvm::FunctionType *FTy = 2399 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2400 CGM.IntTy->getPointerTo(), /*isVarArg=*/false); 2401 return CGM.CreateRuntimeFunction( 2402 FTy, "_Init_thread_abort", 2403 llvm::AttributeList::get(CGM.getLLVMContext(), 2404 llvm::AttributeList::FunctionIndex, 2405 llvm::Attribute::NoUnwind), 2406 /*Local=*/true); 2407 } 2408 2409 namespace { 2410 struct ResetGuardBit final : EHScopeStack::Cleanup { 2411 Address Guard; 2412 unsigned GuardNum; 2413 ResetGuardBit(Address Guard, unsigned GuardNum) 2414 : Guard(Guard), GuardNum(GuardNum) {} 2415 2416 void Emit(CodeGenFunction &CGF, Flags flags) override { 2417 // Reset the bit in the mask so that the static variable may be 2418 // reinitialized. 2419 CGBuilderTy &Builder = CGF.Builder; 2420 llvm::LoadInst *LI = Builder.CreateLoad(Guard); 2421 llvm::ConstantInt *Mask = 2422 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum)); 2423 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard); 2424 } 2425 }; 2426 2427 struct CallInitThreadAbort final : EHScopeStack::Cleanup { 2428 llvm::Value *Guard; 2429 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {} 2430 2431 void Emit(CodeGenFunction &CGF, Flags flags) override { 2432 // Calling _Init_thread_abort will reset the guard's state. 2433 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard); 2434 } 2435 }; 2436 } 2437 2438 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 2439 llvm::GlobalVariable *GV, 2440 bool PerformInit) { 2441 // MSVC only uses guards for static locals. 2442 if (!D.isStaticLocal()) { 2443 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()); 2444 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr. 2445 llvm::Function *F = CGF.CurFn; 2446 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 2447 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName())); 2448 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 2449 return; 2450 } 2451 2452 bool ThreadlocalStatic = D.getTLSKind(); 2453 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics; 2454 2455 // Thread-safe static variables which aren't thread-specific have a 2456 // per-variable guard. 2457 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic; 2458 2459 CGBuilderTy &Builder = CGF.Builder; 2460 llvm::IntegerType *GuardTy = CGF.Int32Ty; 2461 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 2462 CharUnits GuardAlign = CharUnits::fromQuantity(4); 2463 2464 // Get the guard variable for this function if we have one already. 2465 GuardInfo *GI = nullptr; 2466 if (ThreadlocalStatic) 2467 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()]; 2468 else if (!ThreadsafeStatic) 2469 GI = &GuardVariableMap[D.getDeclContext()]; 2470 2471 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr; 2472 unsigned GuardNum; 2473 if (D.isExternallyVisible()) { 2474 // Externally visible variables have to be numbered in Sema to properly 2475 // handle unreachable VarDecls. 2476 GuardNum = getContext().getStaticLocalNumber(&D); 2477 assert(GuardNum > 0); 2478 GuardNum--; 2479 } else if (HasPerVariableGuard) { 2480 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++; 2481 } else { 2482 // Non-externally visible variables are numbered here in CodeGen. 2483 GuardNum = GI->BitIndex++; 2484 } 2485 2486 if (!HasPerVariableGuard && GuardNum >= 32) { 2487 if (D.isExternallyVisible()) 2488 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 2489 GuardNum %= 32; 2490 GuardVar = nullptr; 2491 } 2492 2493 if (!GuardVar) { 2494 // Mangle the name for the guard. 2495 SmallString<256> GuardName; 2496 { 2497 llvm::raw_svector_ostream Out(GuardName); 2498 if (HasPerVariableGuard) 2499 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum, 2500 Out); 2501 else 2502 getMangleContext().mangleStaticGuardVariable(&D, Out); 2503 } 2504 2505 // Create the guard variable with a zero-initializer. Just absorb linkage, 2506 // visibility and dll storage class from the guarded variable. 2507 GuardVar = 2508 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false, 2509 GV->getLinkage(), Zero, GuardName.str()); 2510 GuardVar->setVisibility(GV->getVisibility()); 2511 GuardVar->setDLLStorageClass(GV->getDLLStorageClass()); 2512 GuardVar->setAlignment(GuardAlign.getAsAlign()); 2513 if (GuardVar->isWeakForLinker()) 2514 GuardVar->setComdat( 2515 CGM.getModule().getOrInsertComdat(GuardVar->getName())); 2516 if (D.getTLSKind()) 2517 GuardVar->setThreadLocal(true); 2518 if (GI && !HasPerVariableGuard) 2519 GI->Guard = GuardVar; 2520 } 2521 2522 ConstantAddress GuardAddr(GuardVar, GuardAlign); 2523 2524 assert(GuardVar->getLinkage() == GV->getLinkage() && 2525 "static local from the same function had different linkage"); 2526 2527 if (!HasPerVariableGuard) { 2528 // Pseudo code for the test: 2529 // if (!(GuardVar & MyGuardBit)) { 2530 // GuardVar |= MyGuardBit; 2531 // ... initialize the object ...; 2532 // } 2533 2534 // Test our bit from the guard variable. 2535 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum); 2536 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr); 2537 llvm::Value *NeedsInit = 2538 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero); 2539 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 2540 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 2541 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock, 2542 CodeGenFunction::GuardKind::VariableGuard, &D); 2543 2544 // Set our bit in the guard variable and emit the initializer and add a global 2545 // destructor if appropriate. 2546 CGF.EmitBlock(InitBlock); 2547 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr); 2548 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum); 2549 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 2550 CGF.PopCleanupBlock(); 2551 Builder.CreateBr(EndBlock); 2552 2553 // Continue. 2554 CGF.EmitBlock(EndBlock); 2555 } else { 2556 // Pseudo code for the test: 2557 // if (TSS > _Init_thread_epoch) { 2558 // _Init_thread_header(&TSS); 2559 // if (TSS == -1) { 2560 // ... initialize the object ...; 2561 // _Init_thread_footer(&TSS); 2562 // } 2563 // } 2564 // 2565 // The algorithm is almost identical to what can be found in the appendix 2566 // found in N2325. 2567 2568 // This BasicBLock determines whether or not we have any work to do. 2569 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr); 2570 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered); 2571 llvm::LoadInst *InitThreadEpoch = 2572 Builder.CreateLoad(getInitThreadEpochPtr(CGM)); 2573 llvm::Value *IsUninitialized = 2574 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch); 2575 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt"); 2576 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 2577 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock, 2578 CodeGenFunction::GuardKind::VariableGuard, &D); 2579 2580 // This BasicBlock attempts to determine whether or not this thread is 2581 // responsible for doing the initialization. 2582 CGF.EmitBlock(AttemptInitBlock); 2583 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM), 2584 GuardAddr.getPointer()); 2585 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr); 2586 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered); 2587 llvm::Value *ShouldDoInit = 2588 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt()); 2589 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 2590 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock); 2591 2592 // Ok, we ended up getting selected as the initializing thread. 2593 CGF.EmitBlock(InitBlock); 2594 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr); 2595 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 2596 CGF.PopCleanupBlock(); 2597 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM), 2598 GuardAddr.getPointer()); 2599 Builder.CreateBr(EndBlock); 2600 2601 CGF.EmitBlock(EndBlock); 2602 } 2603 } 2604 2605 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 2606 // Null-ness for function memptrs only depends on the first field, which is 2607 // the function pointer. The rest don't matter, so we can zero initialize. 2608 if (MPT->isMemberFunctionPointer()) 2609 return true; 2610 2611 // The virtual base adjustment field is always -1 for null, so if we have one 2612 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 2613 // valid field offset. 2614 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2615 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2616 return (!inheritanceModelHasVBTableOffsetField(Inheritance) && 2617 RD->nullFieldOffsetIsZero()); 2618 } 2619 2620 llvm::Type * 2621 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 2622 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2623 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2624 llvm::SmallVector<llvm::Type *, 4> fields; 2625 if (MPT->isMemberFunctionPointer()) 2626 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 2627 else 2628 fields.push_back(CGM.IntTy); // FieldOffset 2629 2630 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(), 2631 Inheritance)) 2632 fields.push_back(CGM.IntTy); 2633 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 2634 fields.push_back(CGM.IntTy); 2635 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 2636 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 2637 2638 if (fields.size() == 1) 2639 return fields[0]; 2640 return llvm::StructType::get(CGM.getLLVMContext(), fields); 2641 } 2642 2643 void MicrosoftCXXABI:: 2644 GetNullMemberPointerFields(const MemberPointerType *MPT, 2645 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 2646 assert(fields.empty()); 2647 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2648 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2649 if (MPT->isMemberFunctionPointer()) { 2650 // FunctionPointerOrVirtualThunk 2651 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 2652 } else { 2653 if (RD->nullFieldOffsetIsZero()) 2654 fields.push_back(getZeroInt()); // FieldOffset 2655 else 2656 fields.push_back(getAllOnesInt()); // FieldOffset 2657 } 2658 2659 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(), 2660 Inheritance)) 2661 fields.push_back(getZeroInt()); 2662 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 2663 fields.push_back(getZeroInt()); 2664 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 2665 fields.push_back(getAllOnesInt()); 2666 } 2667 2668 llvm::Constant * 2669 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 2670 llvm::SmallVector<llvm::Constant *, 4> fields; 2671 GetNullMemberPointerFields(MPT, fields); 2672 if (fields.size() == 1) 2673 return fields[0]; 2674 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 2675 assert(Res->getType() == ConvertMemberPointerType(MPT)); 2676 return Res; 2677 } 2678 2679 llvm::Constant * 2680 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 2681 bool IsMemberFunction, 2682 const CXXRecordDecl *RD, 2683 CharUnits NonVirtualBaseAdjustment, 2684 unsigned VBTableIndex) { 2685 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2686 2687 // Single inheritance class member pointer are represented as scalars instead 2688 // of aggregates. 2689 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance)) 2690 return FirstField; 2691 2692 llvm::SmallVector<llvm::Constant *, 4> fields; 2693 fields.push_back(FirstField); 2694 2695 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance)) 2696 fields.push_back(llvm::ConstantInt::get( 2697 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 2698 2699 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) { 2700 CharUnits Offs = CharUnits::Zero(); 2701 if (VBTableIndex) 2702 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 2703 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 2704 } 2705 2706 // The rest of the fields are adjusted by conversions to a more derived class. 2707 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 2708 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex)); 2709 2710 return llvm::ConstantStruct::getAnon(fields); 2711 } 2712 2713 llvm::Constant * 2714 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 2715 CharUnits offset) { 2716 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset); 2717 } 2718 2719 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD, 2720 CharUnits offset) { 2721 if (RD->getMSInheritanceModel() == 2722 MSInheritanceModel::Virtual) 2723 offset -= getContext().getOffsetOfBaseWithVBPtr(RD); 2724 llvm::Constant *FirstField = 2725 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 2726 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 2727 CharUnits::Zero(), /*VBTableIndex=*/0); 2728 } 2729 2730 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 2731 QualType MPType) { 2732 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>(); 2733 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2734 if (!MPD) 2735 return EmitNullMemberPointer(DstTy); 2736 2737 ASTContext &Ctx = getContext(); 2738 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath(); 2739 2740 llvm::Constant *C; 2741 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) { 2742 C = EmitMemberFunctionPointer(MD); 2743 } else { 2744 // For a pointer to data member, start off with the offset of the field in 2745 // the class in which it was declared, and convert from there if necessary. 2746 // For indirect field decls, get the outermost anonymous field and use the 2747 // parent class. 2748 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD)); 2749 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD); 2750 if (!FD) 2751 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin()); 2752 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent()); 2753 RD = RD->getMostRecentNonInjectedDecl(); 2754 C = EmitMemberDataPointer(RD, FieldOffset); 2755 } 2756 2757 if (!MemberPointerPath.empty()) { 2758 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2759 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr(); 2760 const MemberPointerType *SrcTy = 2761 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy) 2762 ->castAs<MemberPointerType>(); 2763 2764 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2765 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath; 2766 const CXXRecordDecl *PrevRD = SrcRD; 2767 for (const CXXRecordDecl *PathElem : MemberPointerPath) { 2768 const CXXRecordDecl *Base = nullptr; 2769 const CXXRecordDecl *Derived = nullptr; 2770 if (DerivedMember) { 2771 Base = PathElem; 2772 Derived = PrevRD; 2773 } else { 2774 Base = PrevRD; 2775 Derived = PathElem; 2776 } 2777 for (const CXXBaseSpecifier &BS : Derived->bases()) 2778 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == 2779 Base->getCanonicalDecl()) 2780 DerivedToBasePath.push_back(&BS); 2781 PrevRD = PathElem; 2782 } 2783 assert(DerivedToBasePath.size() == MemberPointerPath.size()); 2784 2785 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer 2786 : CK_BaseToDerivedMemberPointer; 2787 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(), 2788 DerivedToBasePath.end(), C); 2789 } 2790 return C; 2791 } 2792 2793 llvm::Constant * 2794 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) { 2795 assert(MD->isInstance() && "Member function must not be static!"); 2796 2797 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero(); 2798 const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl(); 2799 CodeGenTypes &Types = CGM.getTypes(); 2800 2801 unsigned VBTableIndex = 0; 2802 llvm::Constant *FirstField; 2803 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 2804 if (!MD->isVirtual()) { 2805 llvm::Type *Ty; 2806 // Check whether the function has a computable LLVM signature. 2807 if (Types.isFuncTypeConvertible(FPT)) { 2808 // The function has a computable LLVM signature; use the correct type. 2809 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 2810 } else { 2811 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 2812 // function type is incomplete. 2813 Ty = CGM.PtrDiffTy; 2814 } 2815 FirstField = CGM.GetAddrOfFunction(MD, Ty); 2816 } else { 2817 auto &VTableContext = CGM.getMicrosoftVTableContext(); 2818 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD); 2819 FirstField = EmitVirtualMemPtrThunk(MD, ML); 2820 // Include the vfptr adjustment if the method is in a non-primary vftable. 2821 NonVirtualBaseAdjustment += ML.VFPtrOffset; 2822 if (ML.VBase) 2823 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4; 2824 } 2825 2826 if (VBTableIndex == 0 && 2827 RD->getMSInheritanceModel() == 2828 MSInheritanceModel::Virtual) 2829 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD); 2830 2831 // The rest of the fields are common with data member pointers. 2832 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 2833 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 2834 NonVirtualBaseAdjustment, VBTableIndex); 2835 } 2836 2837 /// Member pointers are the same if they're either bitwise identical *or* both 2838 /// null. Null-ness for function members is determined by the first field, 2839 /// while for data member pointers we must compare all fields. 2840 llvm::Value * 2841 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 2842 llvm::Value *L, 2843 llvm::Value *R, 2844 const MemberPointerType *MPT, 2845 bool Inequality) { 2846 CGBuilderTy &Builder = CGF.Builder; 2847 2848 // Handle != comparisons by switching the sense of all boolean operations. 2849 llvm::ICmpInst::Predicate Eq; 2850 llvm::Instruction::BinaryOps And, Or; 2851 if (Inequality) { 2852 Eq = llvm::ICmpInst::ICMP_NE; 2853 And = llvm::Instruction::Or; 2854 Or = llvm::Instruction::And; 2855 } else { 2856 Eq = llvm::ICmpInst::ICMP_EQ; 2857 And = llvm::Instruction::And; 2858 Or = llvm::Instruction::Or; 2859 } 2860 2861 // If this is a single field member pointer (single inheritance), this is a 2862 // single icmp. 2863 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2864 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2865 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(), 2866 Inheritance)) 2867 return Builder.CreateICmp(Eq, L, R); 2868 2869 // Compare the first field. 2870 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 2871 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 2872 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 2873 2874 // Compare everything other than the first field. 2875 llvm::Value *Res = nullptr; 2876 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 2877 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 2878 llvm::Value *LF = Builder.CreateExtractValue(L, I); 2879 llvm::Value *RF = Builder.CreateExtractValue(R, I); 2880 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 2881 if (Res) 2882 Res = Builder.CreateBinOp(And, Res, Cmp); 2883 else 2884 Res = Cmp; 2885 } 2886 2887 // Check if the first field is 0 if this is a function pointer. 2888 if (MPT->isMemberFunctionPointer()) { 2889 // (l1 == r1 && ...) || l0 == 0 2890 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 2891 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 2892 Res = Builder.CreateBinOp(Or, Res, IsZero); 2893 } 2894 2895 // Combine the comparison of the first field, which must always be true for 2896 // this comparison to succeeed. 2897 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 2898 } 2899 2900 llvm::Value * 2901 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 2902 llvm::Value *MemPtr, 2903 const MemberPointerType *MPT) { 2904 CGBuilderTy &Builder = CGF.Builder; 2905 llvm::SmallVector<llvm::Constant *, 4> fields; 2906 // We only need one field for member functions. 2907 if (MPT->isMemberFunctionPointer()) 2908 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 2909 else 2910 GetNullMemberPointerFields(MPT, fields); 2911 assert(!fields.empty()); 2912 llvm::Value *FirstField = MemPtr; 2913 if (MemPtr->getType()->isStructTy()) 2914 FirstField = Builder.CreateExtractValue(MemPtr, 0); 2915 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 2916 2917 // For function member pointers, we only need to test the function pointer 2918 // field. The other fields if any can be garbage. 2919 if (MPT->isMemberFunctionPointer()) 2920 return Res; 2921 2922 // Otherwise, emit a series of compares and combine the results. 2923 for (int I = 1, E = fields.size(); I < E; ++I) { 2924 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 2925 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 2926 Res = Builder.CreateOr(Res, Next, "memptr.tobool"); 2927 } 2928 return Res; 2929 } 2930 2931 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 2932 llvm::Constant *Val) { 2933 // Function pointers are null if the pointer in the first field is null. 2934 if (MPT->isMemberFunctionPointer()) { 2935 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 2936 Val->getAggregateElement(0U) : Val; 2937 return FirstField->isNullValue(); 2938 } 2939 2940 // If it's not a function pointer and it's zero initializable, we can easily 2941 // check zero. 2942 if (isZeroInitializable(MPT) && Val->isNullValue()) 2943 return true; 2944 2945 // Otherwise, break down all the fields for comparison. Hopefully these 2946 // little Constants are reused, while a big null struct might not be. 2947 llvm::SmallVector<llvm::Constant *, 4> Fields; 2948 GetNullMemberPointerFields(MPT, Fields); 2949 if (Fields.size() == 1) { 2950 assert(Val->getType()->isIntegerTy()); 2951 return Val == Fields[0]; 2952 } 2953 2954 unsigned I, E; 2955 for (I = 0, E = Fields.size(); I != E; ++I) { 2956 if (Val->getAggregateElement(I) != Fields[I]) 2957 break; 2958 } 2959 return I == E; 2960 } 2961 2962 llvm::Value * 2963 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 2964 Address This, 2965 llvm::Value *VBPtrOffset, 2966 llvm::Value *VBTableOffset, 2967 llvm::Value **VBPtrOut) { 2968 CGBuilderTy &Builder = CGF.Builder; 2969 // Load the vbtable pointer from the vbptr in the instance. 2970 This = Builder.CreateElementBitCast(This, CGM.Int8Ty); 2971 llvm::Value *VBPtr = 2972 Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr"); 2973 if (VBPtrOut) *VBPtrOut = VBPtr; 2974 VBPtr = Builder.CreateBitCast(VBPtr, 2975 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace())); 2976 2977 CharUnits VBPtrAlign; 2978 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) { 2979 VBPtrAlign = This.getAlignment().alignmentAtOffset( 2980 CharUnits::fromQuantity(CI->getSExtValue())); 2981 } else { 2982 VBPtrAlign = CGF.getPointerAlign(); 2983 } 2984 2985 llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable"); 2986 2987 // Translate from byte offset to table index. It improves analyzability. 2988 llvm::Value *VBTableIndex = Builder.CreateAShr( 2989 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2), 2990 "vbtindex", /*isExact=*/true); 2991 2992 // Load an i32 offset from the vb-table. 2993 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex); 2994 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 2995 return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4), 2996 "vbase_offs"); 2997 } 2998 2999 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 3000 // it. 3001 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase( 3002 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD, 3003 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) { 3004 CGBuilderTy &Builder = CGF.Builder; 3005 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty); 3006 llvm::BasicBlock *OriginalBB = nullptr; 3007 llvm::BasicBlock *SkipAdjustBB = nullptr; 3008 llvm::BasicBlock *VBaseAdjustBB = nullptr; 3009 3010 // In the unspecified inheritance model, there might not be a vbtable at all, 3011 // in which case we need to skip the virtual base lookup. If there is a 3012 // vbtable, the first entry is a no-op entry that gives back the original 3013 // base, so look for a virtual base adjustment offset of zero. 3014 if (VBPtrOffset) { 3015 OriginalBB = Builder.GetInsertBlock(); 3016 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 3017 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 3018 llvm::Value *IsVirtual = 3019 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 3020 "memptr.is_vbase"); 3021 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 3022 CGF.EmitBlock(VBaseAdjustBB); 3023 } 3024 3025 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 3026 // know the vbptr offset. 3027 if (!VBPtrOffset) { 3028 CharUnits offs = CharUnits::Zero(); 3029 if (!RD->hasDefinition()) { 3030 DiagnosticsEngine &Diags = CGF.CGM.getDiags(); 3031 unsigned DiagID = Diags.getCustomDiagID( 3032 DiagnosticsEngine::Error, 3033 "member pointer representation requires a " 3034 "complete class type for %0 to perform this expression"); 3035 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange(); 3036 } else if (RD->getNumVBases()) 3037 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 3038 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 3039 } 3040 llvm::Value *VBPtr = nullptr; 3041 llvm::Value *VBaseOffs = 3042 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 3043 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 3044 3045 // Merge control flow with the case where we didn't have to adjust. 3046 if (VBaseAdjustBB) { 3047 Builder.CreateBr(SkipAdjustBB); 3048 CGF.EmitBlock(SkipAdjustBB); 3049 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 3050 Phi->addIncoming(Base.getPointer(), OriginalBB); 3051 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 3052 return Phi; 3053 } 3054 return AdjustedBase; 3055 } 3056 3057 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress( 3058 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, 3059 const MemberPointerType *MPT) { 3060 assert(MPT->isMemberDataPointer()); 3061 unsigned AS = Base.getAddressSpace(); 3062 llvm::Type *PType = 3063 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 3064 CGBuilderTy &Builder = CGF.Builder; 3065 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 3066 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 3067 3068 // Extract the fields we need, regardless of model. We'll apply them if we 3069 // have them. 3070 llvm::Value *FieldOffset = MemPtr; 3071 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 3072 llvm::Value *VBPtrOffset = nullptr; 3073 if (MemPtr->getType()->isStructTy()) { 3074 // We need to extract values. 3075 unsigned I = 0; 3076 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 3077 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 3078 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 3079 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 3080 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 3081 } 3082 3083 llvm::Value *Addr; 3084 if (VirtualBaseAdjustmentOffset) { 3085 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset, 3086 VBPtrOffset); 3087 } else { 3088 Addr = Base.getPointer(); 3089 } 3090 3091 // Cast to char*. 3092 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS)); 3093 3094 // Apply the offset, which we assume is non-null. 3095 Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset"); 3096 3097 // Cast the address to the appropriate pointer type, adopting the address 3098 // space of the base pointer. 3099 return Builder.CreateBitCast(Addr, PType); 3100 } 3101 3102 llvm::Value * 3103 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 3104 const CastExpr *E, 3105 llvm::Value *Src) { 3106 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 3107 E->getCastKind() == CK_BaseToDerivedMemberPointer || 3108 E->getCastKind() == CK_ReinterpretMemberPointer); 3109 3110 // Use constant emission if we can. 3111 if (isa<llvm::Constant>(Src)) 3112 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 3113 3114 // We may be adding or dropping fields from the member pointer, so we need 3115 // both types and the inheritance models of both records. 3116 const MemberPointerType *SrcTy = 3117 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 3118 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 3119 bool IsFunc = SrcTy->isMemberFunctionPointer(); 3120 3121 // If the classes use the same null representation, reinterpret_cast is a nop. 3122 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 3123 if (IsReinterpret && IsFunc) 3124 return Src; 3125 3126 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 3127 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 3128 if (IsReinterpret && 3129 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 3130 return Src; 3131 3132 CGBuilderTy &Builder = CGF.Builder; 3133 3134 // Branch past the conversion if Src is null. 3135 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 3136 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 3137 3138 // C++ 5.2.10p9: The null member pointer value is converted to the null member 3139 // pointer value of the destination type. 3140 if (IsReinterpret) { 3141 // For reinterpret casts, sema ensures that src and dst are both functions 3142 // or data and have the same size, which means the LLVM types should match. 3143 assert(Src->getType() == DstNull->getType()); 3144 return Builder.CreateSelect(IsNotNull, Src, DstNull); 3145 } 3146 3147 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 3148 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 3149 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 3150 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 3151 CGF.EmitBlock(ConvertBB); 3152 3153 llvm::Value *Dst = EmitNonNullMemberPointerConversion( 3154 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src, 3155 Builder); 3156 3157 Builder.CreateBr(ContinueBB); 3158 3159 // In the continuation, choose between DstNull and Dst. 3160 CGF.EmitBlock(ContinueBB); 3161 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 3162 Phi->addIncoming(DstNull, OriginalBB); 3163 Phi->addIncoming(Dst, ConvertBB); 3164 return Phi; 3165 } 3166 3167 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion( 3168 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK, 3169 CastExpr::path_const_iterator PathBegin, 3170 CastExpr::path_const_iterator PathEnd, llvm::Value *Src, 3171 CGBuilderTy &Builder) { 3172 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 3173 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 3174 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel(); 3175 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel(); 3176 bool IsFunc = SrcTy->isMemberFunctionPointer(); 3177 bool IsConstant = isa<llvm::Constant>(Src); 3178 3179 // Decompose src. 3180 llvm::Value *FirstField = Src; 3181 llvm::Value *NonVirtualBaseAdjustment = getZeroInt(); 3182 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt(); 3183 llvm::Value *VBPtrOffset = getZeroInt(); 3184 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) { 3185 // We need to extract values. 3186 unsigned I = 0; 3187 FirstField = Builder.CreateExtractValue(Src, I++); 3188 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance)) 3189 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 3190 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance)) 3191 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 3192 if (inheritanceModelHasVBTableOffsetField(SrcInheritance)) 3193 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 3194 } 3195 3196 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer); 3197 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy; 3198 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl(); 3199 3200 // For data pointers, we adjust the field offset directly. For functions, we 3201 // have a separate field. 3202 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 3203 3204 // The virtual inheritance model has a quirk: the virtual base table is always 3205 // referenced when dereferencing a member pointer even if the member pointer 3206 // is non-virtual. This is accounted for by adjusting the non-virtual offset 3207 // to point backwards to the top of the MDC from the first VBase. Undo this 3208 // adjustment to normalize the member pointer. 3209 llvm::Value *SrcVBIndexEqZero = 3210 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt()); 3211 if (SrcInheritance == MSInheritanceModel::Virtual) { 3212 if (int64_t SrcOffsetToFirstVBase = 3213 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) { 3214 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect( 3215 SrcVBIndexEqZero, 3216 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase), 3217 getZeroInt()); 3218 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment); 3219 } 3220 } 3221 3222 // A non-zero vbindex implies that we are dealing with a source member in a 3223 // floating virtual base in addition to some non-virtual offset. If the 3224 // vbindex is zero, we are dealing with a source that exists in a non-virtual, 3225 // fixed, base. The difference between these two cases is that the vbindex + 3226 // nvoffset *always* point to the member regardless of what context they are 3227 // evaluated in so long as the vbindex is adjusted. A member inside a fixed 3228 // base requires explicit nv adjustment. 3229 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get( 3230 CGM.IntTy, 3231 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd) 3232 .getQuantity()); 3233 3234 llvm::Value *NVDisp; 3235 if (IsDerivedToBase) 3236 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj"); 3237 else 3238 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj"); 3239 3240 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt()); 3241 3242 // Update the vbindex to an appropriate value in the destination because 3243 // SrcRD's vbtable might not be a strict prefix of the one in DstRD. 3244 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero; 3245 if (inheritanceModelHasVBTableOffsetField(DstInheritance) && 3246 inheritanceModelHasVBTableOffsetField(SrcInheritance)) { 3247 if (llvm::GlobalVariable *VDispMap = 3248 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) { 3249 llvm::Value *VBIndex = Builder.CreateExactUDiv( 3250 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4)); 3251 if (IsConstant) { 3252 llvm::Constant *Mapping = VDispMap->getInitializer(); 3253 VirtualBaseAdjustmentOffset = 3254 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex)); 3255 } else { 3256 llvm::Value *Idxs[] = {getZeroInt(), VBIndex}; 3257 VirtualBaseAdjustmentOffset = 3258 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs), 3259 CharUnits::fromQuantity(4)); 3260 } 3261 3262 DstVBIndexEqZero = 3263 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt()); 3264 } 3265 } 3266 3267 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize 3268 // it to the offset of the vbptr. 3269 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) { 3270 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get( 3271 CGM.IntTy, 3272 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity()); 3273 VBPtrOffset = 3274 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset); 3275 } 3276 3277 // Likewise, apply a similar adjustment so that dereferencing the member 3278 // pointer correctly accounts for the distance between the start of the first 3279 // virtual base and the top of the MDC. 3280 if (DstInheritance == MSInheritanceModel::Virtual) { 3281 if (int64_t DstOffsetToFirstVBase = 3282 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) { 3283 llvm::Value *DoDstAdjustment = Builder.CreateSelect( 3284 DstVBIndexEqZero, 3285 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase), 3286 getZeroInt()); 3287 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment); 3288 } 3289 } 3290 3291 // Recompose dst from the null struct and the adjusted fields from src. 3292 llvm::Value *Dst; 3293 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) { 3294 Dst = FirstField; 3295 } else { 3296 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy)); 3297 unsigned Idx = 0; 3298 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 3299 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance)) 3300 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++); 3301 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) 3302 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++); 3303 if (inheritanceModelHasVBTableOffsetField(DstInheritance)) 3304 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++); 3305 } 3306 return Dst; 3307 } 3308 3309 llvm::Constant * 3310 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 3311 llvm::Constant *Src) { 3312 const MemberPointerType *SrcTy = 3313 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 3314 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 3315 3316 CastKind CK = E->getCastKind(); 3317 3318 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(), 3319 E->path_end(), Src); 3320 } 3321 3322 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion( 3323 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK, 3324 CastExpr::path_const_iterator PathBegin, 3325 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) { 3326 assert(CK == CK_DerivedToBaseMemberPointer || 3327 CK == CK_BaseToDerivedMemberPointer || 3328 CK == CK_ReinterpretMemberPointer); 3329 // If src is null, emit a new null for dst. We can't return src because dst 3330 // might have a new representation. 3331 if (MemberPointerConstantIsNull(SrcTy, Src)) 3332 return EmitNullMemberPointer(DstTy); 3333 3334 // We don't need to do anything for reinterpret_casts of non-null member 3335 // pointers. We should only get here when the two type representations have 3336 // the same size. 3337 if (CK == CK_ReinterpretMemberPointer) 3338 return Src; 3339 3340 CGBuilderTy Builder(CGM, CGM.getLLVMContext()); 3341 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion( 3342 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder)); 3343 3344 return Dst; 3345 } 3346 3347 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer( 3348 CodeGenFunction &CGF, const Expr *E, Address This, 3349 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr, 3350 const MemberPointerType *MPT) { 3351 assert(MPT->isMemberFunctionPointer()); 3352 const FunctionProtoType *FPT = 3353 MPT->getPointeeType()->castAs<FunctionProtoType>(); 3354 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 3355 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( 3356 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); 3357 CGBuilderTy &Builder = CGF.Builder; 3358 3359 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 3360 3361 // Extract the fields we need, regardless of model. We'll apply them if we 3362 // have them. 3363 llvm::Value *FunctionPointer = MemPtr; 3364 llvm::Value *NonVirtualBaseAdjustment = nullptr; 3365 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 3366 llvm::Value *VBPtrOffset = nullptr; 3367 if (MemPtr->getType()->isStructTy()) { 3368 // We need to extract values. 3369 unsigned I = 0; 3370 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 3371 if (inheritanceModelHasNVOffsetField(MPT, Inheritance)) 3372 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 3373 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 3374 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 3375 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 3376 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 3377 } 3378 3379 if (VirtualBaseAdjustmentOffset) { 3380 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This, 3381 VirtualBaseAdjustmentOffset, VBPtrOffset); 3382 } else { 3383 ThisPtrForCall = This.getPointer(); 3384 } 3385 3386 if (NonVirtualBaseAdjustment) { 3387 // Apply the adjustment and cast back to the original struct type. 3388 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy); 3389 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 3390 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(), 3391 "this.adjusted"); 3392 } 3393 3394 FunctionPointer = 3395 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 3396 CGCallee Callee(FPT, FunctionPointer); 3397 return Callee; 3398 } 3399 3400 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 3401 return new MicrosoftCXXABI(CGM); 3402 } 3403 3404 // MS RTTI Overview: 3405 // The run time type information emitted by cl.exe contains 5 distinct types of 3406 // structures. Many of them reference each other. 3407 // 3408 // TypeInfo: Static classes that are returned by typeid. 3409 // 3410 // CompleteObjectLocator: Referenced by vftables. They contain information 3411 // required for dynamic casting, including OffsetFromTop. They also contain 3412 // a reference to the TypeInfo for the type and a reference to the 3413 // CompleteHierarchyDescriptor for the type. 3414 // 3415 // ClassHierarchyDescriptor: Contains information about a class hierarchy. 3416 // Used during dynamic_cast to walk a class hierarchy. References a base 3417 // class array and the size of said array. 3418 // 3419 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is 3420 // somewhat of a misnomer because the most derived class is also in the list 3421 // as well as multiple copies of virtual bases (if they occur multiple times 3422 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for 3423 // every path in the hierarchy, in pre-order depth first order. Note, we do 3424 // not declare a specific llvm type for BaseClassArray, it's merely an array 3425 // of BaseClassDescriptor pointers. 3426 // 3427 // BaseClassDescriptor: Contains information about a class in a class hierarchy. 3428 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that 3429 // BaseClassArray is. It contains information about a class within a 3430 // hierarchy such as: is this base is ambiguous and what is its offset in the 3431 // vbtable. The names of the BaseClassDescriptors have all of their fields 3432 // mangled into them so they can be aggressively deduplicated by the linker. 3433 3434 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) { 3435 StringRef MangledName("??_7type_info@@6B@"); 3436 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName)) 3437 return VTable; 3438 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 3439 /*isConstant=*/true, 3440 llvm::GlobalVariable::ExternalLinkage, 3441 /*Initializer=*/nullptr, MangledName); 3442 } 3443 3444 namespace { 3445 3446 /// A Helper struct that stores information about a class in a class 3447 /// hierarchy. The information stored in these structs struct is used during 3448 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors. 3449 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with 3450 // implicit depth first pre-order tree connectivity. getFirstChild and 3451 // getNextSibling allow us to walk the tree efficiently. 3452 struct MSRTTIClass { 3453 enum { 3454 IsPrivateOnPath = 1 | 8, 3455 IsAmbiguous = 2, 3456 IsPrivate = 4, 3457 IsVirtual = 16, 3458 HasHierarchyDescriptor = 64 3459 }; 3460 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {} 3461 uint32_t initialize(const MSRTTIClass *Parent, 3462 const CXXBaseSpecifier *Specifier); 3463 3464 MSRTTIClass *getFirstChild() { return this + 1; } 3465 static MSRTTIClass *getNextChild(MSRTTIClass *Child) { 3466 return Child + 1 + Child->NumBases; 3467 } 3468 3469 const CXXRecordDecl *RD, *VirtualRoot; 3470 uint32_t Flags, NumBases, OffsetInVBase; 3471 }; 3472 3473 /// Recursively initialize the base class array. 3474 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent, 3475 const CXXBaseSpecifier *Specifier) { 3476 Flags = HasHierarchyDescriptor; 3477 if (!Parent) { 3478 VirtualRoot = nullptr; 3479 OffsetInVBase = 0; 3480 } else { 3481 if (Specifier->getAccessSpecifier() != AS_public) 3482 Flags |= IsPrivate | IsPrivateOnPath; 3483 if (Specifier->isVirtual()) { 3484 Flags |= IsVirtual; 3485 VirtualRoot = RD; 3486 OffsetInVBase = 0; 3487 } else { 3488 if (Parent->Flags & IsPrivateOnPath) 3489 Flags |= IsPrivateOnPath; 3490 VirtualRoot = Parent->VirtualRoot; 3491 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext() 3492 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity(); 3493 } 3494 } 3495 NumBases = 0; 3496 MSRTTIClass *Child = getFirstChild(); 3497 for (const CXXBaseSpecifier &Base : RD->bases()) { 3498 NumBases += Child->initialize(this, &Base) + 1; 3499 Child = getNextChild(Child); 3500 } 3501 return NumBases; 3502 } 3503 3504 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) { 3505 switch (Ty->getLinkage()) { 3506 case NoLinkage: 3507 case InternalLinkage: 3508 case UniqueExternalLinkage: 3509 return llvm::GlobalValue::InternalLinkage; 3510 3511 case VisibleNoLinkage: 3512 case ModuleInternalLinkage: 3513 case ModuleLinkage: 3514 case ExternalLinkage: 3515 return llvm::GlobalValue::LinkOnceODRLinkage; 3516 } 3517 llvm_unreachable("Invalid linkage!"); 3518 } 3519 3520 /// An ephemeral helper class for building MS RTTI types. It caches some 3521 /// calls to the module and information about the most derived class in a 3522 /// hierarchy. 3523 struct MSRTTIBuilder { 3524 enum { 3525 HasBranchingHierarchy = 1, 3526 HasVirtualBranchingHierarchy = 2, 3527 HasAmbiguousBases = 4 3528 }; 3529 3530 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD) 3531 : CGM(ABI.CGM), Context(CGM.getContext()), 3532 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD), 3533 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))), 3534 ABI(ABI) {} 3535 3536 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes); 3537 llvm::GlobalVariable * 3538 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes); 3539 llvm::GlobalVariable *getClassHierarchyDescriptor(); 3540 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info); 3541 3542 CodeGenModule &CGM; 3543 ASTContext &Context; 3544 llvm::LLVMContext &VMContext; 3545 llvm::Module &Module; 3546 const CXXRecordDecl *RD; 3547 llvm::GlobalVariable::LinkageTypes Linkage; 3548 MicrosoftCXXABI &ABI; 3549 }; 3550 3551 } // namespace 3552 3553 /// Recursively serializes a class hierarchy in pre-order depth first 3554 /// order. 3555 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes, 3556 const CXXRecordDecl *RD) { 3557 Classes.push_back(MSRTTIClass(RD)); 3558 for (const CXXBaseSpecifier &Base : RD->bases()) 3559 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl()); 3560 } 3561 3562 /// Find ambiguity among base classes. 3563 static void 3564 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) { 3565 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases; 3566 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases; 3567 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases; 3568 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) { 3569 if ((Class->Flags & MSRTTIClass::IsVirtual) && 3570 !VirtualBases.insert(Class->RD).second) { 3571 Class = MSRTTIClass::getNextChild(Class); 3572 continue; 3573 } 3574 if (!UniqueBases.insert(Class->RD).second) 3575 AmbiguousBases.insert(Class->RD); 3576 Class++; 3577 } 3578 if (AmbiguousBases.empty()) 3579 return; 3580 for (MSRTTIClass &Class : Classes) 3581 if (AmbiguousBases.count(Class.RD)) 3582 Class.Flags |= MSRTTIClass::IsAmbiguous; 3583 } 3584 3585 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() { 3586 SmallString<256> MangledName; 3587 { 3588 llvm::raw_svector_ostream Out(MangledName); 3589 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out); 3590 } 3591 3592 // Check to see if we've already declared this ClassHierarchyDescriptor. 3593 if (auto CHD = Module.getNamedGlobal(MangledName)) 3594 return CHD; 3595 3596 // Serialize the class hierarchy and initialize the CHD Fields. 3597 SmallVector<MSRTTIClass, 8> Classes; 3598 serializeClassHierarchy(Classes, RD); 3599 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr); 3600 detectAmbiguousBases(Classes); 3601 int Flags = 0; 3602 for (auto Class : Classes) { 3603 if (Class.RD->getNumBases() > 1) 3604 Flags |= HasBranchingHierarchy; 3605 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We 3606 // believe the field isn't actually used. 3607 if (Class.Flags & MSRTTIClass::IsAmbiguous) 3608 Flags |= HasAmbiguousBases; 3609 } 3610 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0) 3611 Flags |= HasVirtualBranchingHierarchy; 3612 // These gep indices are used to get the address of the first element of the 3613 // base class array. 3614 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0), 3615 llvm::ConstantInt::get(CGM.IntTy, 0)}; 3616 3617 // Forward-declare the class hierarchy descriptor 3618 auto Type = ABI.getClassHierarchyDescriptorType(); 3619 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage, 3620 /*Initializer=*/nullptr, 3621 MangledName); 3622 if (CHD->isWeakForLinker()) 3623 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName())); 3624 3625 auto *Bases = getBaseClassArray(Classes); 3626 3627 // Initialize the base class ClassHierarchyDescriptor. 3628 llvm::Constant *Fields[] = { 3629 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime 3630 llvm::ConstantInt::get(CGM.IntTy, Flags), 3631 llvm::ConstantInt::get(CGM.IntTy, Classes.size()), 3632 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr( 3633 Bases->getValueType(), Bases, 3634 llvm::ArrayRef<llvm::Value *>(GEPIndices))), 3635 }; 3636 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 3637 return CHD; 3638 } 3639 3640 llvm::GlobalVariable * 3641 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) { 3642 SmallString<256> MangledName; 3643 { 3644 llvm::raw_svector_ostream Out(MangledName); 3645 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out); 3646 } 3647 3648 // Forward-declare the base class array. 3649 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit 3650 // mode) bytes of padding. We provide a pointer sized amount of padding by 3651 // adding +1 to Classes.size(). The sections have pointer alignment and are 3652 // marked pick-any so it shouldn't matter. 3653 llvm::Type *PtrType = ABI.getImageRelativeType( 3654 ABI.getBaseClassDescriptorType()->getPointerTo()); 3655 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1); 3656 auto *BCA = 3657 new llvm::GlobalVariable(Module, ArrType, 3658 /*isConstant=*/true, Linkage, 3659 /*Initializer=*/nullptr, MangledName); 3660 if (BCA->isWeakForLinker()) 3661 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName())); 3662 3663 // Initialize the BaseClassArray. 3664 SmallVector<llvm::Constant *, 8> BaseClassArrayData; 3665 for (MSRTTIClass &Class : Classes) 3666 BaseClassArrayData.push_back( 3667 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class))); 3668 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType)); 3669 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData)); 3670 return BCA; 3671 } 3672 3673 llvm::GlobalVariable * 3674 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) { 3675 // Compute the fields for the BaseClassDescriptor. They are computed up front 3676 // because they are mangled into the name of the object. 3677 uint32_t OffsetInVBTable = 0; 3678 int32_t VBPtrOffset = -1; 3679 if (Class.VirtualRoot) { 3680 auto &VTableContext = CGM.getMicrosoftVTableContext(); 3681 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4; 3682 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity(); 3683 } 3684 3685 SmallString<256> MangledName; 3686 { 3687 llvm::raw_svector_ostream Out(MangledName); 3688 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor( 3689 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable, 3690 Class.Flags, Out); 3691 } 3692 3693 // Check to see if we've already declared this object. 3694 if (auto BCD = Module.getNamedGlobal(MangledName)) 3695 return BCD; 3696 3697 // Forward-declare the base class descriptor. 3698 auto Type = ABI.getBaseClassDescriptorType(); 3699 auto BCD = 3700 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage, 3701 /*Initializer=*/nullptr, MangledName); 3702 if (BCD->isWeakForLinker()) 3703 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName())); 3704 3705 // Initialize the BaseClassDescriptor. 3706 llvm::Constant *Fields[] = { 3707 ABI.getImageRelativeConstant( 3708 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))), 3709 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases), 3710 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase), 3711 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 3712 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable), 3713 llvm::ConstantInt::get(CGM.IntTy, Class.Flags), 3714 ABI.getImageRelativeConstant( 3715 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()), 3716 }; 3717 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 3718 return BCD; 3719 } 3720 3721 llvm::GlobalVariable * 3722 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) { 3723 SmallString<256> MangledName; 3724 { 3725 llvm::raw_svector_ostream Out(MangledName); 3726 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out); 3727 } 3728 3729 // Check to see if we've already computed this complete object locator. 3730 if (auto COL = Module.getNamedGlobal(MangledName)) 3731 return COL; 3732 3733 // Compute the fields of the complete object locator. 3734 int OffsetToTop = Info.FullOffsetInMDC.getQuantity(); 3735 int VFPtrOffset = 0; 3736 // The offset includes the vtordisp if one exists. 3737 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr()) 3738 if (Context.getASTRecordLayout(RD) 3739 .getVBaseOffsetsMap() 3740 .find(VBase) 3741 ->second.hasVtorDisp()) 3742 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4; 3743 3744 // Forward-declare the complete object locator. 3745 llvm::StructType *Type = ABI.getCompleteObjectLocatorType(); 3746 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage, 3747 /*Initializer=*/nullptr, MangledName); 3748 3749 // Initialize the CompleteObjectLocator. 3750 llvm::Constant *Fields[] = { 3751 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()), 3752 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop), 3753 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset), 3754 ABI.getImageRelativeConstant( 3755 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))), 3756 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()), 3757 ABI.getImageRelativeConstant(COL), 3758 }; 3759 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields); 3760 if (!ABI.isImageRelative()) 3761 FieldsRef = FieldsRef.drop_back(); 3762 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef)); 3763 if (COL->isWeakForLinker()) 3764 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName())); 3765 return COL; 3766 } 3767 3768 static QualType decomposeTypeForEH(ASTContext &Context, QualType T, 3769 bool &IsConst, bool &IsVolatile, 3770 bool &IsUnaligned) { 3771 T = Context.getExceptionObjectType(T); 3772 3773 // C++14 [except.handle]p3: 3774 // A handler is a match for an exception object of type E if [...] 3775 // - the handler is of type cv T or const T& where T is a pointer type and 3776 // E is a pointer type that can be converted to T by [...] 3777 // - a qualification conversion 3778 IsConst = false; 3779 IsVolatile = false; 3780 IsUnaligned = false; 3781 QualType PointeeType = T->getPointeeType(); 3782 if (!PointeeType.isNull()) { 3783 IsConst = PointeeType.isConstQualified(); 3784 IsVolatile = PointeeType.isVolatileQualified(); 3785 IsUnaligned = PointeeType.getQualifiers().hasUnaligned(); 3786 } 3787 3788 // Member pointer types like "const int A::*" are represented by having RTTI 3789 // for "int A::*" and separately storing the const qualifier. 3790 if (const auto *MPTy = T->getAs<MemberPointerType>()) 3791 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(), 3792 MPTy->getClass()); 3793 3794 // Pointer types like "const int * const *" are represented by having RTTI 3795 // for "const int **" and separately storing the const qualifier. 3796 if (T->isPointerType()) 3797 T = Context.getPointerType(PointeeType.getUnqualifiedType()); 3798 3799 return T; 3800 } 3801 3802 CatchTypeInfo 3803 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type, 3804 QualType CatchHandlerType) { 3805 // TypeDescriptors for exceptions never have qualified pointer types, 3806 // qualifiers are stored separately in order to support qualification 3807 // conversions. 3808 bool IsConst, IsVolatile, IsUnaligned; 3809 Type = 3810 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned); 3811 3812 bool IsReference = CatchHandlerType->isReferenceType(); 3813 3814 uint32_t Flags = 0; 3815 if (IsConst) 3816 Flags |= 1; 3817 if (IsVolatile) 3818 Flags |= 2; 3819 if (IsUnaligned) 3820 Flags |= 4; 3821 if (IsReference) 3822 Flags |= 8; 3823 3824 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(), 3825 Flags}; 3826 } 3827 3828 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a 3829 /// llvm::GlobalVariable * because different type descriptors have different 3830 /// types, and need to be abstracted. They are abstracting by casting the 3831 /// address to an Int8PtrTy. 3832 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) { 3833 SmallString<256> MangledName; 3834 { 3835 llvm::raw_svector_ostream Out(MangledName); 3836 getMangleContext().mangleCXXRTTI(Type, Out); 3837 } 3838 3839 // Check to see if we've already declared this TypeDescriptor. 3840 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 3841 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 3842 3843 // Note for the future: If we would ever like to do deferred emission of 3844 // RTTI, check if emitting vtables opportunistically need any adjustment. 3845 3846 // Compute the fields for the TypeDescriptor. 3847 SmallString<256> TypeInfoString; 3848 { 3849 llvm::raw_svector_ostream Out(TypeInfoString); 3850 getMangleContext().mangleCXXRTTIName(Type, Out); 3851 } 3852 3853 // Declare and initialize the TypeDescriptor. 3854 llvm::Constant *Fields[] = { 3855 getTypeInfoVTable(CGM), // VFPtr 3856 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data 3857 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)}; 3858 llvm::StructType *TypeDescriptorType = 3859 getTypeDescriptorType(TypeInfoString); 3860 auto *Var = new llvm::GlobalVariable( 3861 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false, 3862 getLinkageForRTTI(Type), 3863 llvm::ConstantStruct::get(TypeDescriptorType, Fields), 3864 MangledName); 3865 if (Var->isWeakForLinker()) 3866 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName())); 3867 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy); 3868 } 3869 3870 /// Gets or a creates a Microsoft CompleteObjectLocator. 3871 llvm::GlobalVariable * 3872 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD, 3873 const VPtrInfo &Info) { 3874 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info); 3875 } 3876 3877 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) { 3878 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) { 3879 // There are no constructor variants, always emit the complete destructor. 3880 llvm::Function *Fn = 3881 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete)); 3882 CGM.maybeSetTrivialComdat(*ctor, *Fn); 3883 return; 3884 } 3885 3886 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl()); 3887 3888 // Emit the base destructor if the base and complete (vbase) destructors are 3889 // equivalent. This effectively implements -mconstructor-aliases as part of 3890 // the ABI. 3891 if (GD.getDtorType() == Dtor_Complete && 3892 dtor->getParent()->getNumVBases() == 0) 3893 GD = GD.getWithDtorType(Dtor_Base); 3894 3895 // The base destructor is equivalent to the base destructor of its 3896 // base class if there is exactly one non-virtual base class with a 3897 // non-trivial destructor, there are no fields with a non-trivial 3898 // destructor, and the body of the destructor is trivial. 3899 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor)) 3900 return; 3901 3902 llvm::Function *Fn = CGM.codegenCXXStructor(GD); 3903 if (Fn->isWeakForLinker()) 3904 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName())); 3905 } 3906 3907 llvm::Function * 3908 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD, 3909 CXXCtorType CT) { 3910 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure); 3911 3912 // Calculate the mangled name. 3913 SmallString<256> ThunkName; 3914 llvm::raw_svector_ostream Out(ThunkName); 3915 getMangleContext().mangleCXXCtor(CD, CT, Out); 3916 3917 // If the thunk has been generated previously, just return it. 3918 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 3919 return cast<llvm::Function>(GV); 3920 3921 // Create the llvm::Function. 3922 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT); 3923 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 3924 const CXXRecordDecl *RD = CD->getParent(); 3925 QualType RecordTy = getContext().getRecordType(RD); 3926 llvm::Function *ThunkFn = llvm::Function::Create( 3927 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule()); 3928 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>( 3929 FnInfo.getEffectiveCallingConvention())); 3930 if (ThunkFn->isWeakForLinker()) 3931 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName())); 3932 bool IsCopy = CT == Ctor_CopyingClosure; 3933 3934 // Start codegen. 3935 CodeGenFunction CGF(CGM); 3936 CGF.CurGD = GlobalDecl(CD, Ctor_Complete); 3937 3938 // Build FunctionArgs. 3939 FunctionArgList FunctionArgs; 3940 3941 // A constructor always starts with a 'this' pointer as its first argument. 3942 buildThisParam(CGF, FunctionArgs); 3943 3944 // Following the 'this' pointer is a reference to the source object that we 3945 // are copying from. 3946 ImplicitParamDecl SrcParam( 3947 getContext(), /*DC=*/nullptr, SourceLocation(), 3948 &getContext().Idents.get("src"), 3949 getContext().getLValueReferenceType(RecordTy, 3950 /*SpelledAsLValue=*/true), 3951 ImplicitParamDecl::Other); 3952 if (IsCopy) 3953 FunctionArgs.push_back(&SrcParam); 3954 3955 // Constructors for classes which utilize virtual bases have an additional 3956 // parameter which indicates whether or not it is being delegated to by a more 3957 // derived constructor. 3958 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr, 3959 SourceLocation(), 3960 &getContext().Idents.get("is_most_derived"), 3961 getContext().IntTy, ImplicitParamDecl::Other); 3962 // Only add the parameter to the list if the class has virtual bases. 3963 if (RD->getNumVBases() > 0) 3964 FunctionArgs.push_back(&IsMostDerived); 3965 3966 // Start defining the function. 3967 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 3968 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo, 3969 FunctionArgs, CD->getLocation(), SourceLocation()); 3970 // Create a scope with an artificial location for the body of this function. 3971 auto AL = ApplyDebugLocation::CreateArtificial(CGF); 3972 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF)); 3973 llvm::Value *This = getThisValue(CGF); 3974 3975 llvm::Value *SrcVal = 3976 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src") 3977 : nullptr; 3978 3979 CallArgList Args; 3980 3981 // Push the this ptr. 3982 Args.add(RValue::get(This), CD->getThisType()); 3983 3984 // Push the src ptr. 3985 if (SrcVal) 3986 Args.add(RValue::get(SrcVal), SrcParam.getType()); 3987 3988 // Add the rest of the default arguments. 3989 SmallVector<const Stmt *, 4> ArgVec; 3990 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0); 3991 for (const ParmVarDecl *PD : params) { 3992 assert(PD->hasDefaultArg() && "ctor closure lacks default args"); 3993 ArgVec.push_back(PD->getDefaultArg()); 3994 } 3995 3996 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 3997 3998 const auto *FPT = CD->getType()->castAs<FunctionProtoType>(); 3999 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0); 4000 4001 // Insert any ABI-specific implicit constructor arguments. 4002 AddedStructorArgs ExtraArgs = 4003 addImplicitConstructorArgs(CGF, CD, Ctor_Complete, 4004 /*ForVirtualBase=*/false, 4005 /*Delegating=*/false, Args); 4006 // Call the destructor with our arguments. 4007 llvm::Constant *CalleePtr = 4008 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete)); 4009 CGCallee Callee = 4010 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete)); 4011 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall( 4012 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix); 4013 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args); 4014 4015 Cleanups.ForceCleanup(); 4016 4017 // Emit the ret instruction, remove any temporary instructions created for the 4018 // aid of CodeGen. 4019 CGF.FinishFunction(SourceLocation()); 4020 4021 return ThunkFn; 4022 } 4023 4024 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T, 4025 uint32_t NVOffset, 4026 int32_t VBPtrOffset, 4027 uint32_t VBIndex) { 4028 assert(!T->isReferenceType()); 4029 4030 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 4031 const CXXConstructorDecl *CD = 4032 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr; 4033 CXXCtorType CT = Ctor_Complete; 4034 if (CD) 4035 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1) 4036 CT = Ctor_CopyingClosure; 4037 4038 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity(); 4039 SmallString<256> MangledName; 4040 { 4041 llvm::raw_svector_ostream Out(MangledName); 4042 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset, 4043 VBPtrOffset, VBIndex, Out); 4044 } 4045 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 4046 return getImageRelativeConstant(GV); 4047 4048 // The TypeDescriptor is used by the runtime to determine if a catch handler 4049 // is appropriate for the exception object. 4050 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T)); 4051 4052 // The runtime is responsible for calling the copy constructor if the 4053 // exception is caught by value. 4054 llvm::Constant *CopyCtor; 4055 if (CD) { 4056 if (CT == Ctor_CopyingClosure) 4057 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure); 4058 else 4059 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete)); 4060 4061 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy); 4062 } else { 4063 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy); 4064 } 4065 CopyCtor = getImageRelativeConstant(CopyCtor); 4066 4067 bool IsScalar = !RD; 4068 bool HasVirtualBases = false; 4069 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason. 4070 QualType PointeeType = T; 4071 if (T->isPointerType()) 4072 PointeeType = T->getPointeeType(); 4073 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) { 4074 HasVirtualBases = RD->getNumVBases() > 0; 4075 if (IdentifierInfo *II = RD->getIdentifier()) 4076 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace(); 4077 } 4078 4079 // Encode the relevant CatchableType properties into the Flags bitfield. 4080 // FIXME: Figure out how bits 2 or 8 can get set. 4081 uint32_t Flags = 0; 4082 if (IsScalar) 4083 Flags |= 1; 4084 if (HasVirtualBases) 4085 Flags |= 4; 4086 if (IsStdBadAlloc) 4087 Flags |= 16; 4088 4089 llvm::Constant *Fields[] = { 4090 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags 4091 TD, // TypeDescriptor 4092 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment 4093 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr 4094 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex 4095 llvm::ConstantInt::get(CGM.IntTy, Size), // Size 4096 CopyCtor // CopyCtor 4097 }; 4098 llvm::StructType *CTType = getCatchableTypeType(); 4099 auto *GV = new llvm::GlobalVariable( 4100 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T), 4101 llvm::ConstantStruct::get(CTType, Fields), MangledName); 4102 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4103 GV->setSection(".xdata"); 4104 if (GV->isWeakForLinker()) 4105 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName())); 4106 return getImageRelativeConstant(GV); 4107 } 4108 4109 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) { 4110 assert(!T->isReferenceType()); 4111 4112 // See if we've already generated a CatchableTypeArray for this type before. 4113 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T]; 4114 if (CTA) 4115 return CTA; 4116 4117 // Ensure that we don't have duplicate entries in our CatchableTypeArray by 4118 // using a SmallSetVector. Duplicates may arise due to virtual bases 4119 // occurring more than once in the hierarchy. 4120 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes; 4121 4122 // C++14 [except.handle]p3: 4123 // A handler is a match for an exception object of type E if [...] 4124 // - the handler is of type cv T or cv T& and T is an unambiguous public 4125 // base class of E, or 4126 // - the handler is of type cv T or const T& where T is a pointer type and 4127 // E is a pointer type that can be converted to T by [...] 4128 // - a standard pointer conversion (4.10) not involving conversions to 4129 // pointers to private or protected or ambiguous classes 4130 const CXXRecordDecl *MostDerivedClass = nullptr; 4131 bool IsPointer = T->isPointerType(); 4132 if (IsPointer) 4133 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl(); 4134 else 4135 MostDerivedClass = T->getAsCXXRecordDecl(); 4136 4137 // Collect all the unambiguous public bases of the MostDerivedClass. 4138 if (MostDerivedClass) { 4139 const ASTContext &Context = getContext(); 4140 const ASTRecordLayout &MostDerivedLayout = 4141 Context.getASTRecordLayout(MostDerivedClass); 4142 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext(); 4143 SmallVector<MSRTTIClass, 8> Classes; 4144 serializeClassHierarchy(Classes, MostDerivedClass); 4145 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr); 4146 detectAmbiguousBases(Classes); 4147 for (const MSRTTIClass &Class : Classes) { 4148 // Skip any ambiguous or private bases. 4149 if (Class.Flags & 4150 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous)) 4151 continue; 4152 // Write down how to convert from a derived pointer to a base pointer. 4153 uint32_t OffsetInVBTable = 0; 4154 int32_t VBPtrOffset = -1; 4155 if (Class.VirtualRoot) { 4156 OffsetInVBTable = 4157 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4; 4158 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity(); 4159 } 4160 4161 // Turn our record back into a pointer if the exception object is a 4162 // pointer. 4163 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0); 4164 if (IsPointer) 4165 RTTITy = Context.getPointerType(RTTITy); 4166 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase, 4167 VBPtrOffset, OffsetInVBTable)); 4168 } 4169 } 4170 4171 // C++14 [except.handle]p3: 4172 // A handler is a match for an exception object of type E if 4173 // - The handler is of type cv T or cv T& and E and T are the same type 4174 // (ignoring the top-level cv-qualifiers) 4175 CatchableTypes.insert(getCatchableType(T)); 4176 4177 // C++14 [except.handle]p3: 4178 // A handler is a match for an exception object of type E if 4179 // - the handler is of type cv T or const T& where T is a pointer type and 4180 // E is a pointer type that can be converted to T by [...] 4181 // - a standard pointer conversion (4.10) not involving conversions to 4182 // pointers to private or protected or ambiguous classes 4183 // 4184 // C++14 [conv.ptr]p2: 4185 // A prvalue of type "pointer to cv T," where T is an object type, can be 4186 // converted to a prvalue of type "pointer to cv void". 4187 if (IsPointer && T->getPointeeType()->isObjectType()) 4188 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy)); 4189 4190 // C++14 [except.handle]p3: 4191 // A handler is a match for an exception object of type E if [...] 4192 // - the handler is of type cv T or const T& where T is a pointer or 4193 // pointer to member type and E is std::nullptr_t. 4194 // 4195 // We cannot possibly list all possible pointer types here, making this 4196 // implementation incompatible with the standard. However, MSVC includes an 4197 // entry for pointer-to-void in this case. Let's do the same. 4198 if (T->isNullPtrType()) 4199 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy)); 4200 4201 uint32_t NumEntries = CatchableTypes.size(); 4202 llvm::Type *CTType = 4203 getImageRelativeType(getCatchableTypeType()->getPointerTo()); 4204 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries); 4205 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries); 4206 llvm::Constant *Fields[] = { 4207 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries 4208 llvm::ConstantArray::get( 4209 AT, llvm::makeArrayRef(CatchableTypes.begin(), 4210 CatchableTypes.end())) // CatchableTypes 4211 }; 4212 SmallString<256> MangledName; 4213 { 4214 llvm::raw_svector_ostream Out(MangledName); 4215 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out); 4216 } 4217 CTA = new llvm::GlobalVariable( 4218 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T), 4219 llvm::ConstantStruct::get(CTAType, Fields), MangledName); 4220 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4221 CTA->setSection(".xdata"); 4222 if (CTA->isWeakForLinker()) 4223 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName())); 4224 return CTA; 4225 } 4226 4227 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) { 4228 bool IsConst, IsVolatile, IsUnaligned; 4229 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned); 4230 4231 // The CatchableTypeArray enumerates the various (CV-unqualified) types that 4232 // the exception object may be caught as. 4233 llvm::GlobalVariable *CTA = getCatchableTypeArray(T); 4234 // The first field in a CatchableTypeArray is the number of CatchableTypes. 4235 // This is used as a component of the mangled name which means that we need to 4236 // know what it is in order to see if we have previously generated the 4237 // ThrowInfo. 4238 uint32_t NumEntries = 4239 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U)) 4240 ->getLimitedValue(); 4241 4242 SmallString<256> MangledName; 4243 { 4244 llvm::raw_svector_ostream Out(MangledName); 4245 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned, 4246 NumEntries, Out); 4247 } 4248 4249 // Reuse a previously generated ThrowInfo if we have generated an appropriate 4250 // one before. 4251 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 4252 return GV; 4253 4254 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must 4255 // be at least as CV qualified. Encode this requirement into the Flags 4256 // bitfield. 4257 uint32_t Flags = 0; 4258 if (IsConst) 4259 Flags |= 1; 4260 if (IsVolatile) 4261 Flags |= 2; 4262 if (IsUnaligned) 4263 Flags |= 4; 4264 4265 // The cleanup-function (a destructor) must be called when the exception 4266 // object's lifetime ends. 4267 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy); 4268 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4269 if (CXXDestructorDecl *DtorD = RD->getDestructor()) 4270 if (!DtorD->isTrivial()) 4271 CleanupFn = llvm::ConstantExpr::getBitCast( 4272 CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)), 4273 CGM.Int8PtrTy); 4274 // This is unused as far as we can tell, initialize it to null. 4275 llvm::Constant *ForwardCompat = 4276 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy)); 4277 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant( 4278 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy)); 4279 llvm::StructType *TIType = getThrowInfoType(); 4280 llvm::Constant *Fields[] = { 4281 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags 4282 getImageRelativeConstant(CleanupFn), // CleanupFn 4283 ForwardCompat, // ForwardCompat 4284 PointerToCatchableTypes // CatchableTypeArray 4285 }; 4286 auto *GV = new llvm::GlobalVariable( 4287 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T), 4288 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName)); 4289 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4290 GV->setSection(".xdata"); 4291 if (GV->isWeakForLinker()) 4292 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName())); 4293 return GV; 4294 } 4295 4296 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) { 4297 const Expr *SubExpr = E->getSubExpr(); 4298 QualType ThrowType = SubExpr->getType(); 4299 // The exception object lives on the stack and it's address is passed to the 4300 // runtime function. 4301 Address AI = CGF.CreateMemTemp(ThrowType); 4302 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(), 4303 /*IsInit=*/true); 4304 4305 // The so-called ThrowInfo is used to describe how the exception object may be 4306 // caught. 4307 llvm::GlobalVariable *TI = getThrowInfo(ThrowType); 4308 4309 // Call into the runtime to throw the exception. 4310 llvm::Value *Args[] = { 4311 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy), 4312 TI 4313 }; 4314 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args); 4315 } 4316 4317 std::pair<llvm::Value *, const CXXRecordDecl *> 4318 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This, 4319 const CXXRecordDecl *RD) { 4320 std::tie(This, std::ignore, RD) = 4321 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0)); 4322 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD}; 4323 } 4324