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 1348 CharUnits 1349 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) { 1350 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1351 1352 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1353 // Complete destructors take a pointer to the complete object as a 1354 // parameter, thus don't need this adjustment. 1355 if (GD.getDtorType() == Dtor_Complete) 1356 return CharUnits(); 1357 1358 // There's no Dtor_Base in vftable but it shares the this adjustment with 1359 // the deleting one, so look it up instead. 1360 GD = GlobalDecl(DD, Dtor_Deleting); 1361 } 1362 1363 MethodVFTableLocation ML = 1364 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 1365 CharUnits Adjustment = ML.VFPtrOffset; 1366 1367 // Normal virtual instance methods need to adjust from the vfptr that first 1368 // defined the virtual method to the virtual base subobject, but destructors 1369 // do not. The vector deleting destructor thunk applies this adjustment for 1370 // us if necessary. 1371 if (isa<CXXDestructorDecl>(MD)) 1372 Adjustment = CharUnits::Zero(); 1373 1374 if (ML.VBase) { 1375 const ASTRecordLayout &DerivedLayout = 1376 getContext().getASTRecordLayout(MD->getParent()); 1377 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 1378 } 1379 1380 return Adjustment; 1381 } 1382 1383 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( 1384 CodeGenFunction &CGF, GlobalDecl GD, Address This, 1385 bool VirtualCall) { 1386 if (!VirtualCall) { 1387 // If the call of a virtual function is not virtual, we just have to 1388 // compensate for the adjustment the virtual function does in its prologue. 1389 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 1390 if (Adjustment.isZero()) 1391 return This; 1392 1393 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty); 1394 assert(Adjustment.isPositive()); 1395 return CGF.Builder.CreateConstByteGEP(This, Adjustment); 1396 } 1397 1398 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1399 1400 GlobalDecl LookupGD = GD; 1401 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1402 // Complete dtors take a pointer to the complete object, 1403 // thus don't need adjustment. 1404 if (GD.getDtorType() == Dtor_Complete) 1405 return This; 1406 1407 // There's only Dtor_Deleting in vftable but it shares the this adjustment 1408 // with the base one, so look up the deleting one instead. 1409 LookupGD = GlobalDecl(DD, Dtor_Deleting); 1410 } 1411 MethodVFTableLocation ML = 1412 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 1413 1414 CharUnits StaticOffset = ML.VFPtrOffset; 1415 1416 // Base destructors expect 'this' to point to the beginning of the base 1417 // subobject, not the first vfptr that happens to contain the virtual dtor. 1418 // However, we still need to apply the virtual base adjustment. 1419 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 1420 StaticOffset = CharUnits::Zero(); 1421 1422 Address Result = This; 1423 if (ML.VBase) { 1424 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty); 1425 1426 const CXXRecordDecl *Derived = MD->getParent(); 1427 const CXXRecordDecl *VBase = ML.VBase; 1428 llvm::Value *VBaseOffset = 1429 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase); 1430 llvm::Value *VBasePtr = 1431 CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset); 1432 CharUnits VBaseAlign = 1433 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase); 1434 Result = Address(VBasePtr, VBaseAlign); 1435 } 1436 if (!StaticOffset.isZero()) { 1437 assert(StaticOffset.isPositive()); 1438 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty); 1439 if (ML.VBase) { 1440 // Non-virtual adjustment might result in a pointer outside the allocated 1441 // object, e.g. if the final overrider class is laid out after the virtual 1442 // base that declares a method in the most derived class. 1443 // FIXME: Update the code that emits this adjustment in thunks prologues. 1444 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset); 1445 } else { 1446 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset); 1447 } 1448 } 1449 return Result; 1450 } 1451 1452 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1453 QualType &ResTy, 1454 FunctionArgList &Params) { 1455 ASTContext &Context = getContext(); 1456 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1457 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1458 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 1459 auto *IsMostDerived = ImplicitParamDecl::Create( 1460 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(), 1461 &Context.Idents.get("is_most_derived"), Context.IntTy, 1462 ImplicitParamDecl::Other); 1463 // The 'most_derived' parameter goes second if the ctor is variadic and last 1464 // if it's not. Dtors can't be variadic. 1465 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1466 if (FPT->isVariadic()) 1467 Params.insert(Params.begin() + 1, IsMostDerived); 1468 else 1469 Params.push_back(IsMostDerived); 1470 getStructorImplicitParamDecl(CGF) = IsMostDerived; 1471 } else if (isDeletingDtor(CGF.CurGD)) { 1472 auto *ShouldDelete = ImplicitParamDecl::Create( 1473 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(), 1474 &Context.Idents.get("should_call_delete"), Context.IntTy, 1475 ImplicitParamDecl::Other); 1476 Params.push_back(ShouldDelete); 1477 getStructorImplicitParamDecl(CGF) = ShouldDelete; 1478 } 1479 } 1480 1481 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1482 // Naked functions have no prolog. 1483 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>()) 1484 return; 1485 1486 // Overridden virtual methods of non-primary bases need to adjust the incoming 1487 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract 1488 // sizeof(void*) to adjust from B* to C*: 1489 // struct A { virtual void a(); }; 1490 // struct B { virtual void b(); }; 1491 // struct C : A, B { virtual void b(); }; 1492 // 1493 // Leave the value stored in the 'this' alloca unadjusted, so that the 1494 // debugger sees the unadjusted value. Microsoft debuggers require this, and 1495 // will apply the ThisAdjustment in the method type information. 1496 // FIXME: Do something better for DWARF debuggers, which won't expect this, 1497 // without making our codegen depend on debug info settings. 1498 llvm::Value *This = loadIncomingCXXThis(CGF); 1499 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1500 if (!CGF.CurFuncIsThunk && MD->isVirtual()) { 1501 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD); 1502 if (!Adjustment.isZero()) { 1503 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 1504 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 1505 *thisTy = This->getType(); 1506 This = CGF.Builder.CreateBitCast(This, charPtrTy); 1507 assert(Adjustment.isPositive()); 1508 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This, 1509 -Adjustment.getQuantity()); 1510 This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted"); 1511 } 1512 } 1513 setCXXABIThisValue(CGF, This); 1514 1515 // If this is a function that the ABI specifies returns 'this', initialize 1516 // the return slot to 'this' at the start of the function. 1517 // 1518 // Unlike the setting of return types, this is done within the ABI 1519 // implementation instead of by clients of CGCXXABI because: 1520 // 1) getThisValue is currently protected 1521 // 2) in theory, an ABI could implement 'this' returns some other way; 1522 // HasThisReturn only specifies a contract, not the implementation 1523 if (HasThisReturn(CGF.CurGD)) 1524 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1525 else if (hasMostDerivedReturn(CGF.CurGD)) 1526 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)), 1527 CGF.ReturnValue); 1528 1529 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 1530 assert(getStructorImplicitParamDecl(CGF) && 1531 "no implicit parameter for a constructor with virtual bases?"); 1532 getStructorImplicitParamValue(CGF) 1533 = CGF.Builder.CreateLoad( 1534 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1535 "is_most_derived"); 1536 } 1537 1538 if (isDeletingDtor(CGF.CurGD)) { 1539 assert(getStructorImplicitParamDecl(CGF) && 1540 "no implicit parameter for a deleting destructor?"); 1541 getStructorImplicitParamValue(CGF) 1542 = CGF.Builder.CreateLoad( 1543 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1544 "should_call_delete"); 1545 } 1546 } 1547 1548 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::addImplicitConstructorArgs( 1549 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1550 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1551 assert(Type == Ctor_Complete || Type == Ctor_Base); 1552 1553 // Check if we need a 'most_derived' parameter. 1554 if (!D->getParent()->getNumVBases()) 1555 return AddedStructorArgs{}; 1556 1557 // Add the 'most_derived' argument second if we are variadic or last if not. 1558 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1559 llvm::Value *MostDerivedArg; 1560 if (Delegating) { 1561 MostDerivedArg = getStructorImplicitParamValue(CGF); 1562 } else { 1563 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 1564 } 1565 RValue RV = RValue::get(MostDerivedArg); 1566 if (FPT->isVariadic()) { 1567 Args.insert(Args.begin() + 1, CallArg(RV, getContext().IntTy)); 1568 return AddedStructorArgs::prefix(1); 1569 } 1570 Args.add(RV, getContext().IntTy); 1571 return AddedStructorArgs::suffix(1); 1572 } 1573 1574 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1575 const CXXDestructorDecl *DD, 1576 CXXDtorType Type, bool ForVirtualBase, 1577 bool Delegating, Address This, 1578 QualType ThisTy) { 1579 // Use the base destructor variant in place of the complete destructor variant 1580 // if the class has no virtual bases. This effectively implements some of the 1581 // -mconstructor-aliases optimization, but as part of the MS C++ ABI. 1582 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0) 1583 Type = Dtor_Base; 1584 1585 GlobalDecl GD(DD, Type); 1586 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD); 1587 1588 if (DD->isVirtual()) { 1589 assert(Type != CXXDtorType::Dtor_Deleting && 1590 "The deleting destructor should only be called via a virtual call"); 1591 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), 1592 This, false); 1593 } 1594 1595 llvm::BasicBlock *BaseDtorEndBB = nullptr; 1596 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) { 1597 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF); 1598 } 1599 1600 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, 1601 /*ImplicitParam=*/nullptr, 1602 /*ImplicitParamTy=*/QualType(), nullptr); 1603 if (BaseDtorEndBB) { 1604 // Complete object handler should continue to be the remaining 1605 CGF.Builder.CreateBr(BaseDtorEndBB); 1606 CGF.EmitBlock(BaseDtorEndBB); 1607 } 1608 } 1609 1610 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info, 1611 const CXXRecordDecl *RD, 1612 llvm::GlobalVariable *VTable) { 1613 if (!CGM.getCodeGenOpts().LTOUnit) 1614 return; 1615 1616 // The location of the first virtual function pointer in the virtual table, 1617 // aka the "address point" on Itanium. This is at offset 0 if RTTI is 1618 // disabled, or sizeof(void*) if RTTI is enabled. 1619 CharUnits AddressPoint = 1620 getContext().getLangOpts().RTTIData 1621 ? getContext().toCharUnitsFromBits( 1622 getContext().getTargetInfo().getPointerWidth(0)) 1623 : CharUnits::Zero(); 1624 1625 if (Info.PathToIntroducingObject.empty()) { 1626 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD); 1627 return; 1628 } 1629 1630 // Add a bitset entry for the least derived base belonging to this vftable. 1631 CGM.AddVTableTypeMetadata(VTable, AddressPoint, 1632 Info.PathToIntroducingObject.back()); 1633 1634 // Add a bitset entry for each derived class that is laid out at the same 1635 // offset as the least derived base. 1636 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) { 1637 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1]; 1638 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I]; 1639 1640 const ASTRecordLayout &Layout = 1641 getContext().getASTRecordLayout(DerivedRD); 1642 CharUnits Offset; 1643 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD); 1644 if (VBI == Layout.getVBaseOffsetsMap().end()) 1645 Offset = Layout.getBaseClassOffset(BaseRD); 1646 else 1647 Offset = VBI->second.VBaseOffset; 1648 if (!Offset.isZero()) 1649 return; 1650 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD); 1651 } 1652 1653 // Finally do the same for the most derived class. 1654 if (Info.FullOffsetInMDC.isZero()) 1655 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD); 1656 } 1657 1658 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1659 const CXXRecordDecl *RD) { 1660 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 1661 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD); 1662 1663 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) { 1664 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC); 1665 if (VTable->hasInitializer()) 1666 continue; 1667 1668 const VTableLayout &VTLayout = 1669 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC); 1670 1671 llvm::Constant *RTTI = nullptr; 1672 if (any_of(VTLayout.vtable_components(), 1673 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); })) 1674 RTTI = getMSCompleteObjectLocator(RD, *Info); 1675 1676 ConstantInitBuilder Builder(CGM); 1677 auto Components = Builder.beginStruct(); 1678 CGVT.createVTableInitializer(Components, VTLayout, RTTI); 1679 Components.finishAndSetAsInitializer(VTable); 1680 1681 emitVTableTypeMetadata(*Info, RD, VTable); 1682 } 1683 } 1684 1685 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField( 1686 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) { 1687 return Vptr.NearestVBase != nullptr; 1688 } 1689 1690 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor( 1691 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1692 const CXXRecordDecl *NearestVBase) { 1693 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass); 1694 if (!VTableAddressPoint) { 1695 assert(Base.getBase()->getNumVBases() && 1696 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr()); 1697 } 1698 return VTableAddressPoint; 1699 } 1700 1701 static void mangleVFTableName(MicrosoftMangleContext &MangleContext, 1702 const CXXRecordDecl *RD, const VPtrInfo &VFPtr, 1703 SmallString<256> &Name) { 1704 llvm::raw_svector_ostream Out(Name); 1705 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out); 1706 } 1707 1708 llvm::Constant * 1709 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base, 1710 const CXXRecordDecl *VTableClass) { 1711 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset()); 1712 VFTableIdTy ID(VTableClass, Base.getBaseOffset()); 1713 return VFTablesMap[ID]; 1714 } 1715 1716 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr( 1717 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1718 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass); 1719 assert(VFTable && "Couldn't find a vftable for the given base?"); 1720 return VFTable; 1721 } 1722 1723 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1724 CharUnits VPtrOffset) { 1725 // getAddrOfVTable may return 0 if asked to get an address of a vtable which 1726 // shouldn't be used in the given record type. We want to cache this result in 1727 // VFTablesMap, thus a simple zero check is not sufficient. 1728 1729 VFTableIdTy ID(RD, VPtrOffset); 1730 VTablesMapTy::iterator I; 1731 bool Inserted; 1732 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr)); 1733 if (!Inserted) 1734 return I->second; 1735 1736 llvm::GlobalVariable *&VTable = I->second; 1737 1738 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 1739 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD); 1740 1741 if (DeferredVFTables.insert(RD).second) { 1742 // We haven't processed this record type before. 1743 // Queue up this vtable for possible deferred emission. 1744 CGM.addDeferredVTable(RD); 1745 1746 #ifndef NDEBUG 1747 // Create all the vftables at once in order to make sure each vftable has 1748 // a unique mangled name. 1749 llvm::StringSet<> ObservedMangledNames; 1750 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 1751 SmallString<256> Name; 1752 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name); 1753 if (!ObservedMangledNames.insert(Name.str()).second) 1754 llvm_unreachable("Already saw this mangling before?"); 1755 } 1756 #endif 1757 } 1758 1759 const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if( 1760 VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) { 1761 return VPI->FullOffsetInMDC == VPtrOffset; 1762 }); 1763 if (VFPtrI == VFPtrs.end()) { 1764 VFTablesMap[ID] = nullptr; 1765 return nullptr; 1766 } 1767 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI; 1768 1769 SmallString<256> VFTableName; 1770 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName); 1771 1772 // Classes marked __declspec(dllimport) need vftables generated on the 1773 // import-side in order to support features like constexpr. No other 1774 // translation unit relies on the emission of the local vftable, translation 1775 // units are expected to generate them as needed. 1776 // 1777 // Because of this unique behavior, we maintain this logic here instead of 1778 // getVTableLinkage. 1779 llvm::GlobalValue::LinkageTypes VFTableLinkage = 1780 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage 1781 : CGM.getVTableLinkage(RD); 1782 bool VFTableComesFromAnotherTU = 1783 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) || 1784 llvm::GlobalValue::isExternalLinkage(VFTableLinkage); 1785 bool VTableAliasIsRequred = 1786 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData; 1787 1788 if (llvm::GlobalValue *VFTable = 1789 CGM.getModule().getNamedGlobal(VFTableName)) { 1790 VFTablesMap[ID] = VFTable; 1791 VTable = VTableAliasIsRequred 1792 ? cast<llvm::GlobalVariable>( 1793 cast<llvm::GlobalAlias>(VFTable)->getBaseObject()) 1794 : cast<llvm::GlobalVariable>(VFTable); 1795 return VTable; 1796 } 1797 1798 const VTableLayout &VTLayout = 1799 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC); 1800 llvm::GlobalValue::LinkageTypes VTableLinkage = 1801 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage; 1802 1803 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str(); 1804 1805 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout); 1806 1807 // Create a backing variable for the contents of VTable. The VTable may 1808 // or may not include space for a pointer to RTTI data. 1809 llvm::GlobalValue *VFTable; 1810 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType, 1811 /*isConstant=*/true, VTableLinkage, 1812 /*Initializer=*/nullptr, VTableName); 1813 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1814 1815 llvm::Comdat *C = nullptr; 1816 if (!VFTableComesFromAnotherTU && 1817 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) || 1818 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) && 1819 VTableAliasIsRequred))) 1820 C = CGM.getModule().getOrInsertComdat(VFTableName.str()); 1821 1822 // Only insert a pointer into the VFTable for RTTI data if we are not 1823 // importing it. We never reference the RTTI data directly so there is no 1824 // need to make room for it. 1825 if (VTableAliasIsRequred) { 1826 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0), 1827 llvm::ConstantInt::get(CGM.Int32Ty, 0), 1828 llvm::ConstantInt::get(CGM.Int32Ty, 1)}; 1829 // Create a GEP which points just after the first entry in the VFTable, 1830 // this should be the location of the first virtual method. 1831 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr( 1832 VTable->getValueType(), VTable, GEPIndices); 1833 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) { 1834 VFTableLinkage = llvm::GlobalValue::ExternalLinkage; 1835 if (C) 1836 C->setSelectionKind(llvm::Comdat::Largest); 1837 } 1838 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy, 1839 /*AddressSpace=*/0, VFTableLinkage, 1840 VFTableName.str(), VTableGEP, 1841 &CGM.getModule()); 1842 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1843 } else { 1844 // We don't need a GlobalAlias to be a symbol for the VTable if we won't 1845 // be referencing any RTTI data. 1846 // The GlobalVariable will end up being an appropriate definition of the 1847 // VFTable. 1848 VFTable = VTable; 1849 } 1850 if (C) 1851 VTable->setComdat(C); 1852 1853 if (RD->hasAttr<DLLExportAttr>()) 1854 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1855 1856 VFTablesMap[ID] = VFTable; 1857 return VTable; 1858 } 1859 1860 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1861 GlobalDecl GD, 1862 Address This, 1863 llvm::Type *Ty, 1864 SourceLocation Loc) { 1865 CGBuilderTy &Builder = CGF.Builder; 1866 1867 Ty = Ty->getPointerTo()->getPointerTo(); 1868 Address VPtr = 1869 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1870 1871 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl()); 1872 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent()); 1873 1874 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 1875 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD); 1876 1877 // Compute the identity of the most derived class whose virtual table is 1878 // located at the MethodVFTableLocation ML. 1879 auto getObjectWithVPtr = [&] { 1880 return llvm::find_if(VFTContext.getVFPtrOffsets( 1881 ML.VBase ? ML.VBase : MethodDecl->getParent()), 1882 [&](const std::unique_ptr<VPtrInfo> &Info) { 1883 return Info->FullOffsetInMDC == ML.VFPtrOffset; 1884 }) 1885 ->get() 1886 ->ObjectWithVPtr; 1887 }; 1888 1889 llvm::Value *VFunc; 1890 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) { 1891 VFunc = CGF.EmitVTableTypeCheckedLoad( 1892 getObjectWithVPtr(), VTable, 1893 ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8); 1894 } else { 1895 if (CGM.getCodeGenOpts().PrepareForLTO) 1896 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc); 1897 1898 llvm::Value *VFuncPtr = 1899 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1900 VFunc = Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); 1901 } 1902 1903 CGCallee Callee(GD, VFunc); 1904 return Callee; 1905 } 1906 1907 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall( 1908 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, 1909 Address This, DeleteOrMemberCallExpr E) { 1910 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>(); 1911 auto *D = E.dyn_cast<const CXXDeleteExpr *>(); 1912 assert((CE != nullptr) ^ (D != nullptr)); 1913 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1914 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1915 1916 // We have only one destructor in the vftable but can get both behaviors 1917 // by passing an implicit int parameter. 1918 GlobalDecl GD(Dtor, Dtor_Deleting); 1919 const CGFunctionInfo *FInfo = 1920 &CGM.getTypes().arrangeCXXStructorDeclaration(GD); 1921 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1922 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty); 1923 1924 ASTContext &Context = getContext(); 1925 llvm::Value *ImplicitParam = llvm::ConstantInt::get( 1926 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 1927 DtorType == Dtor_Deleting); 1928 1929 QualType ThisTy; 1930 if (CE) { 1931 ThisTy = CE->getObjectType(); 1932 } else { 1933 ThisTy = D->getDestroyedType(); 1934 } 1935 1936 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1937 RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, 1938 ImplicitParam, Context.IntTy, CE); 1939 return RV.getScalarVal(); 1940 } 1941 1942 const VBTableGlobals & 1943 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 1944 // At this layer, we can key the cache off of a single class, which is much 1945 // easier than caching each vbtable individually. 1946 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 1947 bool Added; 1948 std::tie(Entry, Added) = 1949 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals())); 1950 VBTableGlobals &VBGlobals = Entry->second; 1951 if (!Added) 1952 return VBGlobals; 1953 1954 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1955 VBGlobals.VBTables = &Context.enumerateVBTables(RD); 1956 1957 // Cache the globals for all vbtables so we don't have to recompute the 1958 // mangled names. 1959 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1960 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(), 1961 E = VBGlobals.VBTables->end(); 1962 I != E; ++I) { 1963 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage)); 1964 } 1965 1966 return VBGlobals; 1967 } 1968 1969 llvm::Function * 1970 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD, 1971 const MethodVFTableLocation &ML) { 1972 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) && 1973 "can't form pointers to ctors or virtual dtors"); 1974 1975 // Calculate the mangled name. 1976 SmallString<256> ThunkName; 1977 llvm::raw_svector_ostream Out(ThunkName); 1978 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out); 1979 1980 // If the thunk has been generated previously, just return it. 1981 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 1982 return cast<llvm::Function>(GV); 1983 1984 // Create the llvm::Function. 1985 const CGFunctionInfo &FnInfo = 1986 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD); 1987 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 1988 llvm::Function *ThunkFn = 1989 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 1990 ThunkName.str(), &CGM.getModule()); 1991 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 1992 1993 ThunkFn->setLinkage(MD->isExternallyVisible() 1994 ? llvm::GlobalValue::LinkOnceODRLinkage 1995 : llvm::GlobalValue::InternalLinkage); 1996 if (MD->isExternallyVisible()) 1997 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName())); 1998 1999 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 2000 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 2001 2002 // Add the "thunk" attribute so that LLVM knows that the return type is 2003 // meaningless. These thunks can be used to call functions with differing 2004 // return types, and the caller is required to cast the prototype 2005 // appropriately to extract the correct value. 2006 ThunkFn->addFnAttr("thunk"); 2007 2008 // These thunks can be compared, so they are not unnamed. 2009 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None); 2010 2011 // Start codegen. 2012 CodeGenFunction CGF(CGM); 2013 CGF.CurGD = GlobalDecl(MD); 2014 CGF.CurFuncIsThunk = true; 2015 2016 // Build FunctionArgs, but only include the implicit 'this' parameter 2017 // declaration. 2018 FunctionArgList FunctionArgs; 2019 buildThisParam(CGF, FunctionArgs); 2020 2021 // Start defining the function. 2022 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo, 2023 FunctionArgs, MD->getLocation(), SourceLocation()); 2024 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF)); 2025 2026 // Load the vfptr and then callee from the vftable. The callee should have 2027 // adjusted 'this' so that the vfptr is at offset zero. 2028 llvm::Value *VTable = CGF.GetVTablePtr( 2029 getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent()); 2030 2031 llvm::Value *VFuncPtr = 2032 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 2033 llvm::Value *Callee = 2034 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); 2035 2036 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee}); 2037 2038 return ThunkFn; 2039 } 2040 2041 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 2042 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 2043 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 2044 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I]; 2045 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 2046 if (GV->isDeclaration()) 2047 emitVBTableDefinition(*VBT, RD, GV); 2048 } 2049 } 2050 2051 llvm::GlobalVariable * 2052 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 2053 llvm::GlobalVariable::LinkageTypes Linkage) { 2054 SmallString<256> OutName; 2055 llvm::raw_svector_ostream Out(OutName); 2056 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out); 2057 StringRef Name = OutName.str(); 2058 2059 llvm::ArrayType *VBTableType = 2060 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases()); 2061 2062 assert(!CGM.getModule().getNamedGlobal(Name) && 2063 "vbtable with this name already exists: mangling bug?"); 2064 CharUnits Alignment = 2065 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy); 2066 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable( 2067 Name, VBTableType, Linkage, Alignment.getQuantity()); 2068 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2069 2070 if (RD->hasAttr<DLLImportAttr>()) 2071 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 2072 else if (RD->hasAttr<DLLExportAttr>()) 2073 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2074 2075 if (!GV->hasExternalLinkage()) 2076 emitVBTableDefinition(VBT, RD, GV); 2077 2078 return GV; 2079 } 2080 2081 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT, 2082 const CXXRecordDecl *RD, 2083 llvm::GlobalVariable *GV) const { 2084 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr; 2085 2086 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() && 2087 "should only emit vbtables for classes with vbtables"); 2088 2089 const ASTRecordLayout &BaseLayout = 2090 getContext().getASTRecordLayout(VBT.IntroducingObject); 2091 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD); 2092 2093 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(), 2094 nullptr); 2095 2096 // The offset from ObjectWithVPtr's vbptr to itself always leads. 2097 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 2098 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 2099 2100 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 2101 for (const auto &I : ObjectWithVPtr->vbases()) { 2102 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl(); 2103 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 2104 assert(!Offset.isNegative()); 2105 2106 // Make it relative to the subobject vbptr. 2107 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 2108 if (VBT.getVBaseWithVPtr()) 2109 CompleteVBPtrOffset += 2110 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr()); 2111 Offset -= CompleteVBPtrOffset; 2112 2113 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase); 2114 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?"); 2115 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 2116 } 2117 2118 assert(Offsets.size() == 2119 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 2120 ->getElementType())->getNumElements()); 2121 llvm::ArrayType *VBTableType = 2122 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 2123 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 2124 GV->setInitializer(Init); 2125 2126 if (RD->hasAttr<DLLImportAttr>()) 2127 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage); 2128 } 2129 2130 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 2131 Address This, 2132 const ThisAdjustment &TA) { 2133 if (TA.isEmpty()) 2134 return This.getPointer(); 2135 2136 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty); 2137 2138 llvm::Value *V; 2139 if (TA.Virtual.isEmpty()) { 2140 V = This.getPointer(); 2141 } else { 2142 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 2143 // Adjust the this argument based on the vtordisp value. 2144 Address VtorDispPtr = 2145 CGF.Builder.CreateConstInBoundsByteGEP(This, 2146 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset)); 2147 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty); 2148 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 2149 V = CGF.Builder.CreateGEP(This.getPointer(), 2150 CGF.Builder.CreateNeg(VtorDisp)); 2151 2152 // Unfortunately, having applied the vtordisp means that we no 2153 // longer really have a known alignment for the vbptr step. 2154 // We'll assume the vbptr is pointer-aligned. 2155 2156 if (TA.Virtual.Microsoft.VBPtrOffset) { 2157 // If the final overrider is defined in a virtual base other than the one 2158 // that holds the vfptr, we have to use a vtordispex thunk which looks up 2159 // the vbtable of the derived class. 2160 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 2161 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 2162 llvm::Value *VBPtr; 2163 llvm::Value *VBaseOffset = 2164 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()), 2165 -TA.Virtual.Microsoft.VBPtrOffset, 2166 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 2167 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 2168 } 2169 } 2170 2171 if (TA.NonVirtual) { 2172 // Non-virtual adjustment might result in a pointer outside the allocated 2173 // object, e.g. if the final overrider class is laid out after the virtual 2174 // base that declares a method in the most derived class. 2175 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 2176 } 2177 2178 // Don't need to bitcast back, the call CodeGen will handle this. 2179 return V; 2180 } 2181 2182 llvm::Value * 2183 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 2184 const ReturnAdjustment &RA) { 2185 if (RA.isEmpty()) 2186 return Ret.getPointer(); 2187 2188 auto OrigTy = Ret.getType(); 2189 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty); 2190 2191 llvm::Value *V = Ret.getPointer(); 2192 if (RA.Virtual.Microsoft.VBIndex) { 2193 assert(RA.Virtual.Microsoft.VBIndex > 0); 2194 int32_t IntSize = CGF.getIntSize().getQuantity(); 2195 llvm::Value *VBPtr; 2196 llvm::Value *VBaseOffset = 2197 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset, 2198 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 2199 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 2200 } 2201 2202 if (RA.NonVirtual) 2203 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual); 2204 2205 // Cast back to the original type. 2206 return CGF.Builder.CreateBitCast(V, OrigTy); 2207 } 2208 2209 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 2210 QualType elementType) { 2211 // Microsoft seems to completely ignore the possibility of a 2212 // two-argument usual deallocation function. 2213 return elementType.isDestructedType(); 2214 } 2215 2216 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 2217 // Microsoft seems to completely ignore the possibility of a 2218 // two-argument usual deallocation function. 2219 return expr->getAllocatedType().isDestructedType(); 2220 } 2221 2222 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 2223 // The array cookie is always a size_t; we then pad that out to the 2224 // alignment of the element type. 2225 ASTContext &Ctx = getContext(); 2226 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 2227 Ctx.getTypeAlignInChars(type)); 2228 } 2229 2230 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 2231 Address allocPtr, 2232 CharUnits cookieSize) { 2233 Address numElementsPtr = 2234 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy); 2235 return CGF.Builder.CreateLoad(numElementsPtr); 2236 } 2237 2238 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 2239 Address newPtr, 2240 llvm::Value *numElements, 2241 const CXXNewExpr *expr, 2242 QualType elementType) { 2243 assert(requiresArrayCookie(expr)); 2244 2245 // The size of the cookie. 2246 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 2247 2248 // Compute an offset to the cookie. 2249 Address cookiePtr = newPtr; 2250 2251 // Write the number of elements into the appropriate slot. 2252 Address numElementsPtr 2253 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy); 2254 CGF.Builder.CreateStore(numElements, numElementsPtr); 2255 2256 // Finally, compute a pointer to the actual data buffer by skipping 2257 // over the cookie completely. 2258 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize); 2259 } 2260 2261 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD, 2262 llvm::FunctionCallee Dtor, 2263 llvm::Constant *Addr) { 2264 // Create a function which calls the destructor. 2265 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr); 2266 2267 // extern "C" int __tlregdtor(void (*f)(void)); 2268 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get( 2269 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false); 2270 2271 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction( 2272 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true); 2273 if (llvm::Function *TLRegDtorFn = 2274 dyn_cast<llvm::Function>(TLRegDtor.getCallee())) 2275 TLRegDtorFn->setDoesNotThrow(); 2276 2277 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub); 2278 } 2279 2280 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 2281 llvm::FunctionCallee Dtor, 2282 llvm::Constant *Addr) { 2283 if (D.isNoDestroy(CGM.getContext())) 2284 return; 2285 2286 if (D.getTLSKind()) 2287 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr); 2288 2289 // The default behavior is to use atexit. 2290 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr); 2291 } 2292 2293 void MicrosoftCXXABI::EmitThreadLocalInitFuncs( 2294 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals, 2295 ArrayRef<llvm::Function *> CXXThreadLocalInits, 2296 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) { 2297 if (CXXThreadLocalInits.empty()) 2298 return; 2299 2300 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() == 2301 llvm::Triple::x86 2302 ? "/include:___dyn_tls_init@12" 2303 : "/include:__dyn_tls_init"); 2304 2305 // This will create a GV in the .CRT$XDU section. It will point to our 2306 // initialization function. The CRT will call all of these function 2307 // pointers at start-up time and, eventually, at thread-creation time. 2308 auto AddToXDU = [&CGM](llvm::Function *InitFunc) { 2309 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable( 2310 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true, 2311 llvm::GlobalVariable::InternalLinkage, InitFunc, 2312 Twine(InitFunc->getName(), "$initializer$")); 2313 InitFuncPtr->setSection(".CRT$XDU"); 2314 // This variable has discardable linkage, we have to add it to @llvm.used to 2315 // ensure it won't get discarded. 2316 CGM.addUsedGlobal(InitFuncPtr); 2317 return InitFuncPtr; 2318 }; 2319 2320 std::vector<llvm::Function *> NonComdatInits; 2321 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) { 2322 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>( 2323 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I]))); 2324 llvm::Function *F = CXXThreadLocalInits[I]; 2325 2326 // If the GV is already in a comdat group, then we have to join it. 2327 if (llvm::Comdat *C = GV->getComdat()) 2328 AddToXDU(F)->setComdat(C); 2329 else 2330 NonComdatInits.push_back(F); 2331 } 2332 2333 if (!NonComdatInits.empty()) { 2334 llvm::FunctionType *FTy = 2335 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 2336 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction( 2337 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(), 2338 SourceLocation(), /*TLS=*/true); 2339 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits); 2340 2341 AddToXDU(InitFunc); 2342 } 2343 } 2344 2345 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2346 const VarDecl *VD, 2347 QualType LValType) { 2348 CGF.CGM.ErrorUnsupported(VD, "thread wrappers"); 2349 return LValue(); 2350 } 2351 2352 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) { 2353 StringRef VarName("_Init_thread_epoch"); 2354 CharUnits Align = CGM.getIntAlign(); 2355 if (auto *GV = CGM.getModule().getNamedGlobal(VarName)) 2356 return ConstantAddress(GV, Align); 2357 auto *GV = new llvm::GlobalVariable( 2358 CGM.getModule(), CGM.IntTy, 2359 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage, 2360 /*Initializer=*/nullptr, VarName, 2361 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel); 2362 GV->setAlignment(Align.getAsAlign()); 2363 return ConstantAddress(GV, Align); 2364 } 2365 2366 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) { 2367 llvm::FunctionType *FTy = 2368 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2369 CGM.IntTy->getPointerTo(), /*isVarArg=*/false); 2370 return CGM.CreateRuntimeFunction( 2371 FTy, "_Init_thread_header", 2372 llvm::AttributeList::get(CGM.getLLVMContext(), 2373 llvm::AttributeList::FunctionIndex, 2374 llvm::Attribute::NoUnwind), 2375 /*Local=*/true); 2376 } 2377 2378 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) { 2379 llvm::FunctionType *FTy = 2380 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2381 CGM.IntTy->getPointerTo(), /*isVarArg=*/false); 2382 return CGM.CreateRuntimeFunction( 2383 FTy, "_Init_thread_footer", 2384 llvm::AttributeList::get(CGM.getLLVMContext(), 2385 llvm::AttributeList::FunctionIndex, 2386 llvm::Attribute::NoUnwind), 2387 /*Local=*/true); 2388 } 2389 2390 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) { 2391 llvm::FunctionType *FTy = 2392 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 2393 CGM.IntTy->getPointerTo(), /*isVarArg=*/false); 2394 return CGM.CreateRuntimeFunction( 2395 FTy, "_Init_thread_abort", 2396 llvm::AttributeList::get(CGM.getLLVMContext(), 2397 llvm::AttributeList::FunctionIndex, 2398 llvm::Attribute::NoUnwind), 2399 /*Local=*/true); 2400 } 2401 2402 namespace { 2403 struct ResetGuardBit final : EHScopeStack::Cleanup { 2404 Address Guard; 2405 unsigned GuardNum; 2406 ResetGuardBit(Address Guard, unsigned GuardNum) 2407 : Guard(Guard), GuardNum(GuardNum) {} 2408 2409 void Emit(CodeGenFunction &CGF, Flags flags) override { 2410 // Reset the bit in the mask so that the static variable may be 2411 // reinitialized. 2412 CGBuilderTy &Builder = CGF.Builder; 2413 llvm::LoadInst *LI = Builder.CreateLoad(Guard); 2414 llvm::ConstantInt *Mask = 2415 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum)); 2416 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard); 2417 } 2418 }; 2419 2420 struct CallInitThreadAbort final : EHScopeStack::Cleanup { 2421 llvm::Value *Guard; 2422 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {} 2423 2424 void Emit(CodeGenFunction &CGF, Flags flags) override { 2425 // Calling _Init_thread_abort will reset the guard's state. 2426 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard); 2427 } 2428 }; 2429 } 2430 2431 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 2432 llvm::GlobalVariable *GV, 2433 bool PerformInit) { 2434 // MSVC only uses guards for static locals. 2435 if (!D.isStaticLocal()) { 2436 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()); 2437 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr. 2438 llvm::Function *F = CGF.CurFn; 2439 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 2440 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName())); 2441 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 2442 return; 2443 } 2444 2445 bool ThreadlocalStatic = D.getTLSKind(); 2446 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics; 2447 2448 // Thread-safe static variables which aren't thread-specific have a 2449 // per-variable guard. 2450 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic; 2451 2452 CGBuilderTy &Builder = CGF.Builder; 2453 llvm::IntegerType *GuardTy = CGF.Int32Ty; 2454 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 2455 CharUnits GuardAlign = CharUnits::fromQuantity(4); 2456 2457 // Get the guard variable for this function if we have one already. 2458 GuardInfo *GI = nullptr; 2459 if (ThreadlocalStatic) 2460 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()]; 2461 else if (!ThreadsafeStatic) 2462 GI = &GuardVariableMap[D.getDeclContext()]; 2463 2464 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr; 2465 unsigned GuardNum; 2466 if (D.isExternallyVisible()) { 2467 // Externally visible variables have to be numbered in Sema to properly 2468 // handle unreachable VarDecls. 2469 GuardNum = getContext().getStaticLocalNumber(&D); 2470 assert(GuardNum > 0); 2471 GuardNum--; 2472 } else if (HasPerVariableGuard) { 2473 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++; 2474 } else { 2475 // Non-externally visible variables are numbered here in CodeGen. 2476 GuardNum = GI->BitIndex++; 2477 } 2478 2479 if (!HasPerVariableGuard && GuardNum >= 32) { 2480 if (D.isExternallyVisible()) 2481 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 2482 GuardNum %= 32; 2483 GuardVar = nullptr; 2484 } 2485 2486 if (!GuardVar) { 2487 // Mangle the name for the guard. 2488 SmallString<256> GuardName; 2489 { 2490 llvm::raw_svector_ostream Out(GuardName); 2491 if (HasPerVariableGuard) 2492 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum, 2493 Out); 2494 else 2495 getMangleContext().mangleStaticGuardVariable(&D, Out); 2496 } 2497 2498 // Create the guard variable with a zero-initializer. Just absorb linkage, 2499 // visibility and dll storage class from the guarded variable. 2500 GuardVar = 2501 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false, 2502 GV->getLinkage(), Zero, GuardName.str()); 2503 GuardVar->setVisibility(GV->getVisibility()); 2504 GuardVar->setDLLStorageClass(GV->getDLLStorageClass()); 2505 GuardVar->setAlignment(GuardAlign.getAsAlign()); 2506 if (GuardVar->isWeakForLinker()) 2507 GuardVar->setComdat( 2508 CGM.getModule().getOrInsertComdat(GuardVar->getName())); 2509 if (D.getTLSKind()) 2510 GuardVar->setThreadLocal(true); 2511 if (GI && !HasPerVariableGuard) 2512 GI->Guard = GuardVar; 2513 } 2514 2515 ConstantAddress GuardAddr(GuardVar, GuardAlign); 2516 2517 assert(GuardVar->getLinkage() == GV->getLinkage() && 2518 "static local from the same function had different linkage"); 2519 2520 if (!HasPerVariableGuard) { 2521 // Pseudo code for the test: 2522 // if (!(GuardVar & MyGuardBit)) { 2523 // GuardVar |= MyGuardBit; 2524 // ... initialize the object ...; 2525 // } 2526 2527 // Test our bit from the guard variable. 2528 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum); 2529 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr); 2530 llvm::Value *NeedsInit = 2531 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero); 2532 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 2533 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 2534 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock, 2535 CodeGenFunction::GuardKind::VariableGuard, &D); 2536 2537 // Set our bit in the guard variable and emit the initializer and add a global 2538 // destructor if appropriate. 2539 CGF.EmitBlock(InitBlock); 2540 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr); 2541 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum); 2542 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 2543 CGF.PopCleanupBlock(); 2544 Builder.CreateBr(EndBlock); 2545 2546 // Continue. 2547 CGF.EmitBlock(EndBlock); 2548 } else { 2549 // Pseudo code for the test: 2550 // if (TSS > _Init_thread_epoch) { 2551 // _Init_thread_header(&TSS); 2552 // if (TSS == -1) { 2553 // ... initialize the object ...; 2554 // _Init_thread_footer(&TSS); 2555 // } 2556 // } 2557 // 2558 // The algorithm is almost identical to what can be found in the appendix 2559 // found in N2325. 2560 2561 // This BasicBLock determines whether or not we have any work to do. 2562 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr); 2563 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered); 2564 llvm::LoadInst *InitThreadEpoch = 2565 Builder.CreateLoad(getInitThreadEpochPtr(CGM)); 2566 llvm::Value *IsUninitialized = 2567 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch); 2568 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt"); 2569 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 2570 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock, 2571 CodeGenFunction::GuardKind::VariableGuard, &D); 2572 2573 // This BasicBlock attempts to determine whether or not this thread is 2574 // responsible for doing the initialization. 2575 CGF.EmitBlock(AttemptInitBlock); 2576 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM), 2577 GuardAddr.getPointer()); 2578 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr); 2579 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered); 2580 llvm::Value *ShouldDoInit = 2581 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt()); 2582 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 2583 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock); 2584 2585 // Ok, we ended up getting selected as the initializing thread. 2586 CGF.EmitBlock(InitBlock); 2587 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr); 2588 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 2589 CGF.PopCleanupBlock(); 2590 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM), 2591 GuardAddr.getPointer()); 2592 Builder.CreateBr(EndBlock); 2593 2594 CGF.EmitBlock(EndBlock); 2595 } 2596 } 2597 2598 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 2599 // Null-ness for function memptrs only depends on the first field, which is 2600 // the function pointer. The rest don't matter, so we can zero initialize. 2601 if (MPT->isMemberFunctionPointer()) 2602 return true; 2603 2604 // The virtual base adjustment field is always -1 for null, so if we have one 2605 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 2606 // valid field offset. 2607 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2608 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2609 return (!inheritanceModelHasVBTableOffsetField(Inheritance) && 2610 RD->nullFieldOffsetIsZero()); 2611 } 2612 2613 llvm::Type * 2614 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 2615 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2616 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2617 llvm::SmallVector<llvm::Type *, 4> fields; 2618 if (MPT->isMemberFunctionPointer()) 2619 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 2620 else 2621 fields.push_back(CGM.IntTy); // FieldOffset 2622 2623 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(), 2624 Inheritance)) 2625 fields.push_back(CGM.IntTy); 2626 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 2627 fields.push_back(CGM.IntTy); 2628 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 2629 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 2630 2631 if (fields.size() == 1) 2632 return fields[0]; 2633 return llvm::StructType::get(CGM.getLLVMContext(), fields); 2634 } 2635 2636 void MicrosoftCXXABI:: 2637 GetNullMemberPointerFields(const MemberPointerType *MPT, 2638 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 2639 assert(fields.empty()); 2640 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2641 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2642 if (MPT->isMemberFunctionPointer()) { 2643 // FunctionPointerOrVirtualThunk 2644 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 2645 } else { 2646 if (RD->nullFieldOffsetIsZero()) 2647 fields.push_back(getZeroInt()); // FieldOffset 2648 else 2649 fields.push_back(getAllOnesInt()); // FieldOffset 2650 } 2651 2652 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(), 2653 Inheritance)) 2654 fields.push_back(getZeroInt()); 2655 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 2656 fields.push_back(getZeroInt()); 2657 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 2658 fields.push_back(getAllOnesInt()); 2659 } 2660 2661 llvm::Constant * 2662 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 2663 llvm::SmallVector<llvm::Constant *, 4> fields; 2664 GetNullMemberPointerFields(MPT, fields); 2665 if (fields.size() == 1) 2666 return fields[0]; 2667 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 2668 assert(Res->getType() == ConvertMemberPointerType(MPT)); 2669 return Res; 2670 } 2671 2672 llvm::Constant * 2673 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 2674 bool IsMemberFunction, 2675 const CXXRecordDecl *RD, 2676 CharUnits NonVirtualBaseAdjustment, 2677 unsigned VBTableIndex) { 2678 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2679 2680 // Single inheritance class member pointer are represented as scalars instead 2681 // of aggregates. 2682 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance)) 2683 return FirstField; 2684 2685 llvm::SmallVector<llvm::Constant *, 4> fields; 2686 fields.push_back(FirstField); 2687 2688 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance)) 2689 fields.push_back(llvm::ConstantInt::get( 2690 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 2691 2692 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) { 2693 CharUnits Offs = CharUnits::Zero(); 2694 if (VBTableIndex) 2695 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 2696 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 2697 } 2698 2699 // The rest of the fields are adjusted by conversions to a more derived class. 2700 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 2701 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex)); 2702 2703 return llvm::ConstantStruct::getAnon(fields); 2704 } 2705 2706 llvm::Constant * 2707 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 2708 CharUnits offset) { 2709 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset); 2710 } 2711 2712 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD, 2713 CharUnits offset) { 2714 if (RD->getMSInheritanceModel() == 2715 MSInheritanceModel::Virtual) 2716 offset -= getContext().getOffsetOfBaseWithVBPtr(RD); 2717 llvm::Constant *FirstField = 2718 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 2719 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 2720 CharUnits::Zero(), /*VBTableIndex=*/0); 2721 } 2722 2723 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 2724 QualType MPType) { 2725 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>(); 2726 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2727 if (!MPD) 2728 return EmitNullMemberPointer(DstTy); 2729 2730 ASTContext &Ctx = getContext(); 2731 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath(); 2732 2733 llvm::Constant *C; 2734 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) { 2735 C = EmitMemberFunctionPointer(MD); 2736 } else { 2737 // For a pointer to data member, start off with the offset of the field in 2738 // the class in which it was declared, and convert from there if necessary. 2739 // For indirect field decls, get the outermost anonymous field and use the 2740 // parent class. 2741 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD)); 2742 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD); 2743 if (!FD) 2744 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin()); 2745 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent()); 2746 RD = RD->getMostRecentNonInjectedDecl(); 2747 C = EmitMemberDataPointer(RD, FieldOffset); 2748 } 2749 2750 if (!MemberPointerPath.empty()) { 2751 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2752 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr(); 2753 const MemberPointerType *SrcTy = 2754 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy) 2755 ->castAs<MemberPointerType>(); 2756 2757 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2758 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath; 2759 const CXXRecordDecl *PrevRD = SrcRD; 2760 for (const CXXRecordDecl *PathElem : MemberPointerPath) { 2761 const CXXRecordDecl *Base = nullptr; 2762 const CXXRecordDecl *Derived = nullptr; 2763 if (DerivedMember) { 2764 Base = PathElem; 2765 Derived = PrevRD; 2766 } else { 2767 Base = PrevRD; 2768 Derived = PathElem; 2769 } 2770 for (const CXXBaseSpecifier &BS : Derived->bases()) 2771 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == 2772 Base->getCanonicalDecl()) 2773 DerivedToBasePath.push_back(&BS); 2774 PrevRD = PathElem; 2775 } 2776 assert(DerivedToBasePath.size() == MemberPointerPath.size()); 2777 2778 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer 2779 : CK_BaseToDerivedMemberPointer; 2780 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(), 2781 DerivedToBasePath.end(), C); 2782 } 2783 return C; 2784 } 2785 2786 llvm::Constant * 2787 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) { 2788 assert(MD->isInstance() && "Member function must not be static!"); 2789 2790 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero(); 2791 const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl(); 2792 CodeGenTypes &Types = CGM.getTypes(); 2793 2794 unsigned VBTableIndex = 0; 2795 llvm::Constant *FirstField; 2796 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 2797 if (!MD->isVirtual()) { 2798 llvm::Type *Ty; 2799 // Check whether the function has a computable LLVM signature. 2800 if (Types.isFuncTypeConvertible(FPT)) { 2801 // The function has a computable LLVM signature; use the correct type. 2802 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 2803 } else { 2804 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 2805 // function type is incomplete. 2806 Ty = CGM.PtrDiffTy; 2807 } 2808 FirstField = CGM.GetAddrOfFunction(MD, Ty); 2809 } else { 2810 auto &VTableContext = CGM.getMicrosoftVTableContext(); 2811 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD); 2812 FirstField = EmitVirtualMemPtrThunk(MD, ML); 2813 // Include the vfptr adjustment if the method is in a non-primary vftable. 2814 NonVirtualBaseAdjustment += ML.VFPtrOffset; 2815 if (ML.VBase) 2816 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4; 2817 } 2818 2819 if (VBTableIndex == 0 && 2820 RD->getMSInheritanceModel() == 2821 MSInheritanceModel::Virtual) 2822 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD); 2823 2824 // The rest of the fields are common with data member pointers. 2825 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 2826 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 2827 NonVirtualBaseAdjustment, VBTableIndex); 2828 } 2829 2830 /// Member pointers are the same if they're either bitwise identical *or* both 2831 /// null. Null-ness for function members is determined by the first field, 2832 /// while for data member pointers we must compare all fields. 2833 llvm::Value * 2834 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 2835 llvm::Value *L, 2836 llvm::Value *R, 2837 const MemberPointerType *MPT, 2838 bool Inequality) { 2839 CGBuilderTy &Builder = CGF.Builder; 2840 2841 // Handle != comparisons by switching the sense of all boolean operations. 2842 llvm::ICmpInst::Predicate Eq; 2843 llvm::Instruction::BinaryOps And, Or; 2844 if (Inequality) { 2845 Eq = llvm::ICmpInst::ICMP_NE; 2846 And = llvm::Instruction::Or; 2847 Or = llvm::Instruction::And; 2848 } else { 2849 Eq = llvm::ICmpInst::ICMP_EQ; 2850 And = llvm::Instruction::And; 2851 Or = llvm::Instruction::Or; 2852 } 2853 2854 // If this is a single field member pointer (single inheritance), this is a 2855 // single icmp. 2856 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2857 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 2858 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(), 2859 Inheritance)) 2860 return Builder.CreateICmp(Eq, L, R); 2861 2862 // Compare the first field. 2863 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 2864 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 2865 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 2866 2867 // Compare everything other than the first field. 2868 llvm::Value *Res = nullptr; 2869 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 2870 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 2871 llvm::Value *LF = Builder.CreateExtractValue(L, I); 2872 llvm::Value *RF = Builder.CreateExtractValue(R, I); 2873 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 2874 if (Res) 2875 Res = Builder.CreateBinOp(And, Res, Cmp); 2876 else 2877 Res = Cmp; 2878 } 2879 2880 // Check if the first field is 0 if this is a function pointer. 2881 if (MPT->isMemberFunctionPointer()) { 2882 // (l1 == r1 && ...) || l0 == 0 2883 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 2884 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 2885 Res = Builder.CreateBinOp(Or, Res, IsZero); 2886 } 2887 2888 // Combine the comparison of the first field, which must always be true for 2889 // this comparison to succeeed. 2890 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 2891 } 2892 2893 llvm::Value * 2894 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 2895 llvm::Value *MemPtr, 2896 const MemberPointerType *MPT) { 2897 CGBuilderTy &Builder = CGF.Builder; 2898 llvm::SmallVector<llvm::Constant *, 4> fields; 2899 // We only need one field for member functions. 2900 if (MPT->isMemberFunctionPointer()) 2901 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 2902 else 2903 GetNullMemberPointerFields(MPT, fields); 2904 assert(!fields.empty()); 2905 llvm::Value *FirstField = MemPtr; 2906 if (MemPtr->getType()->isStructTy()) 2907 FirstField = Builder.CreateExtractValue(MemPtr, 0); 2908 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 2909 2910 // For function member pointers, we only need to test the function pointer 2911 // field. The other fields if any can be garbage. 2912 if (MPT->isMemberFunctionPointer()) 2913 return Res; 2914 2915 // Otherwise, emit a series of compares and combine the results. 2916 for (int I = 1, E = fields.size(); I < E; ++I) { 2917 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 2918 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 2919 Res = Builder.CreateOr(Res, Next, "memptr.tobool"); 2920 } 2921 return Res; 2922 } 2923 2924 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 2925 llvm::Constant *Val) { 2926 // Function pointers are null if the pointer in the first field is null. 2927 if (MPT->isMemberFunctionPointer()) { 2928 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 2929 Val->getAggregateElement(0U) : Val; 2930 return FirstField->isNullValue(); 2931 } 2932 2933 // If it's not a function pointer and it's zero initializable, we can easily 2934 // check zero. 2935 if (isZeroInitializable(MPT) && Val->isNullValue()) 2936 return true; 2937 2938 // Otherwise, break down all the fields for comparison. Hopefully these 2939 // little Constants are reused, while a big null struct might not be. 2940 llvm::SmallVector<llvm::Constant *, 4> Fields; 2941 GetNullMemberPointerFields(MPT, Fields); 2942 if (Fields.size() == 1) { 2943 assert(Val->getType()->isIntegerTy()); 2944 return Val == Fields[0]; 2945 } 2946 2947 unsigned I, E; 2948 for (I = 0, E = Fields.size(); I != E; ++I) { 2949 if (Val->getAggregateElement(I) != Fields[I]) 2950 break; 2951 } 2952 return I == E; 2953 } 2954 2955 llvm::Value * 2956 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 2957 Address This, 2958 llvm::Value *VBPtrOffset, 2959 llvm::Value *VBTableOffset, 2960 llvm::Value **VBPtrOut) { 2961 CGBuilderTy &Builder = CGF.Builder; 2962 // Load the vbtable pointer from the vbptr in the instance. 2963 This = Builder.CreateElementBitCast(This, CGM.Int8Ty); 2964 llvm::Value *VBPtr = 2965 Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr"); 2966 if (VBPtrOut) *VBPtrOut = VBPtr; 2967 VBPtr = Builder.CreateBitCast(VBPtr, 2968 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace())); 2969 2970 CharUnits VBPtrAlign; 2971 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) { 2972 VBPtrAlign = This.getAlignment().alignmentAtOffset( 2973 CharUnits::fromQuantity(CI->getSExtValue())); 2974 } else { 2975 VBPtrAlign = CGF.getPointerAlign(); 2976 } 2977 2978 llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable"); 2979 2980 // Translate from byte offset to table index. It improves analyzability. 2981 llvm::Value *VBTableIndex = Builder.CreateAShr( 2982 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2), 2983 "vbtindex", /*isExact=*/true); 2984 2985 // Load an i32 offset from the vb-table. 2986 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex); 2987 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 2988 return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4), 2989 "vbase_offs"); 2990 } 2991 2992 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 2993 // it. 2994 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase( 2995 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD, 2996 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) { 2997 CGBuilderTy &Builder = CGF.Builder; 2998 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty); 2999 llvm::BasicBlock *OriginalBB = nullptr; 3000 llvm::BasicBlock *SkipAdjustBB = nullptr; 3001 llvm::BasicBlock *VBaseAdjustBB = nullptr; 3002 3003 // In the unspecified inheritance model, there might not be a vbtable at all, 3004 // in which case we need to skip the virtual base lookup. If there is a 3005 // vbtable, the first entry is a no-op entry that gives back the original 3006 // base, so look for a virtual base adjustment offset of zero. 3007 if (VBPtrOffset) { 3008 OriginalBB = Builder.GetInsertBlock(); 3009 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 3010 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 3011 llvm::Value *IsVirtual = 3012 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 3013 "memptr.is_vbase"); 3014 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 3015 CGF.EmitBlock(VBaseAdjustBB); 3016 } 3017 3018 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 3019 // know the vbptr offset. 3020 if (!VBPtrOffset) { 3021 CharUnits offs = CharUnits::Zero(); 3022 if (!RD->hasDefinition()) { 3023 DiagnosticsEngine &Diags = CGF.CGM.getDiags(); 3024 unsigned DiagID = Diags.getCustomDiagID( 3025 DiagnosticsEngine::Error, 3026 "member pointer representation requires a " 3027 "complete class type for %0 to perform this expression"); 3028 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange(); 3029 } else if (RD->getNumVBases()) 3030 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 3031 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 3032 } 3033 llvm::Value *VBPtr = nullptr; 3034 llvm::Value *VBaseOffs = 3035 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 3036 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 3037 3038 // Merge control flow with the case where we didn't have to adjust. 3039 if (VBaseAdjustBB) { 3040 Builder.CreateBr(SkipAdjustBB); 3041 CGF.EmitBlock(SkipAdjustBB); 3042 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 3043 Phi->addIncoming(Base.getPointer(), OriginalBB); 3044 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 3045 return Phi; 3046 } 3047 return AdjustedBase; 3048 } 3049 3050 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress( 3051 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, 3052 const MemberPointerType *MPT) { 3053 assert(MPT->isMemberDataPointer()); 3054 unsigned AS = Base.getAddressSpace(); 3055 llvm::Type *PType = 3056 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 3057 CGBuilderTy &Builder = CGF.Builder; 3058 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 3059 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 3060 3061 // Extract the fields we need, regardless of model. We'll apply them if we 3062 // have them. 3063 llvm::Value *FieldOffset = MemPtr; 3064 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 3065 llvm::Value *VBPtrOffset = nullptr; 3066 if (MemPtr->getType()->isStructTy()) { 3067 // We need to extract values. 3068 unsigned I = 0; 3069 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 3070 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 3071 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 3072 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 3073 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 3074 } 3075 3076 llvm::Value *Addr; 3077 if (VirtualBaseAdjustmentOffset) { 3078 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset, 3079 VBPtrOffset); 3080 } else { 3081 Addr = Base.getPointer(); 3082 } 3083 3084 // Cast to char*. 3085 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS)); 3086 3087 // Apply the offset, which we assume is non-null. 3088 Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset"); 3089 3090 // Cast the address to the appropriate pointer type, adopting the address 3091 // space of the base pointer. 3092 return Builder.CreateBitCast(Addr, PType); 3093 } 3094 3095 llvm::Value * 3096 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 3097 const CastExpr *E, 3098 llvm::Value *Src) { 3099 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 3100 E->getCastKind() == CK_BaseToDerivedMemberPointer || 3101 E->getCastKind() == CK_ReinterpretMemberPointer); 3102 3103 // Use constant emission if we can. 3104 if (isa<llvm::Constant>(Src)) 3105 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 3106 3107 // We may be adding or dropping fields from the member pointer, so we need 3108 // both types and the inheritance models of both records. 3109 const MemberPointerType *SrcTy = 3110 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 3111 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 3112 bool IsFunc = SrcTy->isMemberFunctionPointer(); 3113 3114 // If the classes use the same null representation, reinterpret_cast is a nop. 3115 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 3116 if (IsReinterpret && IsFunc) 3117 return Src; 3118 3119 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 3120 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 3121 if (IsReinterpret && 3122 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 3123 return Src; 3124 3125 CGBuilderTy &Builder = CGF.Builder; 3126 3127 // Branch past the conversion if Src is null. 3128 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 3129 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 3130 3131 // C++ 5.2.10p9: The null member pointer value is converted to the null member 3132 // pointer value of the destination type. 3133 if (IsReinterpret) { 3134 // For reinterpret casts, sema ensures that src and dst are both functions 3135 // or data and have the same size, which means the LLVM types should match. 3136 assert(Src->getType() == DstNull->getType()); 3137 return Builder.CreateSelect(IsNotNull, Src, DstNull); 3138 } 3139 3140 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 3141 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 3142 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 3143 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 3144 CGF.EmitBlock(ConvertBB); 3145 3146 llvm::Value *Dst = EmitNonNullMemberPointerConversion( 3147 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src, 3148 Builder); 3149 3150 Builder.CreateBr(ContinueBB); 3151 3152 // In the continuation, choose between DstNull and Dst. 3153 CGF.EmitBlock(ContinueBB); 3154 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 3155 Phi->addIncoming(DstNull, OriginalBB); 3156 Phi->addIncoming(Dst, ConvertBB); 3157 return Phi; 3158 } 3159 3160 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion( 3161 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK, 3162 CastExpr::path_const_iterator PathBegin, 3163 CastExpr::path_const_iterator PathEnd, llvm::Value *Src, 3164 CGBuilderTy &Builder) { 3165 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 3166 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 3167 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel(); 3168 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel(); 3169 bool IsFunc = SrcTy->isMemberFunctionPointer(); 3170 bool IsConstant = isa<llvm::Constant>(Src); 3171 3172 // Decompose src. 3173 llvm::Value *FirstField = Src; 3174 llvm::Value *NonVirtualBaseAdjustment = getZeroInt(); 3175 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt(); 3176 llvm::Value *VBPtrOffset = getZeroInt(); 3177 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) { 3178 // We need to extract values. 3179 unsigned I = 0; 3180 FirstField = Builder.CreateExtractValue(Src, I++); 3181 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance)) 3182 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 3183 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance)) 3184 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 3185 if (inheritanceModelHasVBTableOffsetField(SrcInheritance)) 3186 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 3187 } 3188 3189 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer); 3190 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy; 3191 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl(); 3192 3193 // For data pointers, we adjust the field offset directly. For functions, we 3194 // have a separate field. 3195 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 3196 3197 // The virtual inheritance model has a quirk: the virtual base table is always 3198 // referenced when dereferencing a member pointer even if the member pointer 3199 // is non-virtual. This is accounted for by adjusting the non-virtual offset 3200 // to point backwards to the top of the MDC from the first VBase. Undo this 3201 // adjustment to normalize the member pointer. 3202 llvm::Value *SrcVBIndexEqZero = 3203 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt()); 3204 if (SrcInheritance == MSInheritanceModel::Virtual) { 3205 if (int64_t SrcOffsetToFirstVBase = 3206 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) { 3207 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect( 3208 SrcVBIndexEqZero, 3209 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase), 3210 getZeroInt()); 3211 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment); 3212 } 3213 } 3214 3215 // A non-zero vbindex implies that we are dealing with a source member in a 3216 // floating virtual base in addition to some non-virtual offset. If the 3217 // vbindex is zero, we are dealing with a source that exists in a non-virtual, 3218 // fixed, base. The difference between these two cases is that the vbindex + 3219 // nvoffset *always* point to the member regardless of what context they are 3220 // evaluated in so long as the vbindex is adjusted. A member inside a fixed 3221 // base requires explicit nv adjustment. 3222 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get( 3223 CGM.IntTy, 3224 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd) 3225 .getQuantity()); 3226 3227 llvm::Value *NVDisp; 3228 if (IsDerivedToBase) 3229 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj"); 3230 else 3231 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj"); 3232 3233 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt()); 3234 3235 // Update the vbindex to an appropriate value in the destination because 3236 // SrcRD's vbtable might not be a strict prefix of the one in DstRD. 3237 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero; 3238 if (inheritanceModelHasVBTableOffsetField(DstInheritance) && 3239 inheritanceModelHasVBTableOffsetField(SrcInheritance)) { 3240 if (llvm::GlobalVariable *VDispMap = 3241 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) { 3242 llvm::Value *VBIndex = Builder.CreateExactUDiv( 3243 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4)); 3244 if (IsConstant) { 3245 llvm::Constant *Mapping = VDispMap->getInitializer(); 3246 VirtualBaseAdjustmentOffset = 3247 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex)); 3248 } else { 3249 llvm::Value *Idxs[] = {getZeroInt(), VBIndex}; 3250 VirtualBaseAdjustmentOffset = 3251 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs), 3252 CharUnits::fromQuantity(4)); 3253 } 3254 3255 DstVBIndexEqZero = 3256 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt()); 3257 } 3258 } 3259 3260 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize 3261 // it to the offset of the vbptr. 3262 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) { 3263 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get( 3264 CGM.IntTy, 3265 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity()); 3266 VBPtrOffset = 3267 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset); 3268 } 3269 3270 // Likewise, apply a similar adjustment so that dereferencing the member 3271 // pointer correctly accounts for the distance between the start of the first 3272 // virtual base and the top of the MDC. 3273 if (DstInheritance == MSInheritanceModel::Virtual) { 3274 if (int64_t DstOffsetToFirstVBase = 3275 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) { 3276 llvm::Value *DoDstAdjustment = Builder.CreateSelect( 3277 DstVBIndexEqZero, 3278 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase), 3279 getZeroInt()); 3280 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment); 3281 } 3282 } 3283 3284 // Recompose dst from the null struct and the adjusted fields from src. 3285 llvm::Value *Dst; 3286 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) { 3287 Dst = FirstField; 3288 } else { 3289 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy)); 3290 unsigned Idx = 0; 3291 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 3292 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance)) 3293 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++); 3294 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) 3295 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++); 3296 if (inheritanceModelHasVBTableOffsetField(DstInheritance)) 3297 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++); 3298 } 3299 return Dst; 3300 } 3301 3302 llvm::Constant * 3303 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 3304 llvm::Constant *Src) { 3305 const MemberPointerType *SrcTy = 3306 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 3307 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 3308 3309 CastKind CK = E->getCastKind(); 3310 3311 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(), 3312 E->path_end(), Src); 3313 } 3314 3315 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion( 3316 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK, 3317 CastExpr::path_const_iterator PathBegin, 3318 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) { 3319 assert(CK == CK_DerivedToBaseMemberPointer || 3320 CK == CK_BaseToDerivedMemberPointer || 3321 CK == CK_ReinterpretMemberPointer); 3322 // If src is null, emit a new null for dst. We can't return src because dst 3323 // might have a new representation. 3324 if (MemberPointerConstantIsNull(SrcTy, Src)) 3325 return EmitNullMemberPointer(DstTy); 3326 3327 // We don't need to do anything for reinterpret_casts of non-null member 3328 // pointers. We should only get here when the two type representations have 3329 // the same size. 3330 if (CK == CK_ReinterpretMemberPointer) 3331 return Src; 3332 3333 CGBuilderTy Builder(CGM, CGM.getLLVMContext()); 3334 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion( 3335 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder)); 3336 3337 return Dst; 3338 } 3339 3340 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer( 3341 CodeGenFunction &CGF, const Expr *E, Address This, 3342 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr, 3343 const MemberPointerType *MPT) { 3344 assert(MPT->isMemberFunctionPointer()); 3345 const FunctionProtoType *FPT = 3346 MPT->getPointeeType()->castAs<FunctionProtoType>(); 3347 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 3348 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( 3349 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); 3350 CGBuilderTy &Builder = CGF.Builder; 3351 3352 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 3353 3354 // Extract the fields we need, regardless of model. We'll apply them if we 3355 // have them. 3356 llvm::Value *FunctionPointer = MemPtr; 3357 llvm::Value *NonVirtualBaseAdjustment = nullptr; 3358 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 3359 llvm::Value *VBPtrOffset = nullptr; 3360 if (MemPtr->getType()->isStructTy()) { 3361 // We need to extract values. 3362 unsigned I = 0; 3363 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 3364 if (inheritanceModelHasNVOffsetField(MPT, Inheritance)) 3365 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 3366 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) 3367 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 3368 if (inheritanceModelHasVBTableOffsetField(Inheritance)) 3369 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 3370 } 3371 3372 if (VirtualBaseAdjustmentOffset) { 3373 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This, 3374 VirtualBaseAdjustmentOffset, VBPtrOffset); 3375 } else { 3376 ThisPtrForCall = This.getPointer(); 3377 } 3378 3379 if (NonVirtualBaseAdjustment) { 3380 // Apply the adjustment and cast back to the original struct type. 3381 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy); 3382 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 3383 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(), 3384 "this.adjusted"); 3385 } 3386 3387 FunctionPointer = 3388 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 3389 CGCallee Callee(FPT, FunctionPointer); 3390 return Callee; 3391 } 3392 3393 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 3394 return new MicrosoftCXXABI(CGM); 3395 } 3396 3397 // MS RTTI Overview: 3398 // The run time type information emitted by cl.exe contains 5 distinct types of 3399 // structures. Many of them reference each other. 3400 // 3401 // TypeInfo: Static classes that are returned by typeid. 3402 // 3403 // CompleteObjectLocator: Referenced by vftables. They contain information 3404 // required for dynamic casting, including OffsetFromTop. They also contain 3405 // a reference to the TypeInfo for the type and a reference to the 3406 // CompleteHierarchyDescriptor for the type. 3407 // 3408 // ClassHierarchyDescriptor: Contains information about a class hierarchy. 3409 // Used during dynamic_cast to walk a class hierarchy. References a base 3410 // class array and the size of said array. 3411 // 3412 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is 3413 // somewhat of a misnomer because the most derived class is also in the list 3414 // as well as multiple copies of virtual bases (if they occur multiple times 3415 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for 3416 // every path in the hierarchy, in pre-order depth first order. Note, we do 3417 // not declare a specific llvm type for BaseClassArray, it's merely an array 3418 // of BaseClassDescriptor pointers. 3419 // 3420 // BaseClassDescriptor: Contains information about a class in a class hierarchy. 3421 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that 3422 // BaseClassArray is. It contains information about a class within a 3423 // hierarchy such as: is this base is ambiguous and what is its offset in the 3424 // vbtable. The names of the BaseClassDescriptors have all of their fields 3425 // mangled into them so they can be aggressively deduplicated by the linker. 3426 3427 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) { 3428 StringRef MangledName("??_7type_info@@6B@"); 3429 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName)) 3430 return VTable; 3431 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 3432 /*isConstant=*/true, 3433 llvm::GlobalVariable::ExternalLinkage, 3434 /*Initializer=*/nullptr, MangledName); 3435 } 3436 3437 namespace { 3438 3439 /// A Helper struct that stores information about a class in a class 3440 /// hierarchy. The information stored in these structs struct is used during 3441 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors. 3442 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with 3443 // implicit depth first pre-order tree connectivity. getFirstChild and 3444 // getNextSibling allow us to walk the tree efficiently. 3445 struct MSRTTIClass { 3446 enum { 3447 IsPrivateOnPath = 1 | 8, 3448 IsAmbiguous = 2, 3449 IsPrivate = 4, 3450 IsVirtual = 16, 3451 HasHierarchyDescriptor = 64 3452 }; 3453 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {} 3454 uint32_t initialize(const MSRTTIClass *Parent, 3455 const CXXBaseSpecifier *Specifier); 3456 3457 MSRTTIClass *getFirstChild() { return this + 1; } 3458 static MSRTTIClass *getNextChild(MSRTTIClass *Child) { 3459 return Child + 1 + Child->NumBases; 3460 } 3461 3462 const CXXRecordDecl *RD, *VirtualRoot; 3463 uint32_t Flags, NumBases, OffsetInVBase; 3464 }; 3465 3466 /// Recursively initialize the base class array. 3467 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent, 3468 const CXXBaseSpecifier *Specifier) { 3469 Flags = HasHierarchyDescriptor; 3470 if (!Parent) { 3471 VirtualRoot = nullptr; 3472 OffsetInVBase = 0; 3473 } else { 3474 if (Specifier->getAccessSpecifier() != AS_public) 3475 Flags |= IsPrivate | IsPrivateOnPath; 3476 if (Specifier->isVirtual()) { 3477 Flags |= IsVirtual; 3478 VirtualRoot = RD; 3479 OffsetInVBase = 0; 3480 } else { 3481 if (Parent->Flags & IsPrivateOnPath) 3482 Flags |= IsPrivateOnPath; 3483 VirtualRoot = Parent->VirtualRoot; 3484 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext() 3485 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity(); 3486 } 3487 } 3488 NumBases = 0; 3489 MSRTTIClass *Child = getFirstChild(); 3490 for (const CXXBaseSpecifier &Base : RD->bases()) { 3491 NumBases += Child->initialize(this, &Base) + 1; 3492 Child = getNextChild(Child); 3493 } 3494 return NumBases; 3495 } 3496 3497 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) { 3498 switch (Ty->getLinkage()) { 3499 case NoLinkage: 3500 case InternalLinkage: 3501 case UniqueExternalLinkage: 3502 return llvm::GlobalValue::InternalLinkage; 3503 3504 case VisibleNoLinkage: 3505 case ModuleInternalLinkage: 3506 case ModuleLinkage: 3507 case ExternalLinkage: 3508 return llvm::GlobalValue::LinkOnceODRLinkage; 3509 } 3510 llvm_unreachable("Invalid linkage!"); 3511 } 3512 3513 /// An ephemeral helper class for building MS RTTI types. It caches some 3514 /// calls to the module and information about the most derived class in a 3515 /// hierarchy. 3516 struct MSRTTIBuilder { 3517 enum { 3518 HasBranchingHierarchy = 1, 3519 HasVirtualBranchingHierarchy = 2, 3520 HasAmbiguousBases = 4 3521 }; 3522 3523 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD) 3524 : CGM(ABI.CGM), Context(CGM.getContext()), 3525 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD), 3526 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))), 3527 ABI(ABI) {} 3528 3529 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes); 3530 llvm::GlobalVariable * 3531 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes); 3532 llvm::GlobalVariable *getClassHierarchyDescriptor(); 3533 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info); 3534 3535 CodeGenModule &CGM; 3536 ASTContext &Context; 3537 llvm::LLVMContext &VMContext; 3538 llvm::Module &Module; 3539 const CXXRecordDecl *RD; 3540 llvm::GlobalVariable::LinkageTypes Linkage; 3541 MicrosoftCXXABI &ABI; 3542 }; 3543 3544 } // namespace 3545 3546 /// Recursively serializes a class hierarchy in pre-order depth first 3547 /// order. 3548 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes, 3549 const CXXRecordDecl *RD) { 3550 Classes.push_back(MSRTTIClass(RD)); 3551 for (const CXXBaseSpecifier &Base : RD->bases()) 3552 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl()); 3553 } 3554 3555 /// Find ambiguity among base classes. 3556 static void 3557 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) { 3558 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases; 3559 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases; 3560 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases; 3561 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) { 3562 if ((Class->Flags & MSRTTIClass::IsVirtual) && 3563 !VirtualBases.insert(Class->RD).second) { 3564 Class = MSRTTIClass::getNextChild(Class); 3565 continue; 3566 } 3567 if (!UniqueBases.insert(Class->RD).second) 3568 AmbiguousBases.insert(Class->RD); 3569 Class++; 3570 } 3571 if (AmbiguousBases.empty()) 3572 return; 3573 for (MSRTTIClass &Class : Classes) 3574 if (AmbiguousBases.count(Class.RD)) 3575 Class.Flags |= MSRTTIClass::IsAmbiguous; 3576 } 3577 3578 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() { 3579 SmallString<256> MangledName; 3580 { 3581 llvm::raw_svector_ostream Out(MangledName); 3582 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out); 3583 } 3584 3585 // Check to see if we've already declared this ClassHierarchyDescriptor. 3586 if (auto CHD = Module.getNamedGlobal(MangledName)) 3587 return CHD; 3588 3589 // Serialize the class hierarchy and initialize the CHD Fields. 3590 SmallVector<MSRTTIClass, 8> Classes; 3591 serializeClassHierarchy(Classes, RD); 3592 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr); 3593 detectAmbiguousBases(Classes); 3594 int Flags = 0; 3595 for (auto Class : Classes) { 3596 if (Class.RD->getNumBases() > 1) 3597 Flags |= HasBranchingHierarchy; 3598 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We 3599 // believe the field isn't actually used. 3600 if (Class.Flags & MSRTTIClass::IsAmbiguous) 3601 Flags |= HasAmbiguousBases; 3602 } 3603 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0) 3604 Flags |= HasVirtualBranchingHierarchy; 3605 // These gep indices are used to get the address of the first element of the 3606 // base class array. 3607 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0), 3608 llvm::ConstantInt::get(CGM.IntTy, 0)}; 3609 3610 // Forward-declare the class hierarchy descriptor 3611 auto Type = ABI.getClassHierarchyDescriptorType(); 3612 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage, 3613 /*Initializer=*/nullptr, 3614 MangledName); 3615 if (CHD->isWeakForLinker()) 3616 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName())); 3617 3618 auto *Bases = getBaseClassArray(Classes); 3619 3620 // Initialize the base class ClassHierarchyDescriptor. 3621 llvm::Constant *Fields[] = { 3622 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime 3623 llvm::ConstantInt::get(CGM.IntTy, Flags), 3624 llvm::ConstantInt::get(CGM.IntTy, Classes.size()), 3625 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr( 3626 Bases->getValueType(), Bases, 3627 llvm::ArrayRef<llvm::Value *>(GEPIndices))), 3628 }; 3629 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 3630 return CHD; 3631 } 3632 3633 llvm::GlobalVariable * 3634 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) { 3635 SmallString<256> MangledName; 3636 { 3637 llvm::raw_svector_ostream Out(MangledName); 3638 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out); 3639 } 3640 3641 // Forward-declare the base class array. 3642 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit 3643 // mode) bytes of padding. We provide a pointer sized amount of padding by 3644 // adding +1 to Classes.size(). The sections have pointer alignment and are 3645 // marked pick-any so it shouldn't matter. 3646 llvm::Type *PtrType = ABI.getImageRelativeType( 3647 ABI.getBaseClassDescriptorType()->getPointerTo()); 3648 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1); 3649 auto *BCA = 3650 new llvm::GlobalVariable(Module, ArrType, 3651 /*isConstant=*/true, Linkage, 3652 /*Initializer=*/nullptr, MangledName); 3653 if (BCA->isWeakForLinker()) 3654 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName())); 3655 3656 // Initialize the BaseClassArray. 3657 SmallVector<llvm::Constant *, 8> BaseClassArrayData; 3658 for (MSRTTIClass &Class : Classes) 3659 BaseClassArrayData.push_back( 3660 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class))); 3661 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType)); 3662 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData)); 3663 return BCA; 3664 } 3665 3666 llvm::GlobalVariable * 3667 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) { 3668 // Compute the fields for the BaseClassDescriptor. They are computed up front 3669 // because they are mangled into the name of the object. 3670 uint32_t OffsetInVBTable = 0; 3671 int32_t VBPtrOffset = -1; 3672 if (Class.VirtualRoot) { 3673 auto &VTableContext = CGM.getMicrosoftVTableContext(); 3674 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4; 3675 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity(); 3676 } 3677 3678 SmallString<256> MangledName; 3679 { 3680 llvm::raw_svector_ostream Out(MangledName); 3681 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor( 3682 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable, 3683 Class.Flags, Out); 3684 } 3685 3686 // Check to see if we've already declared this object. 3687 if (auto BCD = Module.getNamedGlobal(MangledName)) 3688 return BCD; 3689 3690 // Forward-declare the base class descriptor. 3691 auto Type = ABI.getBaseClassDescriptorType(); 3692 auto BCD = 3693 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage, 3694 /*Initializer=*/nullptr, MangledName); 3695 if (BCD->isWeakForLinker()) 3696 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName())); 3697 3698 // Initialize the BaseClassDescriptor. 3699 llvm::Constant *Fields[] = { 3700 ABI.getImageRelativeConstant( 3701 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))), 3702 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases), 3703 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase), 3704 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 3705 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable), 3706 llvm::ConstantInt::get(CGM.IntTy, Class.Flags), 3707 ABI.getImageRelativeConstant( 3708 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()), 3709 }; 3710 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields)); 3711 return BCD; 3712 } 3713 3714 llvm::GlobalVariable * 3715 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) { 3716 SmallString<256> MangledName; 3717 { 3718 llvm::raw_svector_ostream Out(MangledName); 3719 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out); 3720 } 3721 3722 // Check to see if we've already computed this complete object locator. 3723 if (auto COL = Module.getNamedGlobal(MangledName)) 3724 return COL; 3725 3726 // Compute the fields of the complete object locator. 3727 int OffsetToTop = Info.FullOffsetInMDC.getQuantity(); 3728 int VFPtrOffset = 0; 3729 // The offset includes the vtordisp if one exists. 3730 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr()) 3731 if (Context.getASTRecordLayout(RD) 3732 .getVBaseOffsetsMap() 3733 .find(VBase) 3734 ->second.hasVtorDisp()) 3735 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4; 3736 3737 // Forward-declare the complete object locator. 3738 llvm::StructType *Type = ABI.getCompleteObjectLocatorType(); 3739 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage, 3740 /*Initializer=*/nullptr, MangledName); 3741 3742 // Initialize the CompleteObjectLocator. 3743 llvm::Constant *Fields[] = { 3744 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()), 3745 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop), 3746 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset), 3747 ABI.getImageRelativeConstant( 3748 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))), 3749 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()), 3750 ABI.getImageRelativeConstant(COL), 3751 }; 3752 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields); 3753 if (!ABI.isImageRelative()) 3754 FieldsRef = FieldsRef.drop_back(); 3755 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef)); 3756 if (COL->isWeakForLinker()) 3757 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName())); 3758 return COL; 3759 } 3760 3761 static QualType decomposeTypeForEH(ASTContext &Context, QualType T, 3762 bool &IsConst, bool &IsVolatile, 3763 bool &IsUnaligned) { 3764 T = Context.getExceptionObjectType(T); 3765 3766 // C++14 [except.handle]p3: 3767 // A handler is a match for an exception object of type E if [...] 3768 // - the handler is of type cv T or const T& where T is a pointer type and 3769 // E is a pointer type that can be converted to T by [...] 3770 // - a qualification conversion 3771 IsConst = false; 3772 IsVolatile = false; 3773 IsUnaligned = false; 3774 QualType PointeeType = T->getPointeeType(); 3775 if (!PointeeType.isNull()) { 3776 IsConst = PointeeType.isConstQualified(); 3777 IsVolatile = PointeeType.isVolatileQualified(); 3778 IsUnaligned = PointeeType.getQualifiers().hasUnaligned(); 3779 } 3780 3781 // Member pointer types like "const int A::*" are represented by having RTTI 3782 // for "int A::*" and separately storing the const qualifier. 3783 if (const auto *MPTy = T->getAs<MemberPointerType>()) 3784 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(), 3785 MPTy->getClass()); 3786 3787 // Pointer types like "const int * const *" are represented by having RTTI 3788 // for "const int **" and separately storing the const qualifier. 3789 if (T->isPointerType()) 3790 T = Context.getPointerType(PointeeType.getUnqualifiedType()); 3791 3792 return T; 3793 } 3794 3795 CatchTypeInfo 3796 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type, 3797 QualType CatchHandlerType) { 3798 // TypeDescriptors for exceptions never have qualified pointer types, 3799 // qualifiers are stored separately in order to support qualification 3800 // conversions. 3801 bool IsConst, IsVolatile, IsUnaligned; 3802 Type = 3803 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned); 3804 3805 bool IsReference = CatchHandlerType->isReferenceType(); 3806 3807 uint32_t Flags = 0; 3808 if (IsConst) 3809 Flags |= 1; 3810 if (IsVolatile) 3811 Flags |= 2; 3812 if (IsUnaligned) 3813 Flags |= 4; 3814 if (IsReference) 3815 Flags |= 8; 3816 3817 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(), 3818 Flags}; 3819 } 3820 3821 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a 3822 /// llvm::GlobalVariable * because different type descriptors have different 3823 /// types, and need to be abstracted. They are abstracting by casting the 3824 /// address to an Int8PtrTy. 3825 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) { 3826 SmallString<256> MangledName; 3827 { 3828 llvm::raw_svector_ostream Out(MangledName); 3829 getMangleContext().mangleCXXRTTI(Type, Out); 3830 } 3831 3832 // Check to see if we've already declared this TypeDescriptor. 3833 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 3834 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 3835 3836 // Note for the future: If we would ever like to do deferred emission of 3837 // RTTI, check if emitting vtables opportunistically need any adjustment. 3838 3839 // Compute the fields for the TypeDescriptor. 3840 SmallString<256> TypeInfoString; 3841 { 3842 llvm::raw_svector_ostream Out(TypeInfoString); 3843 getMangleContext().mangleCXXRTTIName(Type, Out); 3844 } 3845 3846 // Declare and initialize the TypeDescriptor. 3847 llvm::Constant *Fields[] = { 3848 getTypeInfoVTable(CGM), // VFPtr 3849 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data 3850 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)}; 3851 llvm::StructType *TypeDescriptorType = 3852 getTypeDescriptorType(TypeInfoString); 3853 auto *Var = new llvm::GlobalVariable( 3854 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false, 3855 getLinkageForRTTI(Type), 3856 llvm::ConstantStruct::get(TypeDescriptorType, Fields), 3857 MangledName); 3858 if (Var->isWeakForLinker()) 3859 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName())); 3860 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy); 3861 } 3862 3863 /// Gets or a creates a Microsoft CompleteObjectLocator. 3864 llvm::GlobalVariable * 3865 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD, 3866 const VPtrInfo &Info) { 3867 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info); 3868 } 3869 3870 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) { 3871 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) { 3872 // There are no constructor variants, always emit the complete destructor. 3873 llvm::Function *Fn = 3874 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete)); 3875 CGM.maybeSetTrivialComdat(*ctor, *Fn); 3876 return; 3877 } 3878 3879 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl()); 3880 3881 // Emit the base destructor if the base and complete (vbase) destructors are 3882 // equivalent. This effectively implements -mconstructor-aliases as part of 3883 // the ABI. 3884 if (GD.getDtorType() == Dtor_Complete && 3885 dtor->getParent()->getNumVBases() == 0) 3886 GD = GD.getWithDtorType(Dtor_Base); 3887 3888 // The base destructor is equivalent to the base destructor of its 3889 // base class if there is exactly one non-virtual base class with a 3890 // non-trivial destructor, there are no fields with a non-trivial 3891 // destructor, and the body of the destructor is trivial. 3892 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor)) 3893 return; 3894 3895 llvm::Function *Fn = CGM.codegenCXXStructor(GD); 3896 if (Fn->isWeakForLinker()) 3897 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName())); 3898 } 3899 3900 llvm::Function * 3901 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD, 3902 CXXCtorType CT) { 3903 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure); 3904 3905 // Calculate the mangled name. 3906 SmallString<256> ThunkName; 3907 llvm::raw_svector_ostream Out(ThunkName); 3908 getMangleContext().mangleCXXCtor(CD, CT, Out); 3909 3910 // If the thunk has been generated previously, just return it. 3911 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 3912 return cast<llvm::Function>(GV); 3913 3914 // Create the llvm::Function. 3915 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT); 3916 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 3917 const CXXRecordDecl *RD = CD->getParent(); 3918 QualType RecordTy = getContext().getRecordType(RD); 3919 llvm::Function *ThunkFn = llvm::Function::Create( 3920 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule()); 3921 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>( 3922 FnInfo.getEffectiveCallingConvention())); 3923 if (ThunkFn->isWeakForLinker()) 3924 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName())); 3925 bool IsCopy = CT == Ctor_CopyingClosure; 3926 3927 // Start codegen. 3928 CodeGenFunction CGF(CGM); 3929 CGF.CurGD = GlobalDecl(CD, Ctor_Complete); 3930 3931 // Build FunctionArgs. 3932 FunctionArgList FunctionArgs; 3933 3934 // A constructor always starts with a 'this' pointer as its first argument. 3935 buildThisParam(CGF, FunctionArgs); 3936 3937 // Following the 'this' pointer is a reference to the source object that we 3938 // are copying from. 3939 ImplicitParamDecl SrcParam( 3940 getContext(), /*DC=*/nullptr, SourceLocation(), 3941 &getContext().Idents.get("src"), 3942 getContext().getLValueReferenceType(RecordTy, 3943 /*SpelledAsLValue=*/true), 3944 ImplicitParamDecl::Other); 3945 if (IsCopy) 3946 FunctionArgs.push_back(&SrcParam); 3947 3948 // Constructors for classes which utilize virtual bases have an additional 3949 // parameter which indicates whether or not it is being delegated to by a more 3950 // derived constructor. 3951 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr, 3952 SourceLocation(), 3953 &getContext().Idents.get("is_most_derived"), 3954 getContext().IntTy, ImplicitParamDecl::Other); 3955 // Only add the parameter to the list if the class has virtual bases. 3956 if (RD->getNumVBases() > 0) 3957 FunctionArgs.push_back(&IsMostDerived); 3958 3959 // Start defining the function. 3960 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 3961 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo, 3962 FunctionArgs, CD->getLocation(), SourceLocation()); 3963 // Create a scope with an artificial location for the body of this function. 3964 auto AL = ApplyDebugLocation::CreateArtificial(CGF); 3965 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF)); 3966 llvm::Value *This = getThisValue(CGF); 3967 3968 llvm::Value *SrcVal = 3969 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src") 3970 : nullptr; 3971 3972 CallArgList Args; 3973 3974 // Push the this ptr. 3975 Args.add(RValue::get(This), CD->getThisType()); 3976 3977 // Push the src ptr. 3978 if (SrcVal) 3979 Args.add(RValue::get(SrcVal), SrcParam.getType()); 3980 3981 // Add the rest of the default arguments. 3982 SmallVector<const Stmt *, 4> ArgVec; 3983 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0); 3984 for (const ParmVarDecl *PD : params) { 3985 assert(PD->hasDefaultArg() && "ctor closure lacks default args"); 3986 ArgVec.push_back(PD->getDefaultArg()); 3987 } 3988 3989 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 3990 3991 const auto *FPT = CD->getType()->castAs<FunctionProtoType>(); 3992 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0); 3993 3994 // Insert any ABI-specific implicit constructor arguments. 3995 AddedStructorArgs ExtraArgs = 3996 addImplicitConstructorArgs(CGF, CD, Ctor_Complete, 3997 /*ForVirtualBase=*/false, 3998 /*Delegating=*/false, Args); 3999 // Call the destructor with our arguments. 4000 llvm::Constant *CalleePtr = 4001 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete)); 4002 CGCallee Callee = 4003 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete)); 4004 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall( 4005 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix); 4006 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args); 4007 4008 Cleanups.ForceCleanup(); 4009 4010 // Emit the ret instruction, remove any temporary instructions created for the 4011 // aid of CodeGen. 4012 CGF.FinishFunction(SourceLocation()); 4013 4014 return ThunkFn; 4015 } 4016 4017 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T, 4018 uint32_t NVOffset, 4019 int32_t VBPtrOffset, 4020 uint32_t VBIndex) { 4021 assert(!T->isReferenceType()); 4022 4023 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 4024 const CXXConstructorDecl *CD = 4025 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr; 4026 CXXCtorType CT = Ctor_Complete; 4027 if (CD) 4028 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1) 4029 CT = Ctor_CopyingClosure; 4030 4031 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity(); 4032 SmallString<256> MangledName; 4033 { 4034 llvm::raw_svector_ostream Out(MangledName); 4035 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset, 4036 VBPtrOffset, VBIndex, Out); 4037 } 4038 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 4039 return getImageRelativeConstant(GV); 4040 4041 // The TypeDescriptor is used by the runtime to determine if a catch handler 4042 // is appropriate for the exception object. 4043 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T)); 4044 4045 // The runtime is responsible for calling the copy constructor if the 4046 // exception is caught by value. 4047 llvm::Constant *CopyCtor; 4048 if (CD) { 4049 if (CT == Ctor_CopyingClosure) 4050 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure); 4051 else 4052 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete)); 4053 4054 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy); 4055 } else { 4056 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy); 4057 } 4058 CopyCtor = getImageRelativeConstant(CopyCtor); 4059 4060 bool IsScalar = !RD; 4061 bool HasVirtualBases = false; 4062 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason. 4063 QualType PointeeType = T; 4064 if (T->isPointerType()) 4065 PointeeType = T->getPointeeType(); 4066 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) { 4067 HasVirtualBases = RD->getNumVBases() > 0; 4068 if (IdentifierInfo *II = RD->getIdentifier()) 4069 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace(); 4070 } 4071 4072 // Encode the relevant CatchableType properties into the Flags bitfield. 4073 // FIXME: Figure out how bits 2 or 8 can get set. 4074 uint32_t Flags = 0; 4075 if (IsScalar) 4076 Flags |= 1; 4077 if (HasVirtualBases) 4078 Flags |= 4; 4079 if (IsStdBadAlloc) 4080 Flags |= 16; 4081 4082 llvm::Constant *Fields[] = { 4083 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags 4084 TD, // TypeDescriptor 4085 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment 4086 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr 4087 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex 4088 llvm::ConstantInt::get(CGM.IntTy, Size), // Size 4089 CopyCtor // CopyCtor 4090 }; 4091 llvm::StructType *CTType = getCatchableTypeType(); 4092 auto *GV = new llvm::GlobalVariable( 4093 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T), 4094 llvm::ConstantStruct::get(CTType, Fields), MangledName); 4095 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4096 GV->setSection(".xdata"); 4097 if (GV->isWeakForLinker()) 4098 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName())); 4099 return getImageRelativeConstant(GV); 4100 } 4101 4102 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) { 4103 assert(!T->isReferenceType()); 4104 4105 // See if we've already generated a CatchableTypeArray for this type before. 4106 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T]; 4107 if (CTA) 4108 return CTA; 4109 4110 // Ensure that we don't have duplicate entries in our CatchableTypeArray by 4111 // using a SmallSetVector. Duplicates may arise due to virtual bases 4112 // occurring more than once in the hierarchy. 4113 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes; 4114 4115 // C++14 [except.handle]p3: 4116 // A handler is a match for an exception object of type E if [...] 4117 // - the handler is of type cv T or cv T& and T is an unambiguous public 4118 // base class of E, or 4119 // - the handler is of type cv T or const T& where T is a pointer type and 4120 // E is a pointer type that can be converted to T by [...] 4121 // - a standard pointer conversion (4.10) not involving conversions to 4122 // pointers to private or protected or ambiguous classes 4123 const CXXRecordDecl *MostDerivedClass = nullptr; 4124 bool IsPointer = T->isPointerType(); 4125 if (IsPointer) 4126 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl(); 4127 else 4128 MostDerivedClass = T->getAsCXXRecordDecl(); 4129 4130 // Collect all the unambiguous public bases of the MostDerivedClass. 4131 if (MostDerivedClass) { 4132 const ASTContext &Context = getContext(); 4133 const ASTRecordLayout &MostDerivedLayout = 4134 Context.getASTRecordLayout(MostDerivedClass); 4135 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext(); 4136 SmallVector<MSRTTIClass, 8> Classes; 4137 serializeClassHierarchy(Classes, MostDerivedClass); 4138 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr); 4139 detectAmbiguousBases(Classes); 4140 for (const MSRTTIClass &Class : Classes) { 4141 // Skip any ambiguous or private bases. 4142 if (Class.Flags & 4143 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous)) 4144 continue; 4145 // Write down how to convert from a derived pointer to a base pointer. 4146 uint32_t OffsetInVBTable = 0; 4147 int32_t VBPtrOffset = -1; 4148 if (Class.VirtualRoot) { 4149 OffsetInVBTable = 4150 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4; 4151 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity(); 4152 } 4153 4154 // Turn our record back into a pointer if the exception object is a 4155 // pointer. 4156 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0); 4157 if (IsPointer) 4158 RTTITy = Context.getPointerType(RTTITy); 4159 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase, 4160 VBPtrOffset, OffsetInVBTable)); 4161 } 4162 } 4163 4164 // C++14 [except.handle]p3: 4165 // A handler is a match for an exception object of type E if 4166 // - The handler is of type cv T or cv T& and E and T are the same type 4167 // (ignoring the top-level cv-qualifiers) 4168 CatchableTypes.insert(getCatchableType(T)); 4169 4170 // C++14 [except.handle]p3: 4171 // A handler is a match for an exception object of type E if 4172 // - the handler is of type cv T or const T& where T is a pointer type and 4173 // E is a pointer type that can be converted to T by [...] 4174 // - a standard pointer conversion (4.10) not involving conversions to 4175 // pointers to private or protected or ambiguous classes 4176 // 4177 // C++14 [conv.ptr]p2: 4178 // A prvalue of type "pointer to cv T," where T is an object type, can be 4179 // converted to a prvalue of type "pointer to cv void". 4180 if (IsPointer && T->getPointeeType()->isObjectType()) 4181 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy)); 4182 4183 // C++14 [except.handle]p3: 4184 // A handler is a match for an exception object of type E if [...] 4185 // - the handler is of type cv T or const T& where T is a pointer or 4186 // pointer to member type and E is std::nullptr_t. 4187 // 4188 // We cannot possibly list all possible pointer types here, making this 4189 // implementation incompatible with the standard. However, MSVC includes an 4190 // entry for pointer-to-void in this case. Let's do the same. 4191 if (T->isNullPtrType()) 4192 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy)); 4193 4194 uint32_t NumEntries = CatchableTypes.size(); 4195 llvm::Type *CTType = 4196 getImageRelativeType(getCatchableTypeType()->getPointerTo()); 4197 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries); 4198 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries); 4199 llvm::Constant *Fields[] = { 4200 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries 4201 llvm::ConstantArray::get( 4202 AT, llvm::makeArrayRef(CatchableTypes.begin(), 4203 CatchableTypes.end())) // CatchableTypes 4204 }; 4205 SmallString<256> MangledName; 4206 { 4207 llvm::raw_svector_ostream Out(MangledName); 4208 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out); 4209 } 4210 CTA = new llvm::GlobalVariable( 4211 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T), 4212 llvm::ConstantStruct::get(CTAType, Fields), MangledName); 4213 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4214 CTA->setSection(".xdata"); 4215 if (CTA->isWeakForLinker()) 4216 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName())); 4217 return CTA; 4218 } 4219 4220 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) { 4221 bool IsConst, IsVolatile, IsUnaligned; 4222 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned); 4223 4224 // The CatchableTypeArray enumerates the various (CV-unqualified) types that 4225 // the exception object may be caught as. 4226 llvm::GlobalVariable *CTA = getCatchableTypeArray(T); 4227 // The first field in a CatchableTypeArray is the number of CatchableTypes. 4228 // This is used as a component of the mangled name which means that we need to 4229 // know what it is in order to see if we have previously generated the 4230 // ThrowInfo. 4231 uint32_t NumEntries = 4232 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U)) 4233 ->getLimitedValue(); 4234 4235 SmallString<256> MangledName; 4236 { 4237 llvm::raw_svector_ostream Out(MangledName); 4238 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned, 4239 NumEntries, Out); 4240 } 4241 4242 // Reuse a previously generated ThrowInfo if we have generated an appropriate 4243 // one before. 4244 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName)) 4245 return GV; 4246 4247 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must 4248 // be at least as CV qualified. Encode this requirement into the Flags 4249 // bitfield. 4250 uint32_t Flags = 0; 4251 if (IsConst) 4252 Flags |= 1; 4253 if (IsVolatile) 4254 Flags |= 2; 4255 if (IsUnaligned) 4256 Flags |= 4; 4257 4258 // The cleanup-function (a destructor) must be called when the exception 4259 // object's lifetime ends. 4260 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy); 4261 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4262 if (CXXDestructorDecl *DtorD = RD->getDestructor()) 4263 if (!DtorD->isTrivial()) 4264 CleanupFn = llvm::ConstantExpr::getBitCast( 4265 CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)), 4266 CGM.Int8PtrTy); 4267 // This is unused as far as we can tell, initialize it to null. 4268 llvm::Constant *ForwardCompat = 4269 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy)); 4270 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant( 4271 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy)); 4272 llvm::StructType *TIType = getThrowInfoType(); 4273 llvm::Constant *Fields[] = { 4274 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags 4275 getImageRelativeConstant(CleanupFn), // CleanupFn 4276 ForwardCompat, // ForwardCompat 4277 PointerToCatchableTypes // CatchableTypeArray 4278 }; 4279 auto *GV = new llvm::GlobalVariable( 4280 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T), 4281 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName)); 4282 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4283 GV->setSection(".xdata"); 4284 if (GV->isWeakForLinker()) 4285 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName())); 4286 return GV; 4287 } 4288 4289 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) { 4290 const Expr *SubExpr = E->getSubExpr(); 4291 QualType ThrowType = SubExpr->getType(); 4292 // The exception object lives on the stack and it's address is passed to the 4293 // runtime function. 4294 Address AI = CGF.CreateMemTemp(ThrowType); 4295 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(), 4296 /*IsInit=*/true); 4297 4298 // The so-called ThrowInfo is used to describe how the exception object may be 4299 // caught. 4300 llvm::GlobalVariable *TI = getThrowInfo(ThrowType); 4301 4302 // Call into the runtime to throw the exception. 4303 llvm::Value *Args[] = { 4304 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy), 4305 TI 4306 }; 4307 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args); 4308 } 4309 4310 std::pair<llvm::Value *, const CXXRecordDecl *> 4311 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This, 4312 const CXXRecordDecl *RD) { 4313 std::tie(This, std::ignore, RD) = 4314 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0)); 4315 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD}; 4316 } 4317