1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides C++ code generation targeting the Itanium C++ ABI. The class 11 // in this file generates structures that follow the Itanium C++ ABI, which is 12 // documented at: 13 // http://www.codesourcery.com/public/cxx-abi/abi.html 14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html 15 // 16 // It also supports the closely-related ARM ABI, documented at: 17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "CGCXXABI.h" 22 #include "CGRecordLayout.h" 23 #include "CGVTables.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenModule.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/AST/Type.h" 28 #include "llvm/IR/CallSite.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Intrinsics.h" 31 #include "llvm/IR/Value.h" 32 33 using namespace clang; 34 using namespace CodeGen; 35 36 namespace { 37 class ItaniumCXXABI : public CodeGen::CGCXXABI { 38 /// VTables - All the vtables which have been defined. 39 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables; 40 41 protected: 42 bool UseARMMethodPtrABI; 43 bool UseARMGuardVarABI; 44 45 ItaniumMangleContext &getMangleContext() { 46 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 47 } 48 49 public: 50 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, 51 bool UseARMMethodPtrABI = false, 52 bool UseARMGuardVarABI = false) : 53 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), 54 UseARMGuardVarABI(UseARMGuardVarABI) { } 55 56 bool classifyReturnType(CGFunctionInfo &FI) const override; 57 58 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override { 59 // Structures with either a non-trivial destructor or a non-trivial 60 // copy constructor are always indirect. 61 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared 62 // special members. 63 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) 64 return RAA_Indirect; 65 return RAA_Default; 66 } 67 68 bool isZeroInitializable(const MemberPointerType *MPT) override; 69 70 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 71 72 llvm::Value * 73 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 74 const Expr *E, 75 llvm::Value *&This, 76 llvm::Value *MemFnPtr, 77 const MemberPointerType *MPT) override; 78 79 llvm::Value * 80 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 81 llvm::Value *Base, 82 llvm::Value *MemPtr, 83 const MemberPointerType *MPT) override; 84 85 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 86 const CastExpr *E, 87 llvm::Value *Src) override; 88 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 89 llvm::Constant *Src) override; 90 91 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 92 93 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override; 94 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 95 CharUnits offset) override; 96 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 97 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, 98 CharUnits ThisAdjustment); 99 100 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 101 llvm::Value *L, llvm::Value *R, 102 const MemberPointerType *MPT, 103 bool Inequality) override; 104 105 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 106 llvm::Value *Addr, 107 const MemberPointerType *MPT) override; 108 109 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr, 110 QualType type) override; 111 112 void EmitFundamentalRTTIDescriptor(QualType Type); 113 void EmitFundamentalRTTIDescriptors(); 114 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 115 116 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 117 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 118 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 119 llvm::Value *ThisPtr, 120 llvm::Type *StdTypeInfoPtrTy) override; 121 122 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 123 QualType SrcRecordTy) override; 124 125 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value, 126 QualType SrcRecordTy, QualType DestTy, 127 QualType DestRecordTy, 128 llvm::BasicBlock *CastEnd) override; 129 130 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 131 QualType SrcRecordTy, 132 QualType DestTy) override; 133 134 bool EmitBadCastCall(CodeGenFunction &CGF) override; 135 136 llvm::Value * 137 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This, 138 const CXXRecordDecl *ClassDecl, 139 const CXXRecordDecl *BaseClassDecl) override; 140 141 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 142 143 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 144 SmallVectorImpl<CanQualType> &ArgTys) override; 145 146 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 147 CXXDtorType DT) const override { 148 // Itanium does not emit any destructor variant as an inline thunk. 149 // Delegating may occur as an optimization, but all variants are either 150 // emitted with external linkage or as linkonce if they are inline and used. 151 return false; 152 } 153 154 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 155 156 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 157 FunctionArgList &Params) override; 158 159 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 160 161 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 162 const CXXConstructorDecl *D, 163 CXXCtorType Type, bool ForVirtualBase, 164 bool Delegating, 165 CallArgList &Args) override; 166 167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 168 CXXDtorType Type, bool ForVirtualBase, 169 bool Delegating, llvm::Value *This) override; 170 171 void emitVTableDefinitions(CodeGenVTables &CGVT, 172 const CXXRecordDecl *RD) override; 173 174 llvm::Value *getVTableAddressPointInStructor( 175 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 176 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 177 bool &NeedsVirtualOffset) override; 178 179 llvm::Constant * 180 getVTableAddressPointForConstExpr(BaseSubobject Base, 181 const CXXRecordDecl *VTableClass) override; 182 183 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 184 CharUnits VPtrOffset) override; 185 186 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 187 llvm::Value *This, 188 llvm::Type *Ty) override; 189 190 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 191 const CXXDestructorDecl *Dtor, 192 CXXDtorType DtorType, llvm::Value *This, 193 const CXXMemberCallExpr *CE) override; 194 195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 196 197 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, 198 bool ReturnAdjustment) override { 199 // Allow inlining of thunks by emitting them with available_externally 200 // linkage together with vtables when needed. 201 if (ForVTable) 202 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 203 } 204 205 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 206 const ThisAdjustment &TA) override; 207 208 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 209 const ReturnAdjustment &RA) override; 210 211 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, 212 FunctionArgList &Args) const override { 213 assert(!Args.empty() && "expected the arglist to not be empty!"); 214 return Args.size() - 1; 215 } 216 217 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; } 218 StringRef GetDeletedVirtualCallName() override 219 { return "__cxa_deleted_virtual"; } 220 221 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 222 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 223 llvm::Value *NewPtr, 224 llvm::Value *NumElements, 225 const CXXNewExpr *expr, 226 QualType ElementType) override; 227 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 228 llvm::Value *allocPtr, 229 CharUnits cookieSize) override; 230 231 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 232 llvm::GlobalVariable *DeclPtr, 233 bool PerformInit) override; 234 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 235 llvm::Constant *dtor, llvm::Constant *addr) override; 236 237 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, 238 llvm::Value *Val); 239 void EmitThreadLocalInitFuncs( 240 CodeGenModule &CGM, 241 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>> 242 CXXThreadLocals, 243 ArrayRef<llvm::Function *> CXXThreadLocalInits, 244 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override; 245 246 bool usesThreadWrapperFunction() const override { return true; } 247 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, 248 QualType LValType) override; 249 250 bool NeedsVTTParameter(GlobalDecl GD) override; 251 252 /**************************** RTTI Uniqueness ******************************/ 253 254 protected: 255 /// Returns true if the ABI requires RTTI type_info objects to be unique 256 /// across a program. 257 virtual bool shouldRTTIBeUnique() const { return true; } 258 259 public: 260 /// What sort of unique-RTTI behavior should we use? 261 enum RTTIUniquenessKind { 262 /// We are guaranteeing, or need to guarantee, that the RTTI string 263 /// is unique. 264 RUK_Unique, 265 266 /// We are not guaranteeing uniqueness for the RTTI string, so we 267 /// can demote to hidden visibility but must use string comparisons. 268 RUK_NonUniqueHidden, 269 270 /// We are not guaranteeing uniqueness for the RTTI string, so we 271 /// have to use string comparisons, but we also have to emit it with 272 /// non-hidden visibility. 273 RUK_NonUniqueVisible 274 }; 275 276 /// Return the required visibility status for the given type and linkage in 277 /// the current ABI. 278 RTTIUniquenessKind 279 classifyRTTIUniqueness(QualType CanTy, 280 llvm::GlobalValue::LinkageTypes Linkage) const; 281 friend class ItaniumRTTIBuilder; 282 283 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; 284 }; 285 286 class ARMCXXABI : public ItaniumCXXABI { 287 public: 288 ARMCXXABI(CodeGen::CodeGenModule &CGM) : 289 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 290 /* UseARMGuardVarABI = */ true) {} 291 292 bool HasThisReturn(GlobalDecl GD) const override { 293 return (isa<CXXConstructorDecl>(GD.getDecl()) || ( 294 isa<CXXDestructorDecl>(GD.getDecl()) && 295 GD.getDtorType() != Dtor_Deleting)); 296 } 297 298 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, 299 QualType ResTy) override; 300 301 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 302 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 303 llvm::Value *NewPtr, 304 llvm::Value *NumElements, 305 const CXXNewExpr *expr, 306 QualType ElementType) override; 307 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr, 308 CharUnits cookieSize) override; 309 }; 310 311 class iOS64CXXABI : public ARMCXXABI { 312 public: 313 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {} 314 315 // ARM64 libraries are prepared for non-unique RTTI. 316 bool shouldRTTIBeUnique() const override { return false; } 317 }; 318 } 319 320 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 321 switch (CGM.getTarget().getCXXABI().getKind()) { 322 // For IR-generation purposes, there's no significant difference 323 // between the ARM and iOS ABIs. 324 case TargetCXXABI::GenericARM: 325 case TargetCXXABI::iOS: 326 return new ARMCXXABI(CGM); 327 328 case TargetCXXABI::iOS64: 329 return new iOS64CXXABI(CGM); 330 331 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't 332 // include the other 32-bit ARM oddities: constructor/destructor return values 333 // and array cookies. 334 case TargetCXXABI::GenericAArch64: 335 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 336 /* UseARMGuardVarABI = */ true); 337 338 case TargetCXXABI::GenericItanium: 339 if (CGM.getContext().getTargetInfo().getTriple().getArch() 340 == llvm::Triple::le32) { 341 // For PNaCl, use ARM-style method pointers so that PNaCl code 342 // does not assume anything about the alignment of function 343 // pointers. 344 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 345 /* UseARMGuardVarABI = */ false); 346 } 347 return new ItaniumCXXABI(CGM); 348 349 case TargetCXXABI::Microsoft: 350 llvm_unreachable("Microsoft ABI is not Itanium-based"); 351 } 352 llvm_unreachable("bad ABI kind"); 353 } 354 355 llvm::Type * 356 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 357 if (MPT->isMemberDataPointer()) 358 return CGM.PtrDiffTy; 359 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL); 360 } 361 362 /// In the Itanium and ARM ABIs, method pointers have the form: 363 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 364 /// 365 /// In the Itanium ABI: 366 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero 367 /// - the this-adjustment is (memptr.adj) 368 /// - the virtual offset is (memptr.ptr - 1) 369 /// 370 /// In the ARM ABI: 371 /// - method pointers are virtual if (memptr.adj & 1) is nonzero 372 /// - the this-adjustment is (memptr.adj >> 1) 373 /// - the virtual offset is (memptr.ptr) 374 /// ARM uses 'adj' for the virtual flag because Thumb functions 375 /// may be only single-byte aligned. 376 /// 377 /// If the member is virtual, the adjusted 'this' pointer points 378 /// to a vtable pointer from which the virtual offset is applied. 379 /// 380 /// If the member is non-virtual, memptr.ptr is the address of 381 /// the function to call. 382 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer( 383 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This, 384 llvm::Value *MemFnPtr, const MemberPointerType *MPT) { 385 CGBuilderTy &Builder = CGF.Builder; 386 387 const FunctionProtoType *FPT = 388 MPT->getPointeeType()->getAs<FunctionProtoType>(); 389 const CXXRecordDecl *RD = 390 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 391 392 llvm::FunctionType *FTy = 393 CGM.getTypes().GetFunctionType( 394 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 395 396 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); 397 398 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 399 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 400 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 401 402 // Extract memptr.adj, which is in the second field. 403 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 404 405 // Compute the true adjustment. 406 llvm::Value *Adj = RawAdj; 407 if (UseARMMethodPtrABI) 408 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 409 410 // Apply the adjustment and cast back to the original struct type 411 // for consistency. 412 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 413 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 414 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 415 416 // Load the function pointer. 417 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 418 419 // If the LSB in the function pointer is 1, the function pointer points to 420 // a virtual function. 421 llvm::Value *IsVirtual; 422 if (UseARMMethodPtrABI) 423 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 424 else 425 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 426 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 427 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 428 429 // In the virtual path, the adjustment left 'This' pointing to the 430 // vtable of the correct base subobject. The "function pointer" is an 431 // offset within the vtable (+1 for the virtual flag on non-ARM). 432 CGF.EmitBlock(FnVirtual); 433 434 // Cast the adjusted this to a pointer to vtable pointer and load. 435 llvm::Type *VTableTy = Builder.getInt8PtrTy(); 436 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy); 437 438 // Apply the offset. 439 llvm::Value *VTableOffset = FnAsInt; 440 if (!UseARMMethodPtrABI) 441 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 442 VTable = Builder.CreateGEP(VTable, VTableOffset); 443 444 // Load the virtual function to call. 445 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 446 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn"); 447 CGF.EmitBranch(FnEnd); 448 449 // In the non-virtual path, the function pointer is actually a 450 // function pointer. 451 CGF.EmitBlock(FnNonVirtual); 452 llvm::Value *NonVirtualFn = 453 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 454 455 // We're done. 456 CGF.EmitBlock(FnEnd); 457 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2); 458 Callee->addIncoming(VirtualFn, FnVirtual); 459 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 460 return Callee; 461 } 462 463 /// Compute an l-value by applying the given pointer-to-member to a 464 /// base object. 465 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress( 466 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr, 467 const MemberPointerType *MPT) { 468 assert(MemPtr->getType() == CGM.PtrDiffTy); 469 470 CGBuilderTy &Builder = CGF.Builder; 471 472 unsigned AS = Base->getType()->getPointerAddressSpace(); 473 474 // Cast to char*. 475 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 476 477 // Apply the offset, which we assume is non-null. 478 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset"); 479 480 // Cast the address to the appropriate pointer type, adopting the 481 // address space of the base pointer. 482 llvm::Type *PType 483 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 484 return Builder.CreateBitCast(Addr, PType); 485 } 486 487 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer 488 /// conversion. 489 /// 490 /// Bitcast conversions are always a no-op under Itanium. 491 /// 492 /// Obligatory offset/adjustment diagram: 493 /// <-- offset --> <-- adjustment --> 494 /// |--------------------------|----------------------|--------------------| 495 /// ^Derived address point ^Base address point ^Member address point 496 /// 497 /// So when converting a base member pointer to a derived member pointer, 498 /// we add the offset to the adjustment because the address point has 499 /// decreased; and conversely, when converting a derived MP to a base MP 500 /// we subtract the offset from the adjustment because the address point 501 /// has increased. 502 /// 503 /// The standard forbids (at compile time) conversion to and from 504 /// virtual bases, which is why we don't have to consider them here. 505 /// 506 /// The standard forbids (at run time) casting a derived MP to a base 507 /// MP when the derived MP does not point to a member of the base. 508 /// This is why -1 is a reasonable choice for null data member 509 /// pointers. 510 llvm::Value * 511 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 512 const CastExpr *E, 513 llvm::Value *src) { 514 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 515 E->getCastKind() == CK_BaseToDerivedMemberPointer || 516 E->getCastKind() == CK_ReinterpretMemberPointer); 517 518 // Under Itanium, reinterprets don't require any additional processing. 519 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 520 521 // Use constant emission if we can. 522 if (isa<llvm::Constant>(src)) 523 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src)); 524 525 llvm::Constant *adj = getMemberPointerAdjustment(E); 526 if (!adj) return src; 527 528 CGBuilderTy &Builder = CGF.Builder; 529 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 530 531 const MemberPointerType *destTy = 532 E->getType()->castAs<MemberPointerType>(); 533 534 // For member data pointers, this is just a matter of adding the 535 // offset if the source is non-null. 536 if (destTy->isMemberDataPointer()) { 537 llvm::Value *dst; 538 if (isDerivedToBase) 539 dst = Builder.CreateNSWSub(src, adj, "adj"); 540 else 541 dst = Builder.CreateNSWAdd(src, adj, "adj"); 542 543 // Null check. 544 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); 545 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); 546 return Builder.CreateSelect(isNull, src, dst); 547 } 548 549 // The this-adjustment is left-shifted by 1 on ARM. 550 if (UseARMMethodPtrABI) { 551 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 552 offset <<= 1; 553 adj = llvm::ConstantInt::get(adj->getType(), offset); 554 } 555 556 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); 557 llvm::Value *dstAdj; 558 if (isDerivedToBase) 559 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); 560 else 561 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); 562 563 return Builder.CreateInsertValue(src, dstAdj, 1); 564 } 565 566 llvm::Constant * 567 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, 568 llvm::Constant *src) { 569 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 570 E->getCastKind() == CK_BaseToDerivedMemberPointer || 571 E->getCastKind() == CK_ReinterpretMemberPointer); 572 573 // Under Itanium, reinterprets don't require any additional processing. 574 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 575 576 // If the adjustment is trivial, we don't need to do anything. 577 llvm::Constant *adj = getMemberPointerAdjustment(E); 578 if (!adj) return src; 579 580 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 581 582 const MemberPointerType *destTy = 583 E->getType()->castAs<MemberPointerType>(); 584 585 // For member data pointers, this is just a matter of adding the 586 // offset if the source is non-null. 587 if (destTy->isMemberDataPointer()) { 588 // null maps to null. 589 if (src->isAllOnesValue()) return src; 590 591 if (isDerivedToBase) 592 return llvm::ConstantExpr::getNSWSub(src, adj); 593 else 594 return llvm::ConstantExpr::getNSWAdd(src, adj); 595 } 596 597 // The this-adjustment is left-shifted by 1 on ARM. 598 if (UseARMMethodPtrABI) { 599 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 600 offset <<= 1; 601 adj = llvm::ConstantInt::get(adj->getType(), offset); 602 } 603 604 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); 605 llvm::Constant *dstAdj; 606 if (isDerivedToBase) 607 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); 608 else 609 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); 610 611 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); 612 } 613 614 llvm::Constant * 615 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 616 // Itanium C++ ABI 2.3: 617 // A NULL pointer is represented as -1. 618 if (MPT->isMemberDataPointer()) 619 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); 620 621 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); 622 llvm::Constant *Values[2] = { Zero, Zero }; 623 return llvm::ConstantStruct::getAnon(Values); 624 } 625 626 llvm::Constant * 627 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 628 CharUnits offset) { 629 // Itanium C++ ABI 2.3: 630 // A pointer to data member is an offset from the base address of 631 // the class object containing it, represented as a ptrdiff_t 632 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); 633 } 634 635 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 636 return BuildMemberPointer(MD, CharUnits::Zero()); 637 } 638 639 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, 640 CharUnits ThisAdjustment) { 641 assert(MD->isInstance() && "Member function must not be static!"); 642 MD = MD->getCanonicalDecl(); 643 644 CodeGenTypes &Types = CGM.getTypes(); 645 646 // Get the function pointer (or index if this is a virtual function). 647 llvm::Constant *MemPtr[2]; 648 if (MD->isVirtual()) { 649 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD); 650 651 const ASTContext &Context = getContext(); 652 CharUnits PointerWidth = 653 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 654 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 655 656 if (UseARMMethodPtrABI) { 657 // ARM C++ ABI 3.2.1: 658 // This ABI specifies that adj contains twice the this 659 // adjustment, plus 1 if the member function is virtual. The 660 // least significant bit of adj then makes exactly the same 661 // discrimination as the least significant bit of ptr does for 662 // Itanium. 663 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); 664 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 665 2 * ThisAdjustment.getQuantity() + 1); 666 } else { 667 // Itanium C++ ABI 2.3: 668 // For a virtual function, [the pointer field] is 1 plus the 669 // virtual table offset (in bytes) of the function, 670 // represented as a ptrdiff_t. 671 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); 672 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 673 ThisAdjustment.getQuantity()); 674 } 675 } else { 676 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 677 llvm::Type *Ty; 678 // Check whether the function has a computable LLVM signature. 679 if (Types.isFuncTypeConvertible(FPT)) { 680 // The function has a computable LLVM signature; use the correct type. 681 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 682 } else { 683 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 684 // function type is incomplete. 685 Ty = CGM.PtrDiffTy; 686 } 687 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 688 689 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); 690 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 691 (UseARMMethodPtrABI ? 2 : 1) * 692 ThisAdjustment.getQuantity()); 693 } 694 695 return llvm::ConstantStruct::getAnon(MemPtr); 696 } 697 698 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, 699 QualType MPType) { 700 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 701 const ValueDecl *MPD = MP.getMemberPointerDecl(); 702 if (!MPD) 703 return EmitNullMemberPointer(MPT); 704 705 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 706 707 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 708 return BuildMemberPointer(MD, ThisAdjustment); 709 710 CharUnits FieldOffset = 711 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 712 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 713 } 714 715 /// The comparison algorithm is pretty easy: the member pointers are 716 /// the same if they're either bitwise identical *or* both null. 717 /// 718 /// ARM is different here only because null-ness is more complicated. 719 llvm::Value * 720 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 721 llvm::Value *L, 722 llvm::Value *R, 723 const MemberPointerType *MPT, 724 bool Inequality) { 725 CGBuilderTy &Builder = CGF.Builder; 726 727 llvm::ICmpInst::Predicate Eq; 728 llvm::Instruction::BinaryOps And, Or; 729 if (Inequality) { 730 Eq = llvm::ICmpInst::ICMP_NE; 731 And = llvm::Instruction::Or; 732 Or = llvm::Instruction::And; 733 } else { 734 Eq = llvm::ICmpInst::ICMP_EQ; 735 And = llvm::Instruction::And; 736 Or = llvm::Instruction::Or; 737 } 738 739 // Member data pointers are easy because there's a unique null 740 // value, so it just comes down to bitwise equality. 741 if (MPT->isMemberDataPointer()) 742 return Builder.CreateICmp(Eq, L, R); 743 744 // For member function pointers, the tautologies are more complex. 745 // The Itanium tautology is: 746 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 747 // The ARM tautology is: 748 // (L == R) <==> (L.ptr == R.ptr && 749 // (L.adj == R.adj || 750 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 751 // The inequality tautologies have exactly the same structure, except 752 // applying De Morgan's laws. 753 754 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 755 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 756 757 // This condition tests whether L.ptr == R.ptr. This must always be 758 // true for equality to hold. 759 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 760 761 // This condition, together with the assumption that L.ptr == R.ptr, 762 // tests whether the pointers are both null. ARM imposes an extra 763 // condition. 764 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 765 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 766 767 // This condition tests whether L.adj == R.adj. If this isn't 768 // true, the pointers are unequal unless they're both null. 769 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 770 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 771 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 772 773 // Null member function pointers on ARM clear the low bit of Adj, 774 // so the zero condition has to check that neither low bit is set. 775 if (UseARMMethodPtrABI) { 776 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 777 778 // Compute (l.adj | r.adj) & 1 and test it against zero. 779 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 780 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 781 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 782 "cmp.or.adj"); 783 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 784 } 785 786 // Tie together all our conditions. 787 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 788 Result = Builder.CreateBinOp(And, PtrEq, Result, 789 Inequality ? "memptr.ne" : "memptr.eq"); 790 return Result; 791 } 792 793 llvm::Value * 794 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 795 llvm::Value *MemPtr, 796 const MemberPointerType *MPT) { 797 CGBuilderTy &Builder = CGF.Builder; 798 799 /// For member data pointers, this is just a check against -1. 800 if (MPT->isMemberDataPointer()) { 801 assert(MemPtr->getType() == CGM.PtrDiffTy); 802 llvm::Value *NegativeOne = 803 llvm::Constant::getAllOnesValue(MemPtr->getType()); 804 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 805 } 806 807 // In Itanium, a member function pointer is not null if 'ptr' is not null. 808 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 809 810 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 811 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 812 813 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 814 // (the virtual bit) is set. 815 if (UseARMMethodPtrABI) { 816 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 817 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 818 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 819 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 820 "memptr.isvirtual"); 821 Result = Builder.CreateOr(Result, IsVirtual); 822 } 823 824 return Result; 825 } 826 827 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 828 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 829 if (!RD) 830 return false; 831 832 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor. 833 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared 834 // special members. 835 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) { 836 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 837 return true; 838 } 839 return false; 840 } 841 842 /// The Itanium ABI requires non-zero initialization only for data 843 /// member pointers, for which '0' is a valid offset. 844 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 845 return MPT->getPointeeType()->isFunctionType(); 846 } 847 848 /// The Itanium ABI always places an offset to the complete object 849 /// at entry -2 in the vtable. 850 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 851 llvm::Value *ptr, 852 QualType type) { 853 // Grab the vtable pointer as an intptr_t*. 854 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo()); 855 856 // Track back to entry -2 and pull out the offset there. 857 llvm::Value *offsetPtr = 858 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr"); 859 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr); 860 offset->setAlignment(CGF.PointerAlignInBytes); 861 862 // Apply the offset. 863 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy); 864 return CGF.Builder.CreateInBoundsGEP(ptr, offset); 865 } 866 867 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) { 868 // void *__dynamic_cast(const void *sub, 869 // const abi::__class_type_info *src, 870 // const abi::__class_type_info *dst, 871 // std::ptrdiff_t src2dst_offset); 872 873 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 874 llvm::Type *PtrDiffTy = 875 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 876 877 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy }; 878 879 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false); 880 881 // Mark the function as nounwind readonly. 882 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind, 883 llvm::Attribute::ReadOnly }; 884 llvm::AttributeSet Attrs = llvm::AttributeSet::get( 885 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs); 886 887 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs); 888 } 889 890 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) { 891 // void __cxa_bad_cast(); 892 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 893 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast"); 894 } 895 896 /// \brief Compute the src2dst_offset hint as described in the 897 /// Itanium C++ ABI [2.9.7] 898 static CharUnits computeOffsetHint(ASTContext &Context, 899 const CXXRecordDecl *Src, 900 const CXXRecordDecl *Dst) { 901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 902 /*DetectVirtual=*/false); 903 904 // If Dst is not derived from Src we can skip the whole computation below and 905 // return that Src is not a public base of Dst. Record all inheritance paths. 906 if (!Dst->isDerivedFrom(Src, Paths)) 907 return CharUnits::fromQuantity(-2ULL); 908 909 unsigned NumPublicPaths = 0; 910 CharUnits Offset; 911 912 // Now walk all possible inheritance paths. 913 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E; 914 ++I) { 915 if (I->Access != AS_public) // Ignore non-public inheritance. 916 continue; 917 918 ++NumPublicPaths; 919 920 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) { 921 // If the path contains a virtual base class we can't give any hint. 922 // -1: no hint. 923 if (J->Base->isVirtual()) 924 return CharUnits::fromQuantity(-1ULL); 925 926 if (NumPublicPaths > 1) // Won't use offsets, skip computation. 927 continue; 928 929 // Accumulate the base class offsets. 930 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class); 931 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl()); 932 } 933 } 934 935 // -2: Src is not a public base of Dst. 936 if (NumPublicPaths == 0) 937 return CharUnits::fromQuantity(-2ULL); 938 939 // -3: Src is a multiple public base type but never a virtual base type. 940 if (NumPublicPaths > 1) 941 return CharUnits::fromQuantity(-3ULL); 942 943 // Otherwise, the Src type is a unique public nonvirtual base type of Dst. 944 // Return the offset of Src from the origin of Dst. 945 return Offset; 946 } 947 948 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) { 949 // void __cxa_bad_typeid(); 950 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 951 952 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid"); 953 } 954 955 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 956 QualType SrcRecordTy) { 957 return IsDeref; 958 } 959 960 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 961 llvm::Value *Fn = getBadTypeidFn(CGF); 962 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 963 CGF.Builder.CreateUnreachable(); 964 } 965 966 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF, 967 QualType SrcRecordTy, 968 llvm::Value *ThisPtr, 969 llvm::Type *StdTypeInfoPtrTy) { 970 llvm::Value *Value = 971 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo()); 972 973 // Load the type info. 974 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL); 975 return CGF.Builder.CreateLoad(Value); 976 } 977 978 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 979 QualType SrcRecordTy) { 980 return SrcIsPtr; 981 } 982 983 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall( 984 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy, 985 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 986 llvm::Type *PtrDiffLTy = 987 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 988 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 989 990 llvm::Value *SrcRTTI = 991 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 992 llvm::Value *DestRTTI = 993 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 994 995 // Compute the offset hint. 996 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 997 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl(); 998 llvm::Value *OffsetHint = llvm::ConstantInt::get( 999 PtrDiffLTy, 1000 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity()); 1001 1002 // Emit the call to __dynamic_cast. 1003 Value = CGF.EmitCastToVoidPtr(Value); 1004 1005 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint}; 1006 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args); 1007 Value = CGF.Builder.CreateBitCast(Value, DestLTy); 1008 1009 /// C++ [expr.dynamic.cast]p9: 1010 /// A failed cast to reference type throws std::bad_cast 1011 if (DestTy->isReferenceType()) { 1012 llvm::BasicBlock *BadCastBlock = 1013 CGF.createBasicBlock("dynamic_cast.bad_cast"); 1014 1015 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value); 1016 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd); 1017 1018 CGF.EmitBlock(BadCastBlock); 1019 EmitBadCastCall(CGF); 1020 } 1021 1022 return Value; 1023 } 1024 1025 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, 1026 llvm::Value *Value, 1027 QualType SrcRecordTy, 1028 QualType DestTy) { 1029 llvm::Type *PtrDiffLTy = 1030 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1031 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1032 1033 // Get the vtable pointer. 1034 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo()); 1035 1036 // Get the offset-to-top from the vtable. 1037 llvm::Value *OffsetToTop = 1038 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL); 1039 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top"); 1040 1041 // Finally, add the offset to the pointer. 1042 Value = CGF.EmitCastToVoidPtr(Value); 1043 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop); 1044 1045 return CGF.Builder.CreateBitCast(Value, DestLTy); 1046 } 1047 1048 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 1049 llvm::Value *Fn = getBadCastFn(CGF); 1050 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 1051 CGF.Builder.CreateUnreachable(); 1052 return true; 1053 } 1054 1055 llvm::Value * 1056 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 1057 llvm::Value *This, 1058 const CXXRecordDecl *ClassDecl, 1059 const CXXRecordDecl *BaseClassDecl) { 1060 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy); 1061 CharUnits VBaseOffsetOffset = 1062 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl, 1063 BaseClassDecl); 1064 1065 llvm::Value *VBaseOffsetPtr = 1066 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1067 "vbase.offset.ptr"); 1068 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, 1069 CGM.PtrDiffTy->getPointerTo()); 1070 1071 llvm::Value *VBaseOffset = 1072 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 1073 1074 return VBaseOffset; 1075 } 1076 1077 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 1078 // Just make sure we're in sync with TargetCXXABI. 1079 assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); 1080 1081 // The constructor used for constructing this as a base class; 1082 // ignores virtual bases. 1083 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); 1084 1085 // The constructor used for constructing this as a complete class; 1086 // constucts the virtual bases, then calls the base constructor. 1087 if (!D->getParent()->isAbstract()) { 1088 // We don't need to emit the complete ctor if the class is abstract. 1089 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 1090 } 1091 } 1092 1093 void 1094 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 1095 SmallVectorImpl<CanQualType> &ArgTys) { 1096 ASTContext &Context = getContext(); 1097 1098 // All parameters are already in place except VTT, which goes after 'this'. 1099 // These are Clang types, so we don't need to worry about sret yet. 1100 1101 // Check if we need to add a VTT parameter (which has type void **). 1102 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) 1103 ArgTys.insert(ArgTys.begin() + 1, 1104 Context.getPointerType(Context.VoidPtrTy)); 1105 } 1106 1107 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 1108 // The destructor used for destructing this as a base class; ignores 1109 // virtual bases. 1110 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 1111 1112 // The destructor used for destructing this as a most-derived class; 1113 // call the base destructor and then destructs any virtual bases. 1114 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 1115 1116 // The destructor in a virtual table is always a 'deleting' 1117 // destructor, which calls the complete destructor and then uses the 1118 // appropriate operator delete. 1119 if (D->isVirtual()) 1120 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 1121 } 1122 1123 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1124 QualType &ResTy, 1125 FunctionArgList &Params) { 1126 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1127 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1128 1129 // Check if we need a VTT parameter as well. 1130 if (NeedsVTTParameter(CGF.CurGD)) { 1131 ASTContext &Context = getContext(); 1132 1133 // FIXME: avoid the fake decl 1134 QualType T = Context.getPointerType(Context.VoidPtrTy); 1135 ImplicitParamDecl *VTTDecl 1136 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(), 1137 &Context.Idents.get("vtt"), T); 1138 Params.insert(Params.begin() + 1, VTTDecl); 1139 getStructorImplicitParamDecl(CGF) = VTTDecl; 1140 } 1141 } 1142 1143 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1144 /// Initialize the 'this' slot. 1145 EmitThisParam(CGF); 1146 1147 /// Initialize the 'vtt' slot if needed. 1148 if (getStructorImplicitParamDecl(CGF)) { 1149 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad( 1150 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt"); 1151 } 1152 1153 /// If this is a function that the ABI specifies returns 'this', initialize 1154 /// the return slot to 'this' at the start of the function. 1155 /// 1156 /// Unlike the setting of return types, this is done within the ABI 1157 /// implementation instead of by clients of CGCXXABI because: 1158 /// 1) getThisValue is currently protected 1159 /// 2) in theory, an ABI could implement 'this' returns some other way; 1160 /// HasThisReturn only specifies a contract, not the implementation 1161 if (HasThisReturn(CGF.CurGD)) 1162 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1163 } 1164 1165 unsigned ItaniumCXXABI::addImplicitConstructorArgs( 1166 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1167 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1168 if (!NeedsVTTParameter(GlobalDecl(D, Type))) 1169 return 0; 1170 1171 // Insert the implicit 'vtt' argument as the second argument. 1172 llvm::Value *VTT = 1173 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating); 1174 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1175 Args.insert(Args.begin() + 1, 1176 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false)); 1177 return 1; // Added one arg. 1178 } 1179 1180 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1181 const CXXDestructorDecl *DD, 1182 CXXDtorType Type, bool ForVirtualBase, 1183 bool Delegating, llvm::Value *This) { 1184 GlobalDecl GD(DD, Type); 1185 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating); 1186 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1187 1188 llvm::Value *Callee = nullptr; 1189 if (getContext().getLangOpts().AppleKext) 1190 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent()); 1191 1192 if (!Callee) 1193 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)); 1194 1195 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT, 1196 VTTTy, nullptr); 1197 } 1198 1199 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1200 const CXXRecordDecl *RD) { 1201 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits()); 1202 if (VTable->hasInitializer()) 1203 return; 1204 1205 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1206 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); 1207 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1208 llvm::Constant *RTTI = 1209 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD)); 1210 1211 // Create and set the initializer. 1212 llvm::Constant *Init = CGVT.CreateVTableInitializer( 1213 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(), 1214 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI); 1215 VTable->setInitializer(Init); 1216 1217 // Set the correct linkage. 1218 VTable->setLinkage(Linkage); 1219 1220 // Set the right visibility. 1221 CGM.setGlobalVisibility(VTable, RD); 1222 1223 // Use pointer alignment for the vtable. Otherwise we would align them based 1224 // on the size of the initializer which doesn't make sense as only single 1225 // values are read. 1226 unsigned PAlign = CGM.getTarget().getPointerAlign(0); 1227 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity()); 1228 1229 // If this is the magic class __cxxabiv1::__fundamental_type_info, 1230 // we will emit the typeinfo for the fundamental types. This is the 1231 // same behaviour as GCC. 1232 const DeclContext *DC = RD->getDeclContext(); 1233 if (RD->getIdentifier() && 1234 RD->getIdentifier()->isStr("__fundamental_type_info") && 1235 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() && 1236 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 1237 DC->getParent()->isTranslationUnit()) 1238 EmitFundamentalRTTIDescriptors(); 1239 } 1240 1241 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor( 1242 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1243 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 1244 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD); 1245 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase); 1246 1247 llvm::Value *VTableAddressPoint; 1248 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) { 1249 // Get the secondary vpointer index. 1250 uint64_t VirtualPointerIndex = 1251 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1252 1253 /// Load the VTT. 1254 llvm::Value *VTT = CGF.LoadCXXVTT(); 1255 if (VirtualPointerIndex) 1256 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1257 1258 // And load the address point from the VTT. 1259 VTableAddressPoint = CGF.Builder.CreateLoad(VTT); 1260 } else { 1261 llvm::Constant *VTable = 1262 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits()); 1263 uint64_t AddressPoint = CGM.getItaniumVTableContext() 1264 .getVTableLayout(VTableClass) 1265 .getAddressPoint(Base); 1266 VTableAddressPoint = 1267 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 1268 } 1269 1270 return VTableAddressPoint; 1271 } 1272 1273 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr( 1274 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1275 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits()); 1276 1277 // Find the appropriate vtable within the vtable group. 1278 uint64_t AddressPoint = CGM.getItaniumVTableContext() 1279 .getVTableLayout(VTableClass) 1280 .getAddressPoint(Base); 1281 llvm::Value *Indices[] = { 1282 llvm::ConstantInt::get(CGM.Int64Ty, 0), 1283 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint) 1284 }; 1285 1286 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices); 1287 } 1288 1289 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1290 CharUnits VPtrOffset) { 1291 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets"); 1292 1293 llvm::GlobalVariable *&VTable = VTables[RD]; 1294 if (VTable) 1295 return VTable; 1296 1297 // Queue up this v-table for possible deferred emission. 1298 CGM.addDeferredVTable(RD); 1299 1300 SmallString<256> OutName; 1301 llvm::raw_svector_ostream Out(OutName); 1302 getMangleContext().mangleCXXVTable(RD, Out); 1303 Out.flush(); 1304 StringRef Name = OutName.str(); 1305 1306 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1307 llvm::ArrayType *ArrayType = llvm::ArrayType::get( 1308 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents()); 1309 1310 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 1311 Name, ArrayType, llvm::GlobalValue::ExternalLinkage); 1312 VTable->setUnnamedAddr(true); 1313 1314 if (RD->hasAttr<DLLImportAttr>()) 1315 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1316 else if (RD->hasAttr<DLLExportAttr>()) 1317 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1318 1319 return VTable; 1320 } 1321 1322 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1323 GlobalDecl GD, 1324 llvm::Value *This, 1325 llvm::Type *Ty) { 1326 GD = GD.getCanonicalDecl(); 1327 Ty = Ty->getPointerTo()->getPointerTo(); 1328 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty); 1329 1330 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 1331 llvm::Value *VFuncPtr = 1332 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); 1333 return CGF.Builder.CreateLoad(VFuncPtr); 1334 } 1335 1336 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 1337 const CXXDestructorDecl *Dtor, 1338 CXXDtorType DtorType, 1339 llvm::Value *This, 1340 const CXXMemberCallExpr *CE) { 1341 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1342 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1343 1344 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 1345 Dtor, getFromDtorType(DtorType)); 1346 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1347 llvm::Value *Callee = 1348 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty); 1349 1350 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This, 1351 /*ImplicitParam=*/nullptr, QualType(), CE); 1352 } 1353 1354 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1355 CodeGenVTables &VTables = CGM.getVTables(); 1356 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); 1357 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD); 1358 } 1359 1360 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF, 1361 llvm::Value *Ptr, 1362 int64_t NonVirtualAdjustment, 1363 int64_t VirtualAdjustment, 1364 bool IsReturnAdjustment) { 1365 if (!NonVirtualAdjustment && !VirtualAdjustment) 1366 return Ptr; 1367 1368 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 1369 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy); 1370 1371 if (NonVirtualAdjustment && !IsReturnAdjustment) { 1372 // Perform the non-virtual adjustment for a base-to-derived cast. 1373 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 1374 } 1375 1376 if (VirtualAdjustment) { 1377 llvm::Type *PtrDiffTy = 1378 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1379 1380 // Perform the virtual adjustment. 1381 llvm::Value *VTablePtrPtr = 1382 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo()); 1383 1384 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 1385 1386 llvm::Value *OffsetPtr = 1387 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 1388 1389 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 1390 1391 // Load the adjustment offset from the vtable. 1392 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr); 1393 1394 // Adjust our pointer. 1395 V = CGF.Builder.CreateInBoundsGEP(V, Offset); 1396 } 1397 1398 if (NonVirtualAdjustment && IsReturnAdjustment) { 1399 // Perform the non-virtual adjustment for a derived-to-base cast. 1400 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 1401 } 1402 1403 // Cast back to the original type. 1404 return CGF.Builder.CreateBitCast(V, Ptr->getType()); 1405 } 1406 1407 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1408 llvm::Value *This, 1409 const ThisAdjustment &TA) { 1410 return performTypeAdjustment(CGF, This, TA.NonVirtual, 1411 TA.Virtual.Itanium.VCallOffsetOffset, 1412 /*IsReturnAdjustment=*/false); 1413 } 1414 1415 llvm::Value * 1416 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1417 const ReturnAdjustment &RA) { 1418 return performTypeAdjustment(CGF, Ret, RA.NonVirtual, 1419 RA.Virtual.Itanium.VBaseOffsetOffset, 1420 /*IsReturnAdjustment=*/true); 1421 } 1422 1423 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 1424 RValue RV, QualType ResultType) { 1425 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 1426 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 1427 1428 // Destructor thunks in the ARM ABI have indeterminate results. 1429 llvm::Type *T = 1430 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType(); 1431 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 1432 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 1433 } 1434 1435 /************************** Array allocation cookies **************************/ 1436 1437 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1438 // The array cookie is a size_t; pad that up to the element alignment. 1439 // The cookie is actually right-justified in that space. 1440 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), 1441 CGM.getContext().getTypeAlignInChars(elementType)); 1442 } 1443 1444 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1445 llvm::Value *NewPtr, 1446 llvm::Value *NumElements, 1447 const CXXNewExpr *expr, 1448 QualType ElementType) { 1449 assert(requiresArrayCookie(expr)); 1450 1451 unsigned AS = NewPtr->getType()->getPointerAddressSpace(); 1452 1453 ASTContext &Ctx = getContext(); 1454 QualType SizeTy = Ctx.getSizeType(); 1455 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy); 1456 1457 // The size of the cookie. 1458 CharUnits CookieSize = 1459 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 1460 assert(CookieSize == getArrayCookieSizeImpl(ElementType)); 1461 1462 // Compute an offset to the cookie. 1463 llvm::Value *CookiePtr = NewPtr; 1464 CharUnits CookieOffset = CookieSize - SizeSize; 1465 if (!CookieOffset.isZero()) 1466 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr, 1467 CookieOffset.getQuantity()); 1468 1469 // Write the number of elements into the appropriate slot. 1470 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS); 1471 llvm::Value *NumElementsPtr = 1472 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy); 1473 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr); 1474 if (CGM.getLangOpts().Sanitize.Address && AS == 0 && 1475 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) { 1476 // The store to the CookiePtr does not need to be instrumented. 1477 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI); 1478 llvm::FunctionType *FTy = 1479 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false); 1480 llvm::Constant *F = 1481 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie"); 1482 CGF.Builder.CreateCall(F, NumElementsPtr); 1483 } 1484 1485 // Finally, compute a pointer to the actual data buffer by skipping 1486 // over the cookie completely. 1487 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 1488 CookieSize.getQuantity()); 1489 } 1490 1491 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1492 llvm::Value *allocPtr, 1493 CharUnits cookieSize) { 1494 // The element size is right-justified in the cookie. 1495 llvm::Value *numElementsPtr = allocPtr; 1496 CharUnits numElementsOffset = 1497 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes); 1498 if (!numElementsOffset.isZero()) 1499 numElementsPtr = 1500 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr, 1501 numElementsOffset.getQuantity()); 1502 1503 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1504 numElementsPtr = 1505 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1506 if (!CGM.getLangOpts().Sanitize.Address || AS != 0) 1507 return CGF.Builder.CreateLoad(numElementsPtr); 1508 // In asan mode emit a function call instead of a regular load and let the 1509 // run-time deal with it: if the shadow is properly poisoned return the 1510 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs. 1511 // We can't simply ignore this load using nosanitize metadata because 1512 // the metadata may be lost. 1513 llvm::FunctionType *FTy = 1514 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false); 1515 llvm::Constant *F = 1516 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie"); 1517 return CGF.Builder.CreateCall(F, numElementsPtr); 1518 } 1519 1520 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1521 // ARM says that the cookie is always: 1522 // struct array_cookie { 1523 // std::size_t element_size; // element_size != 0 1524 // std::size_t element_count; 1525 // }; 1526 // But the base ABI doesn't give anything an alignment greater than 1527 // 8, so we can dismiss this as typical ABI-author blindness to 1528 // actual language complexity and round up to the element alignment. 1529 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), 1530 CGM.getContext().getTypeAlignInChars(elementType)); 1531 } 1532 1533 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1534 llvm::Value *newPtr, 1535 llvm::Value *numElements, 1536 const CXXNewExpr *expr, 1537 QualType elementType) { 1538 assert(requiresArrayCookie(expr)); 1539 1540 // NewPtr is a char*, but we generalize to arbitrary addrspaces. 1541 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1542 1543 // The cookie is always at the start of the buffer. 1544 llvm::Value *cookie = newPtr; 1545 1546 // The first element is the element size. 1547 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS)); 1548 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, 1549 getContext().getTypeSizeInChars(elementType).getQuantity()); 1550 CGF.Builder.CreateStore(elementSize, cookie); 1551 1552 // The second element is the element count. 1553 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1); 1554 CGF.Builder.CreateStore(numElements, cookie); 1555 1556 // Finally, compute a pointer to the actual data buffer by skipping 1557 // over the cookie completely. 1558 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); 1559 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1560 cookieSize.getQuantity()); 1561 } 1562 1563 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1564 llvm::Value *allocPtr, 1565 CharUnits cookieSize) { 1566 // The number of elements is at offset sizeof(size_t) relative to 1567 // the allocated pointer. 1568 llvm::Value *numElementsPtr 1569 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes); 1570 1571 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1572 numElementsPtr = 1573 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1574 return CGF.Builder.CreateLoad(numElementsPtr); 1575 } 1576 1577 /*********************** Static local initialization **************************/ 1578 1579 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1580 llvm::PointerType *GuardPtrTy) { 1581 // int __cxa_guard_acquire(__guard *guard_object); 1582 llvm::FunctionType *FTy = 1583 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1584 GuardPtrTy, /*isVarArg=*/false); 1585 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire", 1586 llvm::AttributeSet::get(CGM.getLLVMContext(), 1587 llvm::AttributeSet::FunctionIndex, 1588 llvm::Attribute::NoUnwind)); 1589 } 1590 1591 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1592 llvm::PointerType *GuardPtrTy) { 1593 // void __cxa_guard_release(__guard *guard_object); 1594 llvm::FunctionType *FTy = 1595 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1596 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release", 1597 llvm::AttributeSet::get(CGM.getLLVMContext(), 1598 llvm::AttributeSet::FunctionIndex, 1599 llvm::Attribute::NoUnwind)); 1600 } 1601 1602 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1603 llvm::PointerType *GuardPtrTy) { 1604 // void __cxa_guard_abort(__guard *guard_object); 1605 llvm::FunctionType *FTy = 1606 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1607 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort", 1608 llvm::AttributeSet::get(CGM.getLLVMContext(), 1609 llvm::AttributeSet::FunctionIndex, 1610 llvm::Attribute::NoUnwind)); 1611 } 1612 1613 namespace { 1614 struct CallGuardAbort : EHScopeStack::Cleanup { 1615 llvm::GlobalVariable *Guard; 1616 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1617 1618 void Emit(CodeGenFunction &CGF, Flags flags) override { 1619 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), 1620 Guard); 1621 } 1622 }; 1623 } 1624 1625 /// The ARM code here follows the Itanium code closely enough that we 1626 /// just special-case it at particular places. 1627 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1628 const VarDecl &D, 1629 llvm::GlobalVariable *var, 1630 bool shouldPerformInit) { 1631 CGBuilderTy &Builder = CGF.Builder; 1632 1633 // We only need to use thread-safe statics for local non-TLS variables; 1634 // global initialization is always single-threaded. 1635 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && 1636 D.isLocalVarDecl() && !D.getTLSKind(); 1637 1638 // If we have a global variable with internal linkage and thread-safe statics 1639 // are disabled, we can just let the guard variable be of type i8. 1640 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); 1641 1642 llvm::IntegerType *guardTy; 1643 if (useInt8GuardVariable) { 1644 guardTy = CGF.Int8Ty; 1645 } else { 1646 // Guard variables are 64 bits in the generic ABI and size width on ARM 1647 // (i.e. 32-bit on AArch32, 64-bit on AArch64). 1648 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty); 1649 } 1650 llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); 1651 1652 // Create the guard variable if we don't already have it (as we 1653 // might if we're double-emitting this function body). 1654 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); 1655 if (!guard) { 1656 // Mangle the name for the guard. 1657 SmallString<256> guardName; 1658 { 1659 llvm::raw_svector_ostream out(guardName); 1660 getMangleContext().mangleStaticGuardVariable(&D, out); 1661 out.flush(); 1662 } 1663 1664 // Create the guard variable with a zero-initializer. 1665 // Just absorb linkage and visibility from the guarded variable. 1666 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, 1667 false, var->getLinkage(), 1668 llvm::ConstantInt::get(guardTy, 0), 1669 guardName.str()); 1670 guard->setVisibility(var->getVisibility()); 1671 // If the variable is thread-local, so is its guard variable. 1672 guard->setThreadLocalMode(var->getThreadLocalMode()); 1673 1674 // The ABI says: It is suggested that it be emitted in the same COMDAT group 1675 // as the associated data object 1676 if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) { 1677 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName()); 1678 guard->setComdat(C); 1679 var->setComdat(C); 1680 CGF.CurFn->setComdat(C); 1681 } 1682 1683 CGM.setStaticLocalDeclGuardAddress(&D, guard); 1684 } 1685 1686 // Test whether the variable has completed initialization. 1687 // 1688 // Itanium C++ ABI 3.3.2: 1689 // The following is pseudo-code showing how these functions can be used: 1690 // if (obj_guard.first_byte == 0) { 1691 // if ( __cxa_guard_acquire (&obj_guard) ) { 1692 // try { 1693 // ... initialize the object ...; 1694 // } catch (...) { 1695 // __cxa_guard_abort (&obj_guard); 1696 // throw; 1697 // } 1698 // ... queue object destructor with __cxa_atexit() ...; 1699 // __cxa_guard_release (&obj_guard); 1700 // } 1701 // } 1702 1703 // Load the first byte of the guard variable. 1704 llvm::LoadInst *LI = 1705 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy)); 1706 LI->setAlignment(1); 1707 1708 // Itanium ABI: 1709 // An implementation supporting thread-safety on multiprocessor 1710 // systems must also guarantee that references to the initialized 1711 // object do not occur before the load of the initialization flag. 1712 // 1713 // In LLVM, we do this by marking the load Acquire. 1714 if (threadsafe) 1715 LI->setAtomic(llvm::Acquire); 1716 1717 // For ARM, we should only check the first bit, rather than the entire byte: 1718 // 1719 // ARM C++ ABI 3.2.3.1: 1720 // To support the potential use of initialization guard variables 1721 // as semaphores that are the target of ARM SWP and LDREX/STREX 1722 // synchronizing instructions we define a static initialization 1723 // guard variable to be a 4-byte aligned, 4-byte word with the 1724 // following inline access protocol. 1725 // #define INITIALIZED 1 1726 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 1727 // if (__cxa_guard_acquire(&obj_guard)) 1728 // ... 1729 // } 1730 // 1731 // and similarly for ARM64: 1732 // 1733 // ARM64 C++ ABI 3.2.2: 1734 // This ABI instead only specifies the value bit 0 of the static guard 1735 // variable; all other bits are platform defined. Bit 0 shall be 0 when the 1736 // variable is not initialized and 1 when it is. 1737 llvm::Value *V = 1738 (UseARMGuardVarABI && !useInt8GuardVariable) 1739 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1)) 1740 : LI; 1741 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1742 1743 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 1744 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1745 1746 // Check if the first byte of the guard variable is zero. 1747 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock); 1748 1749 CGF.EmitBlock(InitCheckBlock); 1750 1751 // Variables used when coping with thread-safe statics and exceptions. 1752 if (threadsafe) { 1753 // Call __cxa_guard_acquire. 1754 llvm::Value *V 1755 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); 1756 1757 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1758 1759 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 1760 InitBlock, EndBlock); 1761 1762 // Call __cxa_guard_abort along the exceptional edge. 1763 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard); 1764 1765 CGF.EmitBlock(InitBlock); 1766 } 1767 1768 // Emit the initializer and add a global destructor if appropriate. 1769 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); 1770 1771 if (threadsafe) { 1772 // Pop the guard-abort cleanup if we pushed one. 1773 CGF.PopCleanupBlock(); 1774 1775 // Call __cxa_guard_release. This cannot throw. 1776 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard); 1777 } else { 1778 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard); 1779 } 1780 1781 CGF.EmitBlock(EndBlock); 1782 } 1783 1784 /// Register a global destructor using __cxa_atexit. 1785 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, 1786 llvm::Constant *dtor, 1787 llvm::Constant *addr, 1788 bool TLS) { 1789 const char *Name = "__cxa_atexit"; 1790 if (TLS) { 1791 const llvm::Triple &T = CGF.getTarget().getTriple(); 1792 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit"; 1793 } 1794 1795 // We're assuming that the destructor function is something we can 1796 // reasonably call with the default CC. Go ahead and cast it to the 1797 // right prototype. 1798 llvm::Type *dtorTy = 1799 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); 1800 1801 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); 1802 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; 1803 llvm::FunctionType *atexitTy = 1804 llvm::FunctionType::get(CGF.IntTy, paramTys, false); 1805 1806 // Fetch the actual function. 1807 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); 1808 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit)) 1809 fn->setDoesNotThrow(); 1810 1811 // Create a variable that binds the atexit to this shared object. 1812 llvm::Constant *handle = 1813 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); 1814 1815 llvm::Value *args[] = { 1816 llvm::ConstantExpr::getBitCast(dtor, dtorTy), 1817 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), 1818 handle 1819 }; 1820 CGF.EmitNounwindRuntimeCall(atexit, args); 1821 } 1822 1823 /// Register a global destructor as best as we know how. 1824 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, 1825 const VarDecl &D, 1826 llvm::Constant *dtor, 1827 llvm::Constant *addr) { 1828 // Use __cxa_atexit if available. 1829 if (CGM.getCodeGenOpts().CXAAtExit) 1830 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); 1831 1832 if (D.getTLSKind()) 1833 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); 1834 1835 // In Apple kexts, we want to add a global destructor entry. 1836 // FIXME: shouldn't this be guarded by some variable? 1837 if (CGM.getLangOpts().AppleKext) { 1838 // Generate a global destructor entry. 1839 return CGM.AddCXXDtorEntry(dtor, addr); 1840 } 1841 1842 CGF.registerGlobalDtorWithAtExit(D, dtor, addr); 1843 } 1844 1845 static bool isThreadWrapperReplaceable(const VarDecl *VD, 1846 CodeGen::CodeGenModule &CGM) { 1847 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!"); 1848 // OS X prefers to have references to thread local variables to go through 1849 // the thread wrapper instead of directly referencing the backing variable. 1850 return VD->getTLSKind() == VarDecl::TLS_Dynamic && 1851 CGM.getTarget().getTriple().isMacOSX(); 1852 } 1853 1854 /// Get the appropriate linkage for the wrapper function. This is essentially 1855 /// the weak form of the variable's linkage; every translation unit which needs 1856 /// the wrapper emits a copy, and we want the linker to merge them. 1857 static llvm::GlobalValue::LinkageTypes 1858 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) { 1859 llvm::GlobalValue::LinkageTypes VarLinkage = 1860 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false); 1861 1862 // For internal linkage variables, we don't need an external or weak wrapper. 1863 if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) 1864 return VarLinkage; 1865 1866 // If the thread wrapper is replaceable, give it appropriate linkage. 1867 if (isThreadWrapperReplaceable(VD, CGM)) { 1868 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) || 1869 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage)) 1870 return llvm::GlobalVariable::WeakAnyLinkage; 1871 return VarLinkage; 1872 } 1873 return llvm::GlobalValue::WeakODRLinkage; 1874 } 1875 1876 llvm::Function * 1877 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, 1878 llvm::Value *Val) { 1879 // Mangle the name for the thread_local wrapper function. 1880 SmallString<256> WrapperName; 1881 { 1882 llvm::raw_svector_ostream Out(WrapperName); 1883 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); 1884 Out.flush(); 1885 } 1886 1887 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName)) 1888 return cast<llvm::Function>(V); 1889 1890 llvm::Type *RetTy = Val->getType(); 1891 if (VD->getType()->isReferenceType()) 1892 RetTy = RetTy->getPointerElementType(); 1893 1894 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false); 1895 llvm::Function *Wrapper = 1896 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM), 1897 WrapperName.str(), &CGM.getModule()); 1898 // Always resolve references to the wrapper at link time. 1899 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM)) 1900 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); 1901 return Wrapper; 1902 } 1903 1904 void ItaniumCXXABI::EmitThreadLocalInitFuncs( 1905 CodeGenModule &CGM, 1906 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>> 1907 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits, 1908 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) { 1909 llvm::Function *InitFunc = nullptr; 1910 if (!CXXThreadLocalInits.empty()) { 1911 // Generate a guarded initialization function. 1912 llvm::FunctionType *FTy = 1913 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 1914 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", 1915 /*TLS=*/true); 1916 llvm::GlobalVariable *Guard = new llvm::GlobalVariable( 1917 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false, 1918 llvm::GlobalVariable::InternalLinkage, 1919 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard"); 1920 Guard->setThreadLocal(true); 1921 CodeGenFunction(CGM) 1922 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard); 1923 } 1924 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) { 1925 const VarDecl *VD = CXXThreadLocals[I].first; 1926 llvm::GlobalVariable *Var = CXXThreadLocals[I].second; 1927 1928 // Some targets require that all access to thread local variables go through 1929 // the thread wrapper. This means that we cannot attempt to create a thread 1930 // wrapper or a thread helper. 1931 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) 1932 continue; 1933 1934 // Mangle the name for the thread_local initialization function. 1935 SmallString<256> InitFnName; 1936 { 1937 llvm::raw_svector_ostream Out(InitFnName); 1938 getMangleContext().mangleItaniumThreadLocalInit(VD, Out); 1939 Out.flush(); 1940 } 1941 1942 // If we have a definition for the variable, emit the initialization 1943 // function as an alias to the global Init function (if any). Otherwise, 1944 // produce a declaration of the initialization function. 1945 llvm::GlobalValue *Init = nullptr; 1946 bool InitIsInitFunc = false; 1947 if (VD->hasDefinition()) { 1948 InitIsInitFunc = true; 1949 if (InitFunc) 1950 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(), 1951 InitFunc); 1952 } else { 1953 // Emit a weak global function referring to the initialization function. 1954 // This function will not exist if the TU defining the thread_local 1955 // variable in question does not need any dynamic initialization for 1956 // its thread_local variables. 1957 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); 1958 Init = llvm::Function::Create( 1959 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(), 1960 &CGM.getModule()); 1961 } 1962 1963 if (Init) 1964 Init->setVisibility(Var->getVisibility()); 1965 1966 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); 1967 llvm::LLVMContext &Context = CGM.getModule().getContext(); 1968 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 1969 CGBuilderTy Builder(Entry); 1970 if (InitIsInitFunc) { 1971 if (Init) 1972 Builder.CreateCall(Init); 1973 } else { 1974 // Don't know whether we have an init function. Call it if it exists. 1975 llvm::Value *Have = Builder.CreateIsNotNull(Init); 1976 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1977 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1978 Builder.CreateCondBr(Have, InitBB, ExitBB); 1979 1980 Builder.SetInsertPoint(InitBB); 1981 Builder.CreateCall(Init); 1982 Builder.CreateBr(ExitBB); 1983 1984 Builder.SetInsertPoint(ExitBB); 1985 } 1986 1987 // For a reference, the result of the wrapper function is a pointer to 1988 // the referenced object. 1989 llvm::Value *Val = Var; 1990 if (VD->getType()->isReferenceType()) { 1991 llvm::LoadInst *LI = Builder.CreateLoad(Val); 1992 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity()); 1993 Val = LI; 1994 } 1995 if (Val->getType() != Wrapper->getReturnType()) 1996 Val = Builder.CreatePointerBitCastOrAddrSpaceCast( 1997 Val, Wrapper->getReturnType(), ""); 1998 Builder.CreateRet(Val); 1999 } 2000 } 2001 2002 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2003 const VarDecl *VD, 2004 QualType LValType) { 2005 QualType T = VD->getType(); 2006 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T); 2007 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty); 2008 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val); 2009 2010 Val = CGF.Builder.CreateCall(Wrapper); 2011 2012 LValue LV; 2013 if (VD->getType()->isReferenceType()) 2014 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType); 2015 else 2016 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD)); 2017 // FIXME: need setObjCGCLValueClass? 2018 return LV; 2019 } 2020 2021 /// Return whether the given global decl needs a VTT parameter, which it does 2022 /// if it's a base constructor or destructor with virtual bases. 2023 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 2024 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2025 2026 // We don't have any virtual bases, just return early. 2027 if (!MD->getParent()->getNumVBases()) 2028 return false; 2029 2030 // Check if we have a base constructor. 2031 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 2032 return true; 2033 2034 // Check if we have a base destructor. 2035 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 2036 return true; 2037 2038 return false; 2039 } 2040 2041 namespace { 2042 class ItaniumRTTIBuilder { 2043 CodeGenModule &CGM; // Per-module state. 2044 llvm::LLVMContext &VMContext; 2045 const ItaniumCXXABI &CXXABI; // Per-module state. 2046 2047 /// Fields - The fields of the RTTI descriptor currently being built. 2048 SmallVector<llvm::Constant *, 16> Fields; 2049 2050 /// GetAddrOfTypeName - Returns the mangled type name of the given type. 2051 llvm::GlobalVariable * 2052 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage); 2053 2054 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 2055 /// descriptor of the given type. 2056 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty); 2057 2058 /// BuildVTablePointer - Build the vtable pointer for the given type. 2059 void BuildVTablePointer(const Type *Ty); 2060 2061 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2062 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b. 2063 void BuildSIClassTypeInfo(const CXXRecordDecl *RD); 2064 2065 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2066 /// classes with bases that do not satisfy the abi::__si_class_type_info 2067 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2068 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD); 2069 2070 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used 2071 /// for pointer types. 2072 void BuildPointerTypeInfo(QualType PointeeTy); 2073 2074 /// BuildObjCObjectTypeInfo - Build the appropriate kind of 2075 /// type_info for an object type. 2076 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty); 2077 2078 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2079 /// struct, used for member pointer types. 2080 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty); 2081 2082 public: 2083 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI) 2084 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {} 2085 2086 // Pointer type info flags. 2087 enum { 2088 /// PTI_Const - Type has const qualifier. 2089 PTI_Const = 0x1, 2090 2091 /// PTI_Volatile - Type has volatile qualifier. 2092 PTI_Volatile = 0x2, 2093 2094 /// PTI_Restrict - Type has restrict qualifier. 2095 PTI_Restrict = 0x4, 2096 2097 /// PTI_Incomplete - Type is incomplete. 2098 PTI_Incomplete = 0x8, 2099 2100 /// PTI_ContainingClassIncomplete - Containing class is incomplete. 2101 /// (in pointer to member). 2102 PTI_ContainingClassIncomplete = 0x10 2103 }; 2104 2105 // VMI type info flags. 2106 enum { 2107 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance. 2108 VMI_NonDiamondRepeat = 0x1, 2109 2110 /// VMI_DiamondShaped - Class is diamond shaped. 2111 VMI_DiamondShaped = 0x2 2112 }; 2113 2114 // Base class type info flags. 2115 enum { 2116 /// BCTI_Virtual - Base class is virtual. 2117 BCTI_Virtual = 0x1, 2118 2119 /// BCTI_Public - Base class is public. 2120 BCTI_Public = 0x2 2121 }; 2122 2123 /// BuildTypeInfo - Build the RTTI type info struct for the given type. 2124 /// 2125 /// \param Force - true to force the creation of this RTTI value 2126 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false); 2127 }; 2128 } 2129 2130 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName( 2131 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) { 2132 SmallString<256> OutName; 2133 llvm::raw_svector_ostream Out(OutName); 2134 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out); 2135 Out.flush(); 2136 StringRef Name = OutName.str(); 2137 2138 // We know that the mangled name of the type starts at index 4 of the 2139 // mangled name of the typename, so we can just index into it in order to 2140 // get the mangled name of the type. 2141 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 2142 Name.substr(4)); 2143 2144 llvm::GlobalVariable *GV = 2145 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage); 2146 2147 GV->setInitializer(Init); 2148 2149 return GV; 2150 } 2151 2152 llvm::Constant * 2153 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) { 2154 // Mangle the RTTI name. 2155 SmallString<256> OutName; 2156 llvm::raw_svector_ostream Out(OutName); 2157 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2158 Out.flush(); 2159 StringRef Name = OutName.str(); 2160 2161 // Look for an existing global. 2162 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name); 2163 2164 if (!GV) { 2165 // Create a new global variable. 2166 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 2167 /*Constant=*/true, 2168 llvm::GlobalValue::ExternalLinkage, nullptr, 2169 Name); 2170 } 2171 2172 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2173 } 2174 2175 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type 2176 /// info for that type is defined in the standard library. 2177 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) { 2178 // Itanium C++ ABI 2.9.2: 2179 // Basic type information (e.g. for "int", "bool", etc.) will be kept in 2180 // the run-time support library. Specifically, the run-time support 2181 // library should contain type_info objects for the types X, X* and 2182 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char, 2183 // unsigned char, signed char, short, unsigned short, int, unsigned int, 2184 // long, unsigned long, long long, unsigned long long, float, double, 2185 // long double, char16_t, char32_t, and the IEEE 754r decimal and 2186 // half-precision floating point types. 2187 switch (Ty->getKind()) { 2188 case BuiltinType::Void: 2189 case BuiltinType::NullPtr: 2190 case BuiltinType::Bool: 2191 case BuiltinType::WChar_S: 2192 case BuiltinType::WChar_U: 2193 case BuiltinType::Char_U: 2194 case BuiltinType::Char_S: 2195 case BuiltinType::UChar: 2196 case BuiltinType::SChar: 2197 case BuiltinType::Short: 2198 case BuiltinType::UShort: 2199 case BuiltinType::Int: 2200 case BuiltinType::UInt: 2201 case BuiltinType::Long: 2202 case BuiltinType::ULong: 2203 case BuiltinType::LongLong: 2204 case BuiltinType::ULongLong: 2205 case BuiltinType::Half: 2206 case BuiltinType::Float: 2207 case BuiltinType::Double: 2208 case BuiltinType::LongDouble: 2209 case BuiltinType::Char16: 2210 case BuiltinType::Char32: 2211 case BuiltinType::Int128: 2212 case BuiltinType::UInt128: 2213 case BuiltinType::OCLImage1d: 2214 case BuiltinType::OCLImage1dArray: 2215 case BuiltinType::OCLImage1dBuffer: 2216 case BuiltinType::OCLImage2d: 2217 case BuiltinType::OCLImage2dArray: 2218 case BuiltinType::OCLImage3d: 2219 case BuiltinType::OCLSampler: 2220 case BuiltinType::OCLEvent: 2221 return true; 2222 2223 case BuiltinType::Dependent: 2224 #define BUILTIN_TYPE(Id, SingletonId) 2225 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2226 case BuiltinType::Id: 2227 #include "clang/AST/BuiltinTypes.def" 2228 llvm_unreachable("asking for RRTI for a placeholder type!"); 2229 2230 case BuiltinType::ObjCId: 2231 case BuiltinType::ObjCClass: 2232 case BuiltinType::ObjCSel: 2233 llvm_unreachable("FIXME: Objective-C types are unsupported!"); 2234 } 2235 2236 llvm_unreachable("Invalid BuiltinType Kind!"); 2237 } 2238 2239 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) { 2240 QualType PointeeTy = PointerTy->getPointeeType(); 2241 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy); 2242 if (!BuiltinTy) 2243 return false; 2244 2245 // Check the qualifiers. 2246 Qualifiers Quals = PointeeTy.getQualifiers(); 2247 Quals.removeConst(); 2248 2249 if (!Quals.empty()) 2250 return false; 2251 2252 return TypeInfoIsInStandardLibrary(BuiltinTy); 2253 } 2254 2255 /// IsStandardLibraryRTTIDescriptor - Returns whether the type 2256 /// information for the given type exists in the standard library. 2257 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) { 2258 // Type info for builtin types is defined in the standard library. 2259 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty)) 2260 return TypeInfoIsInStandardLibrary(BuiltinTy); 2261 2262 // Type info for some pointer types to builtin types is defined in the 2263 // standard library. 2264 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2265 return TypeInfoIsInStandardLibrary(PointerTy); 2266 2267 return false; 2268 } 2269 2270 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for 2271 /// the given type exists somewhere else, and that we should not emit the type 2272 /// information in this translation unit. Assumes that it is not a 2273 /// standard-library type. 2274 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, 2275 QualType Ty) { 2276 ASTContext &Context = CGM.getContext(); 2277 2278 // If RTTI is disabled, assume it might be disabled in the 2279 // translation unit that defines any potential key function, too. 2280 if (!Context.getLangOpts().RTTI) return false; 2281 2282 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2283 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2284 if (!RD->hasDefinition()) 2285 return false; 2286 2287 if (!RD->isDynamicClass()) 2288 return false; 2289 2290 // FIXME: this may need to be reconsidered if the key function 2291 // changes. 2292 return CGM.getVTables().isVTableExternal(RD); 2293 } 2294 2295 return false; 2296 } 2297 2298 /// IsIncompleteClassType - Returns whether the given record type is incomplete. 2299 static bool IsIncompleteClassType(const RecordType *RecordTy) { 2300 return !RecordTy->getDecl()->isCompleteDefinition(); 2301 } 2302 2303 /// ContainsIncompleteClassType - Returns whether the given type contains an 2304 /// incomplete class type. This is true if 2305 /// 2306 /// * The given type is an incomplete class type. 2307 /// * The given type is a pointer type whose pointee type contains an 2308 /// incomplete class type. 2309 /// * The given type is a member pointer type whose class is an incomplete 2310 /// class type. 2311 /// * The given type is a member pointer type whoise pointee type contains an 2312 /// incomplete class type. 2313 /// is an indirect or direct pointer to an incomplete class type. 2314 static bool ContainsIncompleteClassType(QualType Ty) { 2315 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2316 if (IsIncompleteClassType(RecordTy)) 2317 return true; 2318 } 2319 2320 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2321 return ContainsIncompleteClassType(PointerTy->getPointeeType()); 2322 2323 if (const MemberPointerType *MemberPointerTy = 2324 dyn_cast<MemberPointerType>(Ty)) { 2325 // Check if the class type is incomplete. 2326 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass()); 2327 if (IsIncompleteClassType(ClassType)) 2328 return true; 2329 2330 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType()); 2331 } 2332 2333 return false; 2334 } 2335 2336 // CanUseSingleInheritance - Return whether the given record decl has a "single, 2337 // public, non-virtual base at offset zero (i.e. the derived class is dynamic 2338 // iff the base is)", according to Itanium C++ ABI, 2.95p6b. 2339 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) { 2340 // Check the number of bases. 2341 if (RD->getNumBases() != 1) 2342 return false; 2343 2344 // Get the base. 2345 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(); 2346 2347 // Check that the base is not virtual. 2348 if (Base->isVirtual()) 2349 return false; 2350 2351 // Check that the base is public. 2352 if (Base->getAccessSpecifier() != AS_public) 2353 return false; 2354 2355 // Check that the class is dynamic iff the base is. 2356 const CXXRecordDecl *BaseDecl = 2357 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2358 if (!BaseDecl->isEmpty() && 2359 BaseDecl->isDynamicClass() != RD->isDynamicClass()) 2360 return false; 2361 2362 return true; 2363 } 2364 2365 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) { 2366 // abi::__class_type_info. 2367 static const char * const ClassTypeInfo = 2368 "_ZTVN10__cxxabiv117__class_type_infoE"; 2369 // abi::__si_class_type_info. 2370 static const char * const SIClassTypeInfo = 2371 "_ZTVN10__cxxabiv120__si_class_type_infoE"; 2372 // abi::__vmi_class_type_info. 2373 static const char * const VMIClassTypeInfo = 2374 "_ZTVN10__cxxabiv121__vmi_class_type_infoE"; 2375 2376 const char *VTableName = nullptr; 2377 2378 switch (Ty->getTypeClass()) { 2379 #define TYPE(Class, Base) 2380 #define ABSTRACT_TYPE(Class, Base) 2381 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2382 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2383 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2384 #include "clang/AST/TypeNodes.def" 2385 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2386 2387 case Type::LValueReference: 2388 case Type::RValueReference: 2389 llvm_unreachable("References shouldn't get here"); 2390 2391 case Type::Auto: 2392 llvm_unreachable("Undeduced auto type shouldn't get here"); 2393 2394 case Type::Builtin: 2395 // GCC treats vector and complex types as fundamental types. 2396 case Type::Vector: 2397 case Type::ExtVector: 2398 case Type::Complex: 2399 case Type::Atomic: 2400 // FIXME: GCC treats block pointers as fundamental types?! 2401 case Type::BlockPointer: 2402 // abi::__fundamental_type_info. 2403 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE"; 2404 break; 2405 2406 case Type::ConstantArray: 2407 case Type::IncompleteArray: 2408 case Type::VariableArray: 2409 // abi::__array_type_info. 2410 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE"; 2411 break; 2412 2413 case Type::FunctionNoProto: 2414 case Type::FunctionProto: 2415 // abi::__function_type_info. 2416 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE"; 2417 break; 2418 2419 case Type::Enum: 2420 // abi::__enum_type_info. 2421 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE"; 2422 break; 2423 2424 case Type::Record: { 2425 const CXXRecordDecl *RD = 2426 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2427 2428 if (!RD->hasDefinition() || !RD->getNumBases()) { 2429 VTableName = ClassTypeInfo; 2430 } else if (CanUseSingleInheritance(RD)) { 2431 VTableName = SIClassTypeInfo; 2432 } else { 2433 VTableName = VMIClassTypeInfo; 2434 } 2435 2436 break; 2437 } 2438 2439 case Type::ObjCObject: 2440 // Ignore protocol qualifiers. 2441 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr(); 2442 2443 // Handle id and Class. 2444 if (isa<BuiltinType>(Ty)) { 2445 VTableName = ClassTypeInfo; 2446 break; 2447 } 2448 2449 assert(isa<ObjCInterfaceType>(Ty)); 2450 // Fall through. 2451 2452 case Type::ObjCInterface: 2453 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) { 2454 VTableName = SIClassTypeInfo; 2455 } else { 2456 VTableName = ClassTypeInfo; 2457 } 2458 break; 2459 2460 case Type::ObjCObjectPointer: 2461 case Type::Pointer: 2462 // abi::__pointer_type_info. 2463 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE"; 2464 break; 2465 2466 case Type::MemberPointer: 2467 // abi::__pointer_to_member_type_info. 2468 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE"; 2469 break; 2470 } 2471 2472 llvm::Constant *VTable = 2473 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); 2474 2475 llvm::Type *PtrDiffTy = 2476 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 2477 2478 // The vtable address point is 2. 2479 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2); 2480 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two); 2481 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy); 2482 2483 Fields.push_back(VTable); 2484 } 2485 2486 /// \brief Return the linkage that the type info and type info name constants 2487 /// should have for the given type. 2488 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM, 2489 QualType Ty) { 2490 // Itanium C++ ABI 2.9.5p7: 2491 // In addition, it and all of the intermediate abi::__pointer_type_info 2492 // structs in the chain down to the abi::__class_type_info for the 2493 // incomplete class type must be prevented from resolving to the 2494 // corresponding type_info structs for the complete class type, possibly 2495 // by making them local static objects. Finally, a dummy class RTTI is 2496 // generated for the incomplete type that will not resolve to the final 2497 // complete class RTTI (because the latter need not exist), possibly by 2498 // making it a local static object. 2499 if (ContainsIncompleteClassType(Ty)) 2500 return llvm::GlobalValue::InternalLinkage; 2501 2502 switch (Ty->getLinkage()) { 2503 case NoLinkage: 2504 case InternalLinkage: 2505 case UniqueExternalLinkage: 2506 return llvm::GlobalValue::InternalLinkage; 2507 2508 case VisibleNoLinkage: 2509 case ExternalLinkage: 2510 if (!CGM.getLangOpts().RTTI) { 2511 // RTTI is not enabled, which means that this type info struct is going 2512 // to be used for exception handling. Give it linkonce_odr linkage. 2513 return llvm::GlobalValue::LinkOnceODRLinkage; 2514 } 2515 2516 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) { 2517 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2518 if (RD->hasAttr<WeakAttr>()) 2519 return llvm::GlobalValue::WeakODRLinkage; 2520 if (RD->isDynamicClass()) 2521 return CGM.getVTableLinkage(RD); 2522 } 2523 2524 return llvm::GlobalValue::LinkOnceODRLinkage; 2525 } 2526 2527 llvm_unreachable("Invalid linkage!"); 2528 } 2529 2530 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) { 2531 // We want to operate on the canonical type. 2532 Ty = CGM.getContext().getCanonicalType(Ty); 2533 2534 // Check if we've already emitted an RTTI descriptor for this type. 2535 SmallString<256> OutName; 2536 llvm::raw_svector_ostream Out(OutName); 2537 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2538 Out.flush(); 2539 StringRef Name = OutName.str(); 2540 2541 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name); 2542 if (OldGV && !OldGV->isDeclaration()) { 2543 assert(!OldGV->hasAvailableExternallyLinkage() && 2544 "available_externally typeinfos not yet implemented"); 2545 2546 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy); 2547 } 2548 2549 // Check if there is already an external RTTI descriptor for this type. 2550 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty); 2551 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty))) 2552 return GetAddrOfExternalRTTIDescriptor(Ty); 2553 2554 // Emit the standard library with external linkage. 2555 llvm::GlobalVariable::LinkageTypes Linkage; 2556 if (IsStdLib) 2557 Linkage = llvm::GlobalValue::ExternalLinkage; 2558 else 2559 Linkage = getTypeInfoLinkage(CGM, Ty); 2560 2561 // Add the vtable pointer. 2562 BuildVTablePointer(cast<Type>(Ty)); 2563 2564 // And the name. 2565 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage); 2566 llvm::Constant *TypeNameField; 2567 2568 // If we're supposed to demote the visibility, be sure to set a flag 2569 // to use a string comparison for type_info comparisons. 2570 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness = 2571 CXXABI.classifyRTTIUniqueness(Ty, Linkage); 2572 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) { 2573 // The flag is the sign bit, which on ARM64 is defined to be clear 2574 // for global pointers. This is very ARM64-specific. 2575 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty); 2576 llvm::Constant *flag = 2577 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63); 2578 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag); 2579 TypeNameField = 2580 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy); 2581 } else { 2582 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy); 2583 } 2584 Fields.push_back(TypeNameField); 2585 2586 switch (Ty->getTypeClass()) { 2587 #define TYPE(Class, Base) 2588 #define ABSTRACT_TYPE(Class, Base) 2589 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2590 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2591 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2592 #include "clang/AST/TypeNodes.def" 2593 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2594 2595 // GCC treats vector types as fundamental types. 2596 case Type::Builtin: 2597 case Type::Vector: 2598 case Type::ExtVector: 2599 case Type::Complex: 2600 case Type::BlockPointer: 2601 // Itanium C++ ABI 2.9.5p4: 2602 // abi::__fundamental_type_info adds no data members to std::type_info. 2603 break; 2604 2605 case Type::LValueReference: 2606 case Type::RValueReference: 2607 llvm_unreachable("References shouldn't get here"); 2608 2609 case Type::Auto: 2610 llvm_unreachable("Undeduced auto type shouldn't get here"); 2611 2612 case Type::ConstantArray: 2613 case Type::IncompleteArray: 2614 case Type::VariableArray: 2615 // Itanium C++ ABI 2.9.5p5: 2616 // abi::__array_type_info adds no data members to std::type_info. 2617 break; 2618 2619 case Type::FunctionNoProto: 2620 case Type::FunctionProto: 2621 // Itanium C++ ABI 2.9.5p5: 2622 // abi::__function_type_info adds no data members to std::type_info. 2623 break; 2624 2625 case Type::Enum: 2626 // Itanium C++ ABI 2.9.5p5: 2627 // abi::__enum_type_info adds no data members to std::type_info. 2628 break; 2629 2630 case Type::Record: { 2631 const CXXRecordDecl *RD = 2632 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2633 if (!RD->hasDefinition() || !RD->getNumBases()) { 2634 // We don't need to emit any fields. 2635 break; 2636 } 2637 2638 if (CanUseSingleInheritance(RD)) 2639 BuildSIClassTypeInfo(RD); 2640 else 2641 BuildVMIClassTypeInfo(RD); 2642 2643 break; 2644 } 2645 2646 case Type::ObjCObject: 2647 case Type::ObjCInterface: 2648 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty)); 2649 break; 2650 2651 case Type::ObjCObjectPointer: 2652 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 2653 break; 2654 2655 case Type::Pointer: 2656 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType()); 2657 break; 2658 2659 case Type::MemberPointer: 2660 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty)); 2661 break; 2662 2663 case Type::Atomic: 2664 // No fields, at least for the moment. 2665 break; 2666 } 2667 2668 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields); 2669 2670 llvm::GlobalVariable *GV = 2671 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 2672 /*Constant=*/true, Linkage, Init, Name); 2673 2674 // If there's already an old global variable, replace it with the new one. 2675 if (OldGV) { 2676 GV->takeName(OldGV); 2677 llvm::Constant *NewPtr = 2678 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 2679 OldGV->replaceAllUsesWith(NewPtr); 2680 OldGV->eraseFromParent(); 2681 } 2682 2683 // The Itanium ABI specifies that type_info objects must be globally 2684 // unique, with one exception: if the type is an incomplete class 2685 // type or a (possibly indirect) pointer to one. That exception 2686 // affects the general case of comparing type_info objects produced 2687 // by the typeid operator, which is why the comparison operators on 2688 // std::type_info generally use the type_info name pointers instead 2689 // of the object addresses. However, the language's built-in uses 2690 // of RTTI generally require class types to be complete, even when 2691 // manipulating pointers to those class types. This allows the 2692 // implementation of dynamic_cast to rely on address equality tests, 2693 // which is much faster. 2694 2695 // All of this is to say that it's important that both the type_info 2696 // object and the type_info name be uniqued when weakly emitted. 2697 2698 // Give the type_info object and name the formal visibility of the 2699 // type itself. 2700 llvm::GlobalValue::VisibilityTypes llvmVisibility; 2701 if (llvm::GlobalValue::isLocalLinkage(Linkage)) 2702 // If the linkage is local, only default visibility makes sense. 2703 llvmVisibility = llvm::GlobalValue::DefaultVisibility; 2704 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden) 2705 llvmVisibility = llvm::GlobalValue::HiddenVisibility; 2706 else 2707 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility()); 2708 TypeName->setVisibility(llvmVisibility); 2709 GV->setVisibility(llvmVisibility); 2710 2711 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2712 } 2713 2714 /// ComputeQualifierFlags - Compute the pointer type info flags from the 2715 /// given qualifier. 2716 static unsigned ComputeQualifierFlags(Qualifiers Quals) { 2717 unsigned Flags = 0; 2718 2719 if (Quals.hasConst()) 2720 Flags |= ItaniumRTTIBuilder::PTI_Const; 2721 if (Quals.hasVolatile()) 2722 Flags |= ItaniumRTTIBuilder::PTI_Volatile; 2723 if (Quals.hasRestrict()) 2724 Flags |= ItaniumRTTIBuilder::PTI_Restrict; 2725 2726 return Flags; 2727 } 2728 2729 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info 2730 /// for the given Objective-C object type. 2731 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) { 2732 // Drop qualifiers. 2733 const Type *T = OT->getBaseType().getTypePtr(); 2734 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T)); 2735 2736 // The builtin types are abi::__class_type_infos and don't require 2737 // extra fields. 2738 if (isa<BuiltinType>(T)) return; 2739 2740 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl(); 2741 ObjCInterfaceDecl *Super = Class->getSuperClass(); 2742 2743 // Root classes are also __class_type_info. 2744 if (!Super) return; 2745 2746 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super); 2747 2748 // Everything else is single inheritance. 2749 llvm::Constant *BaseTypeInfo = 2750 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy); 2751 Fields.push_back(BaseTypeInfo); 2752 } 2753 2754 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2755 /// inheritance, according to the Itanium C++ ABI, 2.95p6b. 2756 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) { 2757 // Itanium C++ ABI 2.9.5p6b: 2758 // It adds to abi::__class_type_info a single member pointing to the 2759 // type_info structure for the base type, 2760 llvm::Constant *BaseTypeInfo = 2761 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType()); 2762 Fields.push_back(BaseTypeInfo); 2763 } 2764 2765 namespace { 2766 /// SeenBases - Contains virtual and non-virtual bases seen when traversing 2767 /// a class hierarchy. 2768 struct SeenBases { 2769 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases; 2770 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases; 2771 }; 2772 } 2773 2774 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in 2775 /// abi::__vmi_class_type_info. 2776 /// 2777 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 2778 SeenBases &Bases) { 2779 2780 unsigned Flags = 0; 2781 2782 const CXXRecordDecl *BaseDecl = 2783 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2784 2785 if (Base->isVirtual()) { 2786 // Mark the virtual base as seen. 2787 if (!Bases.VirtualBases.insert(BaseDecl)) { 2788 // If this virtual base has been seen before, then the class is diamond 2789 // shaped. 2790 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped; 2791 } else { 2792 if (Bases.NonVirtualBases.count(BaseDecl)) 2793 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 2794 } 2795 } else { 2796 // Mark the non-virtual base as seen. 2797 if (!Bases.NonVirtualBases.insert(BaseDecl)) { 2798 // If this non-virtual base has been seen before, then the class has non- 2799 // diamond shaped repeated inheritance. 2800 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 2801 } else { 2802 if (Bases.VirtualBases.count(BaseDecl)) 2803 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 2804 } 2805 } 2806 2807 // Walk all bases. 2808 for (const auto &I : BaseDecl->bases()) 2809 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 2810 2811 return Flags; 2812 } 2813 2814 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) { 2815 unsigned Flags = 0; 2816 SeenBases Bases; 2817 2818 // Walk all bases. 2819 for (const auto &I : RD->bases()) 2820 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 2821 2822 return Flags; 2823 } 2824 2825 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2826 /// classes with bases that do not satisfy the abi::__si_class_type_info 2827 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2828 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) { 2829 llvm::Type *UnsignedIntLTy = 2830 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 2831 2832 // Itanium C++ ABI 2.9.5p6c: 2833 // __flags is a word with flags describing details about the class 2834 // structure, which may be referenced by using the __flags_masks 2835 // enumeration. These flags refer to both direct and indirect bases. 2836 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD); 2837 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 2838 2839 // Itanium C++ ABI 2.9.5p6c: 2840 // __base_count is a word with the number of direct proper base class 2841 // descriptions that follow. 2842 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases())); 2843 2844 if (!RD->getNumBases()) 2845 return; 2846 2847 llvm::Type *LongLTy = 2848 CGM.getTypes().ConvertType(CGM.getContext().LongTy); 2849 2850 // Now add the base class descriptions. 2851 2852 // Itanium C++ ABI 2.9.5p6c: 2853 // __base_info[] is an array of base class descriptions -- one for every 2854 // direct proper base. Each description is of the type: 2855 // 2856 // struct abi::__base_class_type_info { 2857 // public: 2858 // const __class_type_info *__base_type; 2859 // long __offset_flags; 2860 // 2861 // enum __offset_flags_masks { 2862 // __virtual_mask = 0x1, 2863 // __public_mask = 0x2, 2864 // __offset_shift = 8 2865 // }; 2866 // }; 2867 for (const auto &Base : RD->bases()) { 2868 // The __base_type member points to the RTTI for the base type. 2869 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType())); 2870 2871 const CXXRecordDecl *BaseDecl = 2872 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 2873 2874 int64_t OffsetFlags = 0; 2875 2876 // All but the lower 8 bits of __offset_flags are a signed offset. 2877 // For a non-virtual base, this is the offset in the object of the base 2878 // subobject. For a virtual base, this is the offset in the virtual table of 2879 // the virtual base offset for the virtual base referenced (negative). 2880 CharUnits Offset; 2881 if (Base.isVirtual()) 2882 Offset = 2883 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl); 2884 else { 2885 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 2886 Offset = Layout.getBaseClassOffset(BaseDecl); 2887 }; 2888 2889 OffsetFlags = uint64_t(Offset.getQuantity()) << 8; 2890 2891 // The low-order byte of __offset_flags contains flags, as given by the 2892 // masks from the enumeration __offset_flags_masks. 2893 if (Base.isVirtual()) 2894 OffsetFlags |= BCTI_Virtual; 2895 if (Base.getAccessSpecifier() == AS_public) 2896 OffsetFlags |= BCTI_Public; 2897 2898 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags)); 2899 } 2900 } 2901 2902 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, 2903 /// used for pointer types. 2904 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) { 2905 Qualifiers Quals; 2906 QualType UnqualifiedPointeeTy = 2907 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals); 2908 2909 // Itanium C++ ABI 2.9.5p7: 2910 // __flags is a flag word describing the cv-qualification and other 2911 // attributes of the type pointed to 2912 unsigned Flags = ComputeQualifierFlags(Quals); 2913 2914 // Itanium C++ ABI 2.9.5p7: 2915 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 2916 // incomplete class type, the incomplete target type flag is set. 2917 if (ContainsIncompleteClassType(UnqualifiedPointeeTy)) 2918 Flags |= PTI_Incomplete; 2919 2920 llvm::Type *UnsignedIntLTy = 2921 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 2922 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 2923 2924 // Itanium C++ ABI 2.9.5p7: 2925 // __pointee is a pointer to the std::type_info derivation for the 2926 // unqualified type being pointed to. 2927 llvm::Constant *PointeeTypeInfo = 2928 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy); 2929 Fields.push_back(PointeeTypeInfo); 2930 } 2931 2932 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2933 /// struct, used for member pointer types. 2934 void 2935 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) { 2936 QualType PointeeTy = Ty->getPointeeType(); 2937 2938 Qualifiers Quals; 2939 QualType UnqualifiedPointeeTy = 2940 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals); 2941 2942 // Itanium C++ ABI 2.9.5p7: 2943 // __flags is a flag word describing the cv-qualification and other 2944 // attributes of the type pointed to. 2945 unsigned Flags = ComputeQualifierFlags(Quals); 2946 2947 const RecordType *ClassType = cast<RecordType>(Ty->getClass()); 2948 2949 // Itanium C++ ABI 2.9.5p7: 2950 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 2951 // incomplete class type, the incomplete target type flag is set. 2952 if (ContainsIncompleteClassType(UnqualifiedPointeeTy)) 2953 Flags |= PTI_Incomplete; 2954 2955 if (IsIncompleteClassType(ClassType)) 2956 Flags |= PTI_ContainingClassIncomplete; 2957 2958 llvm::Type *UnsignedIntLTy = 2959 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 2960 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 2961 2962 // Itanium C++ ABI 2.9.5p7: 2963 // __pointee is a pointer to the std::type_info derivation for the 2964 // unqualified type being pointed to. 2965 llvm::Constant *PointeeTypeInfo = 2966 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy); 2967 Fields.push_back(PointeeTypeInfo); 2968 2969 // Itanium C++ ABI 2.9.5p9: 2970 // __context is a pointer to an abi::__class_type_info corresponding to the 2971 // class type containing the member pointed to 2972 // (e.g., the "A" in "int A::*"). 2973 Fields.push_back( 2974 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0))); 2975 } 2976 2977 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) { 2978 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty); 2979 } 2980 2981 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) { 2982 QualType PointerType = getContext().getPointerType(Type); 2983 QualType PointerTypeConst = getContext().getPointerType(Type.withConst()); 2984 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true); 2985 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true); 2986 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true); 2987 } 2988 2989 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() { 2990 QualType FundamentalTypes[] = { 2991 getContext().VoidTy, getContext().NullPtrTy, 2992 getContext().BoolTy, getContext().WCharTy, 2993 getContext().CharTy, getContext().UnsignedCharTy, 2994 getContext().SignedCharTy, getContext().ShortTy, 2995 getContext().UnsignedShortTy, getContext().IntTy, 2996 getContext().UnsignedIntTy, getContext().LongTy, 2997 getContext().UnsignedLongTy, getContext().LongLongTy, 2998 getContext().UnsignedLongLongTy, getContext().HalfTy, 2999 getContext().FloatTy, getContext().DoubleTy, 3000 getContext().LongDoubleTy, getContext().Char16Ty, 3001 getContext().Char32Ty, 3002 }; 3003 for (const QualType &FundamentalType : FundamentalTypes) 3004 EmitFundamentalRTTIDescriptor(FundamentalType); 3005 } 3006 3007 /// What sort of uniqueness rules should we use for the RTTI for the 3008 /// given type? 3009 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness( 3010 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const { 3011 if (shouldRTTIBeUnique()) 3012 return RUK_Unique; 3013 3014 // It's only necessary for linkonce_odr or weak_odr linkage. 3015 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage && 3016 Linkage != llvm::GlobalValue::WeakODRLinkage) 3017 return RUK_Unique; 3018 3019 // It's only necessary with default visibility. 3020 if (CanTy->getVisibility() != DefaultVisibility) 3021 return RUK_Unique; 3022 3023 // If we're not required to publish this symbol, hide it. 3024 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage) 3025 return RUK_NonUniqueHidden; 3026 3027 // If we're required to publish this symbol, as we might be under an 3028 // explicit instantiation, leave it with default visibility but 3029 // enable string-comparisons. 3030 assert(Linkage == llvm::GlobalValue::WeakODRLinkage); 3031 return RUK_NonUniqueVisible; 3032 } 3033 3034 // Find out how to codegen the complete destructor and constructor 3035 namespace { 3036 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT }; 3037 } 3038 static StructorCodegen getCodegenToUse(CodeGenModule &CGM, 3039 const CXXMethodDecl *MD) { 3040 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases) 3041 return StructorCodegen::Emit; 3042 3043 // The complete and base structors are not equivalent if there are any virtual 3044 // bases, so emit separate functions. 3045 if (MD->getParent()->getNumVBases()) 3046 return StructorCodegen::Emit; 3047 3048 GlobalDecl AliasDecl; 3049 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 3050 AliasDecl = GlobalDecl(DD, Dtor_Complete); 3051 } else { 3052 const auto *CD = cast<CXXConstructorDecl>(MD); 3053 AliasDecl = GlobalDecl(CD, Ctor_Complete); 3054 } 3055 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3056 3057 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) 3058 return StructorCodegen::RAUW; 3059 3060 // FIXME: Should we allow available_externally aliases? 3061 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 3062 return StructorCodegen::RAUW; 3063 3064 if (llvm::GlobalValue::isWeakForLinker(Linkage)) { 3065 // Only ELF supports COMDATs with arbitrary names (C5/D5). 3066 if (CGM.getTarget().getTriple().isOSBinFormatELF()) 3067 return StructorCodegen::COMDAT; 3068 return StructorCodegen::Emit; 3069 } 3070 3071 return StructorCodegen::Alias; 3072 } 3073 3074 static void emitConstructorDestructorAlias(CodeGenModule &CGM, 3075 GlobalDecl AliasDecl, 3076 GlobalDecl TargetDecl) { 3077 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3078 3079 StringRef MangledName = CGM.getMangledName(AliasDecl); 3080 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName); 3081 if (Entry && !Entry->isDeclaration()) 3082 return; 3083 3084 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl)); 3085 llvm::PointerType *AliasType = Aliasee->getType(); 3086 3087 // Create the alias with no name. 3088 auto *Alias = llvm::GlobalAlias::create( 3089 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule()); 3090 3091 // Switch any previous uses to the alias. 3092 if (Entry) { 3093 assert(Entry->getType() == AliasType && 3094 "declaration exists with different type"); 3095 Alias->takeName(Entry); 3096 Entry->replaceAllUsesWith(Alias); 3097 Entry->eraseFromParent(); 3098 } else { 3099 Alias->setName(MangledName); 3100 } 3101 3102 // Finally, set up the alias with its proper name and attributes. 3103 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 3104 } 3105 3106 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 3107 StructorType Type) { 3108 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 3109 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD); 3110 3111 StructorCodegen CGType = getCodegenToUse(CGM, MD); 3112 3113 if (Type == StructorType::Complete) { 3114 GlobalDecl CompleteDecl; 3115 GlobalDecl BaseDecl; 3116 if (CD) { 3117 CompleteDecl = GlobalDecl(CD, Ctor_Complete); 3118 BaseDecl = GlobalDecl(CD, Ctor_Base); 3119 } else { 3120 CompleteDecl = GlobalDecl(DD, Dtor_Complete); 3121 BaseDecl = GlobalDecl(DD, Dtor_Base); 3122 } 3123 3124 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) { 3125 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl); 3126 return; 3127 } 3128 3129 if (CGType == StructorCodegen::RAUW) { 3130 StringRef MangledName = CGM.getMangledName(CompleteDecl); 3131 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl)); 3132 CGM.addReplacement(MangledName, Aliasee); 3133 return; 3134 } 3135 } 3136 3137 // The base destructor is equivalent to the base destructor of its 3138 // base class if there is exactly one non-virtual base class with a 3139 // non-trivial destructor, there are no fields with a non-trivial 3140 // destructor, and the body of the destructor is trivial. 3141 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT && 3142 !CGM.TryEmitBaseDestructorAsAlias(DD)) 3143 return; 3144 3145 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type); 3146 3147 if (CGType == StructorCodegen::COMDAT) { 3148 SmallString<256> Buffer; 3149 llvm::raw_svector_ostream Out(Buffer); 3150 if (DD) 3151 getMangleContext().mangleCXXDtorComdat(DD, Out); 3152 else 3153 getMangleContext().mangleCXXCtorComdat(CD, Out); 3154 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str()); 3155 Fn->setComdat(C); 3156 } 3157 } 3158