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