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