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 "CGCleanup.h" 23 #include "CGRecordLayout.h" 24 #include "CGVTables.h" 25 #include "CodeGenFunction.h" 26 #include "CodeGenModule.h" 27 #include "TargetInfo.h" 28 #include "clang/CodeGen/ConstantInitBuilder.h" 29 #include "clang/AST/Mangle.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/StmtCXX.h" 32 #include "llvm/IR/CallSite.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/Value.h" 37 38 using namespace clang; 39 using namespace CodeGen; 40 41 namespace { 42 class ItaniumCXXABI : public CodeGen::CGCXXABI { 43 /// VTables - All the vtables which have been defined. 44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables; 45 46 protected: 47 bool UseARMMethodPtrABI; 48 bool UseARMGuardVarABI; 49 bool Use32BitVTableOffsetABI; 50 51 ItaniumMangleContext &getMangleContext() { 52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 53 } 54 55 public: 56 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, 57 bool UseARMMethodPtrABI = false, 58 bool UseARMGuardVarABI = false) : 59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), 60 UseARMGuardVarABI(UseARMGuardVarABI), 61 Use32BitVTableOffsetABI(false) { } 62 63 bool classifyReturnType(CGFunctionInfo &FI) const override; 64 65 bool passClassIndirect(const CXXRecordDecl *RD) const { 66 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 67 // The PS4 platform ABI follows the behavior of Clang 3.2. 68 if (CGM.getCodeGenOpts().getClangABICompat() <= 69 CodeGenOptions::ClangABI::Ver4 || 70 CGM.getTriple().getOS() == llvm::Triple::PS4) 71 return RD->hasNonTrivialDestructor() || 72 RD->hasNonTrivialCopyConstructor(); 73 return !canCopyArgument(RD); 74 } 75 76 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override { 77 // If C++ prohibits us from making a copy, pass by address. 78 if (passClassIndirect(RD)) 79 return RAA_Indirect; 80 return RAA_Default; 81 } 82 83 bool isThisCompleteObject(GlobalDecl GD) const override { 84 // The Itanium ABI has separate complete-object vs. base-object 85 // variants of both constructors and destructors. 86 if (isa<CXXDestructorDecl>(GD.getDecl())) { 87 switch (GD.getDtorType()) { 88 case Dtor_Complete: 89 case Dtor_Deleting: 90 return true; 91 92 case Dtor_Base: 93 return false; 94 95 case Dtor_Comdat: 96 llvm_unreachable("emitting dtor comdat as function?"); 97 } 98 llvm_unreachable("bad dtor kind"); 99 } 100 if (isa<CXXConstructorDecl>(GD.getDecl())) { 101 switch (GD.getCtorType()) { 102 case Ctor_Complete: 103 return true; 104 105 case Ctor_Base: 106 return false; 107 108 case Ctor_CopyingClosure: 109 case Ctor_DefaultClosure: 110 llvm_unreachable("closure ctors in Itanium ABI?"); 111 112 case Ctor_Comdat: 113 llvm_unreachable("emitting ctor comdat as function?"); 114 } 115 llvm_unreachable("bad dtor kind"); 116 } 117 118 // No other kinds. 119 return false; 120 } 121 122 bool isZeroInitializable(const MemberPointerType *MPT) override; 123 124 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 125 126 CGCallee 127 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 128 const Expr *E, 129 Address This, 130 llvm::Value *&ThisPtrForCall, 131 llvm::Value *MemFnPtr, 132 const MemberPointerType *MPT) override; 133 134 llvm::Value * 135 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 136 Address Base, 137 llvm::Value *MemPtr, 138 const MemberPointerType *MPT) override; 139 140 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 141 const CastExpr *E, 142 llvm::Value *Src) override; 143 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 144 llvm::Constant *Src) override; 145 146 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 147 148 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override; 149 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 150 CharUnits offset) override; 151 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 152 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, 153 CharUnits ThisAdjustment); 154 155 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 156 llvm::Value *L, llvm::Value *R, 157 const MemberPointerType *MPT, 158 bool Inequality) override; 159 160 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 161 llvm::Value *Addr, 162 const MemberPointerType *MPT) override; 163 164 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, 165 Address Ptr, QualType ElementType, 166 const CXXDestructorDecl *Dtor) override; 167 168 /// Itanium says that an _Unwind_Exception has to be "double-word" 169 /// aligned (and thus the end of it is also so-aligned), meaning 16 170 /// bytes. Of course, that was written for the actual Itanium, 171 /// which is a 64-bit platform. Classically, the ABI doesn't really 172 /// specify the alignment on other platforms, but in practice 173 /// libUnwind declares the struct with __attribute__((aligned)), so 174 /// we assume that alignment here. (It's generally 16 bytes, but 175 /// some targets overwrite it.) 176 CharUnits getAlignmentOfExnObject() { 177 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned(); 178 return CGM.getContext().toCharUnitsFromBits(align); 179 } 180 181 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override; 182 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override; 183 184 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override; 185 186 llvm::CallInst * 187 emitTerminateForUnexpectedException(CodeGenFunction &CGF, 188 llvm::Value *Exn) override; 189 190 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport); 191 void EmitFundamentalRTTIDescriptors(bool DLLExport); 192 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 193 CatchTypeInfo 194 getAddrOfCXXCatchHandlerType(QualType Ty, 195 QualType CatchHandlerType) override { 196 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0}; 197 } 198 199 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 200 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 201 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 202 Address ThisPtr, 203 llvm::Type *StdTypeInfoPtrTy) override; 204 205 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 206 QualType SrcRecordTy) override; 207 208 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value, 209 QualType SrcRecordTy, QualType DestTy, 210 QualType DestRecordTy, 211 llvm::BasicBlock *CastEnd) override; 212 213 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, 214 QualType SrcRecordTy, 215 QualType DestTy) override; 216 217 bool EmitBadCastCall(CodeGenFunction &CGF) override; 218 219 llvm::Value * 220 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, 221 const CXXRecordDecl *ClassDecl, 222 const CXXRecordDecl *BaseClassDecl) override; 223 224 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 225 226 AddedStructorArgs 227 buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 228 SmallVectorImpl<CanQualType> &ArgTys) override; 229 230 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 231 CXXDtorType DT) const override { 232 // Itanium does not emit any destructor variant as an inline thunk. 233 // Delegating may occur as an optimization, but all variants are either 234 // emitted with external linkage or as linkonce if they are inline and used. 235 return false; 236 } 237 238 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 239 240 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 241 FunctionArgList &Params) override; 242 243 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 244 245 AddedStructorArgs 246 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D, 247 CXXCtorType Type, bool ForVirtualBase, 248 bool Delegating, CallArgList &Args) override; 249 250 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 251 CXXDtorType Type, bool ForVirtualBase, 252 bool Delegating, Address This) override; 253 254 void emitVTableDefinitions(CodeGenVTables &CGVT, 255 const CXXRecordDecl *RD) override; 256 257 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF, 258 CodeGenFunction::VPtr Vptr) override; 259 260 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override { 261 return true; 262 } 263 264 llvm::Constant * 265 getVTableAddressPoint(BaseSubobject Base, 266 const CXXRecordDecl *VTableClass) override; 267 268 llvm::Value *getVTableAddressPointInStructor( 269 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 270 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override; 271 272 llvm::Value *getVTableAddressPointInStructorWithVTT( 273 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 274 BaseSubobject Base, const CXXRecordDecl *NearestVBase); 275 276 llvm::Constant * 277 getVTableAddressPointForConstExpr(BaseSubobject Base, 278 const CXXRecordDecl *VTableClass) override; 279 280 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 281 CharUnits VPtrOffset) override; 282 283 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 284 Address This, llvm::Type *Ty, 285 SourceLocation Loc) override; 286 287 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF, 288 const CXXDestructorDecl *Dtor, 289 CXXDtorType DtorType, 290 Address This, 291 const CXXMemberCallExpr *CE) override; 292 293 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 294 295 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override; 296 297 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, 298 bool ReturnAdjustment) override { 299 // Allow inlining of thunks by emitting them with available_externally 300 // linkage together with vtables when needed. 301 if (ForVTable && !Thunk->hasLocalLinkage()) 302 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 303 304 // Propagate dllexport storage, to enable the linker to generate import 305 // thunks as necessary (e.g. when a parent class has a key function and a 306 // child class doesn't, and the construction vtable for the parent in the 307 // child needs to reference the parent's thunks). 308 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 309 if (MD->hasAttr<DLLExportAttr>()) 310 Thunk->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 311 } 312 313 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This, 314 const ThisAdjustment &TA) override; 315 316 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 317 const ReturnAdjustment &RA) override; 318 319 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, 320 FunctionArgList &Args) const override { 321 assert(!Args.empty() && "expected the arglist to not be empty!"); 322 return Args.size() - 1; 323 } 324 325 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; } 326 StringRef GetDeletedVirtualCallName() override 327 { return "__cxa_deleted_virtual"; } 328 329 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 330 Address InitializeArrayCookie(CodeGenFunction &CGF, 331 Address NewPtr, 332 llvm::Value *NumElements, 333 const CXXNewExpr *expr, 334 QualType ElementType) override; 335 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 336 Address allocPtr, 337 CharUnits cookieSize) override; 338 339 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 340 llvm::GlobalVariable *DeclPtr, 341 bool PerformInit) override; 342 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 343 llvm::Constant *dtor, llvm::Constant *addr) override; 344 345 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, 346 llvm::Value *Val); 347 void EmitThreadLocalInitFuncs( 348 CodeGenModule &CGM, 349 ArrayRef<const VarDecl *> CXXThreadLocals, 350 ArrayRef<llvm::Function *> CXXThreadLocalInits, 351 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override; 352 353 bool usesThreadWrapperFunction() const override { return true; } 354 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, 355 QualType LValType) override; 356 357 bool NeedsVTTParameter(GlobalDecl GD) override; 358 359 /**************************** RTTI Uniqueness ******************************/ 360 361 protected: 362 /// Returns true if the ABI requires RTTI type_info objects to be unique 363 /// across a program. 364 virtual bool shouldRTTIBeUnique() const { return true; } 365 366 public: 367 /// What sort of unique-RTTI behavior should we use? 368 enum RTTIUniquenessKind { 369 /// We are guaranteeing, or need to guarantee, that the RTTI string 370 /// is unique. 371 RUK_Unique, 372 373 /// We are not guaranteeing uniqueness for the RTTI string, so we 374 /// can demote to hidden visibility but must use string comparisons. 375 RUK_NonUniqueHidden, 376 377 /// We are not guaranteeing uniqueness for the RTTI string, so we 378 /// have to use string comparisons, but we also have to emit it with 379 /// non-hidden visibility. 380 RUK_NonUniqueVisible 381 }; 382 383 /// Return the required visibility status for the given type and linkage in 384 /// the current ABI. 385 RTTIUniquenessKind 386 classifyRTTIUniqueness(QualType CanTy, 387 llvm::GlobalValue::LinkageTypes Linkage) const; 388 friend class ItaniumRTTIBuilder; 389 390 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; 391 392 private: 393 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const { 394 const auto &VtableLayout = 395 CGM.getItaniumVTableContext().getVTableLayout(RD); 396 397 for (const auto &VtableComponent : VtableLayout.vtable_components()) { 398 // Skip empty slot. 399 if (!VtableComponent.isUsedFunctionPointerKind()) 400 continue; 401 402 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl(); 403 if (!Method->getCanonicalDecl()->isInlined()) 404 continue; 405 406 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl()); 407 auto *Entry = CGM.GetGlobalValue(Name); 408 // This checks if virtual inline function has already been emitted. 409 // Note that it is possible that this inline function would be emitted 410 // after trying to emit vtable speculatively. Because of this we do 411 // an extra pass after emitting all deferred vtables to find and emit 412 // these vtables opportunistically. 413 if (!Entry || Entry->isDeclaration()) 414 return true; 415 } 416 return false; 417 } 418 419 bool isVTableHidden(const CXXRecordDecl *RD) const { 420 const auto &VtableLayout = 421 CGM.getItaniumVTableContext().getVTableLayout(RD); 422 423 for (const auto &VtableComponent : VtableLayout.vtable_components()) { 424 if (VtableComponent.isRTTIKind()) { 425 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl(); 426 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility) 427 return true; 428 } else if (VtableComponent.isUsedFunctionPointerKind()) { 429 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl(); 430 if (Method->getVisibility() == Visibility::HiddenVisibility && 431 !Method->isDefined()) 432 return true; 433 } 434 } 435 return false; 436 } 437 }; 438 439 class ARMCXXABI : public ItaniumCXXABI { 440 public: 441 ARMCXXABI(CodeGen::CodeGenModule &CGM) : 442 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 443 /* UseARMGuardVarABI = */ true) {} 444 445 bool HasThisReturn(GlobalDecl GD) const override { 446 return (isa<CXXConstructorDecl>(GD.getDecl()) || ( 447 isa<CXXDestructorDecl>(GD.getDecl()) && 448 GD.getDtorType() != Dtor_Deleting)); 449 } 450 451 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, 452 QualType ResTy) override; 453 454 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 455 Address InitializeArrayCookie(CodeGenFunction &CGF, 456 Address NewPtr, 457 llvm::Value *NumElements, 458 const CXXNewExpr *expr, 459 QualType ElementType) override; 460 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr, 461 CharUnits cookieSize) override; 462 }; 463 464 class iOS64CXXABI : public ARMCXXABI { 465 public: 466 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) { 467 Use32BitVTableOffsetABI = true; 468 } 469 470 // ARM64 libraries are prepared for non-unique RTTI. 471 bool shouldRTTIBeUnique() const override { return false; } 472 }; 473 474 class WebAssemblyCXXABI final : public ItaniumCXXABI { 475 public: 476 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM) 477 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true, 478 /*UseARMGuardVarABI=*/true) {} 479 480 private: 481 bool HasThisReturn(GlobalDecl GD) const override { 482 return isa<CXXConstructorDecl>(GD.getDecl()) || 483 (isa<CXXDestructorDecl>(GD.getDecl()) && 484 GD.getDtorType() != Dtor_Deleting); 485 } 486 bool canCallMismatchedFunctionType() const override { return false; } 487 }; 488 } 489 490 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 491 switch (CGM.getTarget().getCXXABI().getKind()) { 492 // For IR-generation purposes, there's no significant difference 493 // between the ARM and iOS ABIs. 494 case TargetCXXABI::GenericARM: 495 case TargetCXXABI::iOS: 496 case TargetCXXABI::WatchOS: 497 return new ARMCXXABI(CGM); 498 499 case TargetCXXABI::iOS64: 500 return new iOS64CXXABI(CGM); 501 502 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't 503 // include the other 32-bit ARM oddities: constructor/destructor return values 504 // and array cookies. 505 case TargetCXXABI::GenericAArch64: 506 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 507 /* UseARMGuardVarABI = */ true); 508 509 case TargetCXXABI::GenericMIPS: 510 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true); 511 512 case TargetCXXABI::WebAssembly: 513 return new WebAssemblyCXXABI(CGM); 514 515 case TargetCXXABI::GenericItanium: 516 if (CGM.getContext().getTargetInfo().getTriple().getArch() 517 == llvm::Triple::le32) { 518 // For PNaCl, use ARM-style method pointers so that PNaCl code 519 // does not assume anything about the alignment of function 520 // pointers. 521 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 522 /* UseARMGuardVarABI = */ false); 523 } 524 return new ItaniumCXXABI(CGM); 525 526 case TargetCXXABI::Microsoft: 527 llvm_unreachable("Microsoft ABI is not Itanium-based"); 528 } 529 llvm_unreachable("bad ABI kind"); 530 } 531 532 llvm::Type * 533 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 534 if (MPT->isMemberDataPointer()) 535 return CGM.PtrDiffTy; 536 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy); 537 } 538 539 /// In the Itanium and ARM ABIs, method pointers have the form: 540 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 541 /// 542 /// In the Itanium ABI: 543 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero 544 /// - the this-adjustment is (memptr.adj) 545 /// - the virtual offset is (memptr.ptr - 1) 546 /// 547 /// In the ARM ABI: 548 /// - method pointers are virtual if (memptr.adj & 1) is nonzero 549 /// - the this-adjustment is (memptr.adj >> 1) 550 /// - the virtual offset is (memptr.ptr) 551 /// ARM uses 'adj' for the virtual flag because Thumb functions 552 /// may be only single-byte aligned. 553 /// 554 /// If the member is virtual, the adjusted 'this' pointer points 555 /// to a vtable pointer from which the virtual offset is applied. 556 /// 557 /// If the member is non-virtual, memptr.ptr is the address of 558 /// the function to call. 559 CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer( 560 CodeGenFunction &CGF, const Expr *E, Address ThisAddr, 561 llvm::Value *&ThisPtrForCall, 562 llvm::Value *MemFnPtr, const MemberPointerType *MPT) { 563 CGBuilderTy &Builder = CGF.Builder; 564 565 const FunctionProtoType *FPT = 566 MPT->getPointeeType()->getAs<FunctionProtoType>(); 567 const CXXRecordDecl *RD = 568 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 569 570 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( 571 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); 572 573 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); 574 575 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 576 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 577 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 578 579 // Extract memptr.adj, which is in the second field. 580 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 581 582 // Compute the true adjustment. 583 llvm::Value *Adj = RawAdj; 584 if (UseARMMethodPtrABI) 585 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 586 587 // Apply the adjustment and cast back to the original struct type 588 // for consistency. 589 llvm::Value *This = ThisAddr.getPointer(); 590 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 591 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 592 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 593 ThisPtrForCall = This; 594 595 // Load the function pointer. 596 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 597 598 // If the LSB in the function pointer is 1, the function pointer points to 599 // a virtual function. 600 llvm::Value *IsVirtual; 601 if (UseARMMethodPtrABI) 602 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 603 else 604 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 605 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 606 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 607 608 // In the virtual path, the adjustment left 'This' pointing to the 609 // vtable of the correct base subobject. The "function pointer" is an 610 // offset within the vtable (+1 for the virtual flag on non-ARM). 611 CGF.EmitBlock(FnVirtual); 612 613 // Cast the adjusted this to a pointer to vtable pointer and load. 614 llvm::Type *VTableTy = Builder.getInt8PtrTy(); 615 CharUnits VTablePtrAlign = 616 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD, 617 CGF.getPointerAlign()); 618 llvm::Value *VTable = 619 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD); 620 621 // Apply the offset. 622 // On ARM64, to reserve extra space in virtual member function pointers, 623 // we only pay attention to the low 32 bits of the offset. 624 llvm::Value *VTableOffset = FnAsInt; 625 if (!UseARMMethodPtrABI) 626 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 627 if (Use32BitVTableOffsetABI) { 628 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty); 629 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy); 630 } 631 VTable = Builder.CreateGEP(VTable, VTableOffset); 632 633 // Load the virtual function to call. 634 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 635 llvm::Value *VirtualFn = 636 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(), 637 "memptr.virtualfn"); 638 CGF.EmitBranch(FnEnd); 639 640 // In the non-virtual path, the function pointer is actually a 641 // function pointer. 642 CGF.EmitBlock(FnNonVirtual); 643 llvm::Value *NonVirtualFn = 644 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 645 646 // We're done. 647 CGF.EmitBlock(FnEnd); 648 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2); 649 CalleePtr->addIncoming(VirtualFn, FnVirtual); 650 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual); 651 652 CGCallee Callee(FPT, CalleePtr); 653 return Callee; 654 } 655 656 /// Compute an l-value by applying the given pointer-to-member to a 657 /// base object. 658 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress( 659 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, 660 const MemberPointerType *MPT) { 661 assert(MemPtr->getType() == CGM.PtrDiffTy); 662 663 CGBuilderTy &Builder = CGF.Builder; 664 665 // Cast to char*. 666 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty); 667 668 // Apply the offset, which we assume is non-null. 669 llvm::Value *Addr = 670 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset"); 671 672 // Cast the address to the appropriate pointer type, adopting the 673 // address space of the base pointer. 674 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType()) 675 ->getPointerTo(Base.getAddressSpace()); 676 return Builder.CreateBitCast(Addr, PType); 677 } 678 679 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer 680 /// conversion. 681 /// 682 /// Bitcast conversions are always a no-op under Itanium. 683 /// 684 /// Obligatory offset/adjustment diagram: 685 /// <-- offset --> <-- adjustment --> 686 /// |--------------------------|----------------------|--------------------| 687 /// ^Derived address point ^Base address point ^Member address point 688 /// 689 /// So when converting a base member pointer to a derived member pointer, 690 /// we add the offset to the adjustment because the address point has 691 /// decreased; and conversely, when converting a derived MP to a base MP 692 /// we subtract the offset from the adjustment because the address point 693 /// has increased. 694 /// 695 /// The standard forbids (at compile time) conversion to and from 696 /// virtual bases, which is why we don't have to consider them here. 697 /// 698 /// The standard forbids (at run time) casting a derived MP to a base 699 /// MP when the derived MP does not point to a member of the base. 700 /// This is why -1 is a reasonable choice for null data member 701 /// pointers. 702 llvm::Value * 703 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 704 const CastExpr *E, 705 llvm::Value *src) { 706 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 707 E->getCastKind() == CK_BaseToDerivedMemberPointer || 708 E->getCastKind() == CK_ReinterpretMemberPointer); 709 710 // Under Itanium, reinterprets don't require any additional processing. 711 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 712 713 // Use constant emission if we can. 714 if (isa<llvm::Constant>(src)) 715 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src)); 716 717 llvm::Constant *adj = getMemberPointerAdjustment(E); 718 if (!adj) return src; 719 720 CGBuilderTy &Builder = CGF.Builder; 721 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 722 723 const MemberPointerType *destTy = 724 E->getType()->castAs<MemberPointerType>(); 725 726 // For member data pointers, this is just a matter of adding the 727 // offset if the source is non-null. 728 if (destTy->isMemberDataPointer()) { 729 llvm::Value *dst; 730 if (isDerivedToBase) 731 dst = Builder.CreateNSWSub(src, adj, "adj"); 732 else 733 dst = Builder.CreateNSWAdd(src, adj, "adj"); 734 735 // Null check. 736 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); 737 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); 738 return Builder.CreateSelect(isNull, src, dst); 739 } 740 741 // The this-adjustment is left-shifted by 1 on ARM. 742 if (UseARMMethodPtrABI) { 743 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 744 offset <<= 1; 745 adj = llvm::ConstantInt::get(adj->getType(), offset); 746 } 747 748 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); 749 llvm::Value *dstAdj; 750 if (isDerivedToBase) 751 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); 752 else 753 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); 754 755 return Builder.CreateInsertValue(src, dstAdj, 1); 756 } 757 758 llvm::Constant * 759 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, 760 llvm::Constant *src) { 761 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 762 E->getCastKind() == CK_BaseToDerivedMemberPointer || 763 E->getCastKind() == CK_ReinterpretMemberPointer); 764 765 // Under Itanium, reinterprets don't require any additional processing. 766 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 767 768 // If the adjustment is trivial, we don't need to do anything. 769 llvm::Constant *adj = getMemberPointerAdjustment(E); 770 if (!adj) return src; 771 772 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 773 774 const MemberPointerType *destTy = 775 E->getType()->castAs<MemberPointerType>(); 776 777 // For member data pointers, this is just a matter of adding the 778 // offset if the source is non-null. 779 if (destTy->isMemberDataPointer()) { 780 // null maps to null. 781 if (src->isAllOnesValue()) return src; 782 783 if (isDerivedToBase) 784 return llvm::ConstantExpr::getNSWSub(src, adj); 785 else 786 return llvm::ConstantExpr::getNSWAdd(src, adj); 787 } 788 789 // The this-adjustment is left-shifted by 1 on ARM. 790 if (UseARMMethodPtrABI) { 791 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 792 offset <<= 1; 793 adj = llvm::ConstantInt::get(adj->getType(), offset); 794 } 795 796 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); 797 llvm::Constant *dstAdj; 798 if (isDerivedToBase) 799 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); 800 else 801 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); 802 803 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); 804 } 805 806 llvm::Constant * 807 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 808 // Itanium C++ ABI 2.3: 809 // A NULL pointer is represented as -1. 810 if (MPT->isMemberDataPointer()) 811 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); 812 813 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); 814 llvm::Constant *Values[2] = { Zero, Zero }; 815 return llvm::ConstantStruct::getAnon(Values); 816 } 817 818 llvm::Constant * 819 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 820 CharUnits offset) { 821 // Itanium C++ ABI 2.3: 822 // A pointer to data member is an offset from the base address of 823 // the class object containing it, represented as a ptrdiff_t 824 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); 825 } 826 827 llvm::Constant * 828 ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) { 829 return BuildMemberPointer(MD, CharUnits::Zero()); 830 } 831 832 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, 833 CharUnits ThisAdjustment) { 834 assert(MD->isInstance() && "Member function must not be static!"); 835 MD = MD->getCanonicalDecl(); 836 837 CodeGenTypes &Types = CGM.getTypes(); 838 839 // Get the function pointer (or index if this is a virtual function). 840 llvm::Constant *MemPtr[2]; 841 if (MD->isVirtual()) { 842 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD); 843 844 const ASTContext &Context = getContext(); 845 CharUnits PointerWidth = 846 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 847 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 848 849 if (UseARMMethodPtrABI) { 850 // ARM C++ ABI 3.2.1: 851 // This ABI specifies that adj contains twice the this 852 // adjustment, plus 1 if the member function is virtual. The 853 // least significant bit of adj then makes exactly the same 854 // discrimination as the least significant bit of ptr does for 855 // Itanium. 856 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); 857 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 858 2 * ThisAdjustment.getQuantity() + 1); 859 } else { 860 // Itanium C++ ABI 2.3: 861 // For a virtual function, [the pointer field] is 1 plus the 862 // virtual table offset (in bytes) of the function, 863 // represented as a ptrdiff_t. 864 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); 865 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 866 ThisAdjustment.getQuantity()); 867 } 868 } else { 869 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 870 llvm::Type *Ty; 871 // Check whether the function has a computable LLVM signature. 872 if (Types.isFuncTypeConvertible(FPT)) { 873 // The function has a computable LLVM signature; use the correct type. 874 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 875 } else { 876 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 877 // function type is incomplete. 878 Ty = CGM.PtrDiffTy; 879 } 880 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 881 882 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); 883 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 884 (UseARMMethodPtrABI ? 2 : 1) * 885 ThisAdjustment.getQuantity()); 886 } 887 888 return llvm::ConstantStruct::getAnon(MemPtr); 889 } 890 891 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, 892 QualType MPType) { 893 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 894 const ValueDecl *MPD = MP.getMemberPointerDecl(); 895 if (!MPD) 896 return EmitNullMemberPointer(MPT); 897 898 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 899 900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 901 return BuildMemberPointer(MD, ThisAdjustment); 902 903 CharUnits FieldOffset = 904 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 905 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 906 } 907 908 /// The comparison algorithm is pretty easy: the member pointers are 909 /// the same if they're either bitwise identical *or* both null. 910 /// 911 /// ARM is different here only because null-ness is more complicated. 912 llvm::Value * 913 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 914 llvm::Value *L, 915 llvm::Value *R, 916 const MemberPointerType *MPT, 917 bool Inequality) { 918 CGBuilderTy &Builder = CGF.Builder; 919 920 llvm::ICmpInst::Predicate Eq; 921 llvm::Instruction::BinaryOps And, Or; 922 if (Inequality) { 923 Eq = llvm::ICmpInst::ICMP_NE; 924 And = llvm::Instruction::Or; 925 Or = llvm::Instruction::And; 926 } else { 927 Eq = llvm::ICmpInst::ICMP_EQ; 928 And = llvm::Instruction::And; 929 Or = llvm::Instruction::Or; 930 } 931 932 // Member data pointers are easy because there's a unique null 933 // value, so it just comes down to bitwise equality. 934 if (MPT->isMemberDataPointer()) 935 return Builder.CreateICmp(Eq, L, R); 936 937 // For member function pointers, the tautologies are more complex. 938 // The Itanium tautology is: 939 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 940 // The ARM tautology is: 941 // (L == R) <==> (L.ptr == R.ptr && 942 // (L.adj == R.adj || 943 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 944 // The inequality tautologies have exactly the same structure, except 945 // applying De Morgan's laws. 946 947 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 948 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 949 950 // This condition tests whether L.ptr == R.ptr. This must always be 951 // true for equality to hold. 952 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 953 954 // This condition, together with the assumption that L.ptr == R.ptr, 955 // tests whether the pointers are both null. ARM imposes an extra 956 // condition. 957 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 958 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 959 960 // This condition tests whether L.adj == R.adj. If this isn't 961 // true, the pointers are unequal unless they're both null. 962 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 963 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 964 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 965 966 // Null member function pointers on ARM clear the low bit of Adj, 967 // so the zero condition has to check that neither low bit is set. 968 if (UseARMMethodPtrABI) { 969 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 970 971 // Compute (l.adj | r.adj) & 1 and test it against zero. 972 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 973 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 974 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 975 "cmp.or.adj"); 976 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 977 } 978 979 // Tie together all our conditions. 980 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 981 Result = Builder.CreateBinOp(And, PtrEq, Result, 982 Inequality ? "memptr.ne" : "memptr.eq"); 983 return Result; 984 } 985 986 llvm::Value * 987 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 988 llvm::Value *MemPtr, 989 const MemberPointerType *MPT) { 990 CGBuilderTy &Builder = CGF.Builder; 991 992 /// For member data pointers, this is just a check against -1. 993 if (MPT->isMemberDataPointer()) { 994 assert(MemPtr->getType() == CGM.PtrDiffTy); 995 llvm::Value *NegativeOne = 996 llvm::Constant::getAllOnesValue(MemPtr->getType()); 997 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 998 } 999 1000 // In Itanium, a member function pointer is not null if 'ptr' is not null. 1001 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 1002 1003 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 1004 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 1005 1006 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 1007 // (the virtual bit) is set. 1008 if (UseARMMethodPtrABI) { 1009 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 1010 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 1011 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 1012 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 1013 "memptr.isvirtual"); 1014 Result = Builder.CreateOr(Result, IsVirtual); 1015 } 1016 1017 return Result; 1018 } 1019 1020 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 1021 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 1022 if (!RD) 1023 return false; 1024 1025 // If C++ prohibits us from making a copy, return by address. 1026 if (passClassIndirect(RD)) { 1027 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType()); 1028 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 1029 return true; 1030 } 1031 return false; 1032 } 1033 1034 /// The Itanium ABI requires non-zero initialization only for data 1035 /// member pointers, for which '0' is a valid offset. 1036 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 1037 return MPT->isMemberFunctionPointer(); 1038 } 1039 1040 /// The Itanium ABI always places an offset to the complete object 1041 /// at entry -2 in the vtable. 1042 void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF, 1043 const CXXDeleteExpr *DE, 1044 Address Ptr, 1045 QualType ElementType, 1046 const CXXDestructorDecl *Dtor) { 1047 bool UseGlobalDelete = DE->isGlobalDelete(); 1048 if (UseGlobalDelete) { 1049 // Derive the complete-object pointer, which is what we need 1050 // to pass to the deallocation function. 1051 1052 // Grab the vtable pointer as an intptr_t*. 1053 auto *ClassDecl = 1054 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl()); 1055 llvm::Value *VTable = 1056 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl); 1057 1058 // Track back to entry -2 and pull out the offset there. 1059 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64( 1060 VTable, -2, "complete-offset.ptr"); 1061 llvm::Value *Offset = 1062 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign()); 1063 1064 // Apply the offset. 1065 llvm::Value *CompletePtr = 1066 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy); 1067 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset); 1068 1069 // If we're supposed to call the global delete, make sure we do so 1070 // even if the destructor throws. 1071 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr, 1072 ElementType); 1073 } 1074 1075 // FIXME: Provide a source location here even though there's no 1076 // CXXMemberCallExpr for dtor call. 1077 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting; 1078 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr); 1079 1080 if (UseGlobalDelete) 1081 CGF.PopCleanupBlock(); 1082 } 1083 1084 void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) { 1085 // void __cxa_rethrow(); 1086 1087 llvm::FunctionType *FTy = 1088 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 1089 1090 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow"); 1091 1092 if (isNoReturn) 1093 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None); 1094 else 1095 CGF.EmitRuntimeCallOrInvoke(Fn); 1096 } 1097 1098 static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) { 1099 // void *__cxa_allocate_exception(size_t thrown_size); 1100 1101 llvm::FunctionType *FTy = 1102 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false); 1103 1104 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); 1105 } 1106 1107 static llvm::Constant *getThrowFn(CodeGenModule &CGM) { 1108 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo, 1109 // void (*dest) (void *)); 1110 1111 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy }; 1112 llvm::FunctionType *FTy = 1113 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false); 1114 1115 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); 1116 } 1117 1118 void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) { 1119 QualType ThrowType = E->getSubExpr()->getType(); 1120 // Now allocate the exception object. 1121 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType()); 1122 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity(); 1123 1124 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM); 1125 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall( 1126 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception"); 1127 1128 CharUnits ExnAlign = getAlignmentOfExnObject(); 1129 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign)); 1130 1131 // Now throw the exception. 1132 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, 1133 /*ForEH=*/true); 1134 1135 // The address of the destructor. If the exception type has a 1136 // trivial destructor (or isn't a record), we just pass null. 1137 llvm::Constant *Dtor = nullptr; 1138 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) { 1139 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 1140 if (!Record->hasTrivialDestructor()) { 1141 CXXDestructorDecl *DtorD = Record->getDestructor(); 1142 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete); 1143 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy); 1144 } 1145 } 1146 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy); 1147 1148 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor }; 1149 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args); 1150 } 1151 1152 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) { 1153 // void *__dynamic_cast(const void *sub, 1154 // const abi::__class_type_info *src, 1155 // const abi::__class_type_info *dst, 1156 // std::ptrdiff_t src2dst_offset); 1157 1158 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 1159 llvm::Type *PtrDiffTy = 1160 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1161 1162 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy }; 1163 1164 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false); 1165 1166 // Mark the function as nounwind readonly. 1167 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind, 1168 llvm::Attribute::ReadOnly }; 1169 llvm::AttributeList Attrs = llvm::AttributeList::get( 1170 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs); 1171 1172 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs); 1173 } 1174 1175 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) { 1176 // void __cxa_bad_cast(); 1177 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 1178 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast"); 1179 } 1180 1181 /// \brief Compute the src2dst_offset hint as described in the 1182 /// Itanium C++ ABI [2.9.7] 1183 static CharUnits computeOffsetHint(ASTContext &Context, 1184 const CXXRecordDecl *Src, 1185 const CXXRecordDecl *Dst) { 1186 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1187 /*DetectVirtual=*/false); 1188 1189 // If Dst is not derived from Src we can skip the whole computation below and 1190 // return that Src is not a public base of Dst. Record all inheritance paths. 1191 if (!Dst->isDerivedFrom(Src, Paths)) 1192 return CharUnits::fromQuantity(-2ULL); 1193 1194 unsigned NumPublicPaths = 0; 1195 CharUnits Offset; 1196 1197 // Now walk all possible inheritance paths. 1198 for (const CXXBasePath &Path : Paths) { 1199 if (Path.Access != AS_public) // Ignore non-public inheritance. 1200 continue; 1201 1202 ++NumPublicPaths; 1203 1204 for (const CXXBasePathElement &PathElement : Path) { 1205 // If the path contains a virtual base class we can't give any hint. 1206 // -1: no hint. 1207 if (PathElement.Base->isVirtual()) 1208 return CharUnits::fromQuantity(-1ULL); 1209 1210 if (NumPublicPaths > 1) // Won't use offsets, skip computation. 1211 continue; 1212 1213 // Accumulate the base class offsets. 1214 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class); 1215 Offset += L.getBaseClassOffset( 1216 PathElement.Base->getType()->getAsCXXRecordDecl()); 1217 } 1218 } 1219 1220 // -2: Src is not a public base of Dst. 1221 if (NumPublicPaths == 0) 1222 return CharUnits::fromQuantity(-2ULL); 1223 1224 // -3: Src is a multiple public base type but never a virtual base type. 1225 if (NumPublicPaths > 1) 1226 return CharUnits::fromQuantity(-3ULL); 1227 1228 // Otherwise, the Src type is a unique public nonvirtual base type of Dst. 1229 // Return the offset of Src from the origin of Dst. 1230 return Offset; 1231 } 1232 1233 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) { 1234 // void __cxa_bad_typeid(); 1235 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 1236 1237 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid"); 1238 } 1239 1240 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 1241 QualType SrcRecordTy) { 1242 return IsDeref; 1243 } 1244 1245 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 1246 llvm::Value *Fn = getBadTypeidFn(CGF); 1247 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 1248 CGF.Builder.CreateUnreachable(); 1249 } 1250 1251 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF, 1252 QualType SrcRecordTy, 1253 Address ThisPtr, 1254 llvm::Type *StdTypeInfoPtrTy) { 1255 auto *ClassDecl = 1256 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl()); 1257 llvm::Value *Value = 1258 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl); 1259 1260 // Load the type info. 1261 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL); 1262 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign()); 1263 } 1264 1265 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 1266 QualType SrcRecordTy) { 1267 return SrcIsPtr; 1268 } 1269 1270 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall( 1271 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy, 1272 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 1273 llvm::Type *PtrDiffLTy = 1274 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1275 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1276 1277 llvm::Value *SrcRTTI = 1278 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 1279 llvm::Value *DestRTTI = 1280 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 1281 1282 // Compute the offset hint. 1283 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 1284 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl(); 1285 llvm::Value *OffsetHint = llvm::ConstantInt::get( 1286 PtrDiffLTy, 1287 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity()); 1288 1289 // Emit the call to __dynamic_cast. 1290 llvm::Value *Value = ThisAddr.getPointer(); 1291 Value = CGF.EmitCastToVoidPtr(Value); 1292 1293 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint}; 1294 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args); 1295 Value = CGF.Builder.CreateBitCast(Value, DestLTy); 1296 1297 /// C++ [expr.dynamic.cast]p9: 1298 /// A failed cast to reference type throws std::bad_cast 1299 if (DestTy->isReferenceType()) { 1300 llvm::BasicBlock *BadCastBlock = 1301 CGF.createBasicBlock("dynamic_cast.bad_cast"); 1302 1303 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value); 1304 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd); 1305 1306 CGF.EmitBlock(BadCastBlock); 1307 EmitBadCastCall(CGF); 1308 } 1309 1310 return Value; 1311 } 1312 1313 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, 1314 Address ThisAddr, 1315 QualType SrcRecordTy, 1316 QualType DestTy) { 1317 llvm::Type *PtrDiffLTy = 1318 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1319 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1320 1321 auto *ClassDecl = 1322 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl()); 1323 // Get the vtable pointer. 1324 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(), 1325 ClassDecl); 1326 1327 // Get the offset-to-top from the vtable. 1328 llvm::Value *OffsetToTop = 1329 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL); 1330 OffsetToTop = 1331 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(), 1332 "offset.to.top"); 1333 1334 // Finally, add the offset to the pointer. 1335 llvm::Value *Value = ThisAddr.getPointer(); 1336 Value = CGF.EmitCastToVoidPtr(Value); 1337 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop); 1338 1339 return CGF.Builder.CreateBitCast(Value, DestLTy); 1340 } 1341 1342 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 1343 llvm::Value *Fn = getBadCastFn(CGF); 1344 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 1345 CGF.Builder.CreateUnreachable(); 1346 return true; 1347 } 1348 1349 llvm::Value * 1350 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 1351 Address This, 1352 const CXXRecordDecl *ClassDecl, 1353 const CXXRecordDecl *BaseClassDecl) { 1354 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl); 1355 CharUnits VBaseOffsetOffset = 1356 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl, 1357 BaseClassDecl); 1358 1359 llvm::Value *VBaseOffsetPtr = 1360 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1361 "vbase.offset.ptr"); 1362 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, 1363 CGM.PtrDiffTy->getPointerTo()); 1364 1365 llvm::Value *VBaseOffset = 1366 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(), 1367 "vbase.offset"); 1368 1369 return VBaseOffset; 1370 } 1371 1372 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 1373 // Just make sure we're in sync with TargetCXXABI. 1374 assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); 1375 1376 // The constructor used for constructing this as a base class; 1377 // ignores virtual bases. 1378 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); 1379 1380 // The constructor used for constructing this as a complete class; 1381 // constructs the virtual bases, then calls the base constructor. 1382 if (!D->getParent()->isAbstract()) { 1383 // We don't need to emit the complete ctor if the class is abstract. 1384 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 1385 } 1386 } 1387 1388 CGCXXABI::AddedStructorArgs 1389 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 1390 SmallVectorImpl<CanQualType> &ArgTys) { 1391 ASTContext &Context = getContext(); 1392 1393 // All parameters are already in place except VTT, which goes after 'this'. 1394 // These are Clang types, so we don't need to worry about sret yet. 1395 1396 // Check if we need to add a VTT parameter (which has type void **). 1397 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) { 1398 ArgTys.insert(ArgTys.begin() + 1, 1399 Context.getPointerType(Context.VoidPtrTy)); 1400 return AddedStructorArgs::prefix(1); 1401 } 1402 return AddedStructorArgs{}; 1403 } 1404 1405 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 1406 // The destructor used for destructing this as a base class; ignores 1407 // virtual bases. 1408 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 1409 1410 // The destructor used for destructing this as a most-derived class; 1411 // call the base destructor and then destructs any virtual bases. 1412 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 1413 1414 // The destructor in a virtual table is always a 'deleting' 1415 // destructor, which calls the complete destructor and then uses the 1416 // appropriate operator delete. 1417 if (D->isVirtual()) 1418 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 1419 } 1420 1421 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1422 QualType &ResTy, 1423 FunctionArgList &Params) { 1424 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1425 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1426 1427 // Check if we need a VTT parameter as well. 1428 if (NeedsVTTParameter(CGF.CurGD)) { 1429 ASTContext &Context = getContext(); 1430 1431 // FIXME: avoid the fake decl 1432 QualType T = Context.getPointerType(Context.VoidPtrTy); 1433 auto *VTTDecl = ImplicitParamDecl::Create( 1434 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"), 1435 T, ImplicitParamDecl::CXXVTT); 1436 Params.insert(Params.begin() + 1, VTTDecl); 1437 getStructorImplicitParamDecl(CGF) = VTTDecl; 1438 } 1439 } 1440 1441 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1442 // Naked functions have no prolog. 1443 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>()) 1444 return; 1445 1446 /// Initialize the 'this' slot. 1447 EmitThisParam(CGF); 1448 1449 /// Initialize the 'vtt' slot if needed. 1450 if (getStructorImplicitParamDecl(CGF)) { 1451 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad( 1452 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt"); 1453 } 1454 1455 /// If this is a function that the ABI specifies returns 'this', initialize 1456 /// the return slot to 'this' at the start of the function. 1457 /// 1458 /// Unlike the setting of return types, this is done within the ABI 1459 /// implementation instead of by clients of CGCXXABI because: 1460 /// 1) getThisValue is currently protected 1461 /// 2) in theory, an ABI could implement 'this' returns some other way; 1462 /// HasThisReturn only specifies a contract, not the implementation 1463 if (HasThisReturn(CGF.CurGD)) 1464 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1465 } 1466 1467 CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs( 1468 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1469 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1470 if (!NeedsVTTParameter(GlobalDecl(D, Type))) 1471 return AddedStructorArgs{}; 1472 1473 // Insert the implicit 'vtt' argument as the second argument. 1474 llvm::Value *VTT = 1475 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating); 1476 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1477 Args.insert(Args.begin() + 1, 1478 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false)); 1479 return AddedStructorArgs::prefix(1); // Added one arg. 1480 } 1481 1482 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1483 const CXXDestructorDecl *DD, 1484 CXXDtorType Type, bool ForVirtualBase, 1485 bool Delegating, Address This) { 1486 GlobalDecl GD(DD, Type); 1487 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating); 1488 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1489 1490 CGCallee Callee; 1491 if (getContext().getLangOpts().AppleKext && 1492 Type != Dtor_Base && DD->isVirtual()) 1493 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent()); 1494 else 1495 Callee = 1496 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)), 1497 DD); 1498 1499 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), 1500 This.getPointer(), VTT, VTTTy, 1501 nullptr, nullptr); 1502 } 1503 1504 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1505 const CXXRecordDecl *RD) { 1506 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits()); 1507 if (VTable->hasInitializer()) 1508 return; 1509 1510 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1511 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); 1512 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1513 llvm::Constant *RTTI = 1514 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD)); 1515 1516 // Create and set the initializer. 1517 ConstantInitBuilder Builder(CGM); 1518 auto Components = Builder.beginStruct(); 1519 CGVT.createVTableInitializer(Components, VTLayout, RTTI); 1520 Components.finishAndSetAsInitializer(VTable); 1521 1522 // Set the correct linkage. 1523 VTable->setLinkage(Linkage); 1524 1525 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker()) 1526 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName())); 1527 1528 // Set the right visibility. 1529 CGM.setGlobalVisibility(VTable, RD); 1530 1531 // Use pointer alignment for the vtable. Otherwise we would align them based 1532 // on the size of the initializer which doesn't make sense as only single 1533 // values are read. 1534 unsigned PAlign = CGM.getTarget().getPointerAlign(0); 1535 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity()); 1536 1537 // If this is the magic class __cxxabiv1::__fundamental_type_info, 1538 // we will emit the typeinfo for the fundamental types. This is the 1539 // same behaviour as GCC. 1540 const DeclContext *DC = RD->getDeclContext(); 1541 if (RD->getIdentifier() && 1542 RD->getIdentifier()->isStr("__fundamental_type_info") && 1543 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() && 1544 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 1545 DC->getParent()->isTranslationUnit()) 1546 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>()); 1547 1548 if (!VTable->isDeclarationForLinker()) 1549 CGM.EmitVTableTypeMetadata(VTable, VTLayout); 1550 } 1551 1552 bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField( 1553 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) { 1554 if (Vptr.NearestVBase == nullptr) 1555 return false; 1556 return NeedsVTTParameter(CGF.CurGD); 1557 } 1558 1559 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor( 1560 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1561 const CXXRecordDecl *NearestVBase) { 1562 1563 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) && 1564 NeedsVTTParameter(CGF.CurGD)) { 1565 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base, 1566 NearestVBase); 1567 } 1568 return getVTableAddressPoint(Base, VTableClass); 1569 } 1570 1571 llvm::Constant * 1572 ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base, 1573 const CXXRecordDecl *VTableClass) { 1574 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits()); 1575 1576 // Find the appropriate vtable within the vtable group, and the address point 1577 // within that vtable. 1578 VTableLayout::AddressPointLocation AddressPoint = 1579 CGM.getItaniumVTableContext() 1580 .getVTableLayout(VTableClass) 1581 .getAddressPoint(Base); 1582 llvm::Value *Indices[] = { 1583 llvm::ConstantInt::get(CGM.Int32Ty, 0), 1584 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex), 1585 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex), 1586 }; 1587 1588 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable, 1589 Indices, /*InBounds=*/true, 1590 /*InRangeIndex=*/1); 1591 } 1592 1593 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT( 1594 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1595 const CXXRecordDecl *NearestVBase) { 1596 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) && 1597 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT"); 1598 1599 // Get the secondary vpointer index. 1600 uint64_t VirtualPointerIndex = 1601 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1602 1603 /// Load the VTT. 1604 llvm::Value *VTT = CGF.LoadCXXVTT(); 1605 if (VirtualPointerIndex) 1606 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1607 1608 // And load the address point from the VTT. 1609 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign()); 1610 } 1611 1612 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr( 1613 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1614 return getVTableAddressPoint(Base, VTableClass); 1615 } 1616 1617 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1618 CharUnits VPtrOffset) { 1619 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets"); 1620 1621 llvm::GlobalVariable *&VTable = VTables[RD]; 1622 if (VTable) 1623 return VTable; 1624 1625 // Queue up this vtable for possible deferred emission. 1626 CGM.addDeferredVTable(RD); 1627 1628 SmallString<256> Name; 1629 llvm::raw_svector_ostream Out(Name); 1630 getMangleContext().mangleCXXVTable(RD, Out); 1631 1632 const VTableLayout &VTLayout = 1633 CGM.getItaniumVTableContext().getVTableLayout(RD); 1634 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout); 1635 1636 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 1637 Name, VTableType, llvm::GlobalValue::ExternalLinkage); 1638 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1639 1640 if (RD->hasAttr<DLLImportAttr>()) 1641 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1642 else if (RD->hasAttr<DLLExportAttr>()) 1643 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1644 1645 return VTable; 1646 } 1647 1648 CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1649 GlobalDecl GD, 1650 Address This, 1651 llvm::Type *Ty, 1652 SourceLocation Loc) { 1653 GD = GD.getCanonicalDecl(); 1654 Ty = Ty->getPointerTo()->getPointerTo(); 1655 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl()); 1656 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent()); 1657 1658 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 1659 llvm::Value *VFunc; 1660 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) { 1661 VFunc = CGF.EmitVTableTypeCheckedLoad( 1662 MethodDecl->getParent(), VTable, 1663 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8); 1664 } else { 1665 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc); 1666 1667 llvm::Value *VFuncPtr = 1668 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); 1669 auto *VFuncLoad = 1670 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); 1671 1672 // Add !invariant.load md to virtual function load to indicate that 1673 // function didn't change inside vtable. 1674 // It's safe to add it without -fstrict-vtable-pointers, but it would not 1675 // help in devirtualization because it will only matter if we will have 2 1676 // the same virtual function loads from the same vtable load, which won't 1677 // happen without enabled devirtualization with -fstrict-vtable-pointers. 1678 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 1679 CGM.getCodeGenOpts().StrictVTablePointers) 1680 VFuncLoad->setMetadata( 1681 llvm::LLVMContext::MD_invariant_load, 1682 llvm::MDNode::get(CGM.getLLVMContext(), 1683 llvm::ArrayRef<llvm::Metadata *>())); 1684 VFunc = VFuncLoad; 1685 } 1686 1687 CGCallee Callee(MethodDecl, VFunc); 1688 return Callee; 1689 } 1690 1691 llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall( 1692 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, 1693 Address This, const CXXMemberCallExpr *CE) { 1694 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1695 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1696 1697 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 1698 Dtor, getFromDtorType(DtorType)); 1699 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1700 CGCallee Callee = 1701 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty, 1702 CE ? CE->getLocStart() : SourceLocation()); 1703 1704 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), 1705 This.getPointer(), /*ImplicitParam=*/nullptr, 1706 QualType(), CE, nullptr); 1707 return nullptr; 1708 } 1709 1710 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1711 CodeGenVTables &VTables = CGM.getVTables(); 1712 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); 1713 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD); 1714 } 1715 1716 bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const { 1717 // We don't emit available_externally vtables if we are in -fapple-kext mode 1718 // because kext mode does not permit devirtualization. 1719 if (CGM.getLangOpts().AppleKext) 1720 return false; 1721 1722 // If we don't have any not emitted inline virtual function, and if vtable is 1723 // not hidden, then we are safe to emit available_externally copy of vtable. 1724 // FIXME we can still emit a copy of the vtable if we 1725 // can emit definition of the inline functions. 1726 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD); 1727 } 1728 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF, 1729 Address InitialPtr, 1730 int64_t NonVirtualAdjustment, 1731 int64_t VirtualAdjustment, 1732 bool IsReturnAdjustment) { 1733 if (!NonVirtualAdjustment && !VirtualAdjustment) 1734 return InitialPtr.getPointer(); 1735 1736 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty); 1737 1738 // In a base-to-derived cast, the non-virtual adjustment is applied first. 1739 if (NonVirtualAdjustment && !IsReturnAdjustment) { 1740 V = CGF.Builder.CreateConstInBoundsByteGEP(V, 1741 CharUnits::fromQuantity(NonVirtualAdjustment)); 1742 } 1743 1744 // Perform the virtual adjustment if we have one. 1745 llvm::Value *ResultPtr; 1746 if (VirtualAdjustment) { 1747 llvm::Type *PtrDiffTy = 1748 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1749 1750 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy); 1751 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 1752 1753 llvm::Value *OffsetPtr = 1754 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 1755 1756 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 1757 1758 // Load the adjustment offset from the vtable. 1759 llvm::Value *Offset = 1760 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign()); 1761 1762 // Adjust our pointer. 1763 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset); 1764 } else { 1765 ResultPtr = V.getPointer(); 1766 } 1767 1768 // In a derived-to-base conversion, the non-virtual adjustment is 1769 // applied second. 1770 if (NonVirtualAdjustment && IsReturnAdjustment) { 1771 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr, 1772 NonVirtualAdjustment); 1773 } 1774 1775 // Cast back to the original type. 1776 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType()); 1777 } 1778 1779 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1780 Address This, 1781 const ThisAdjustment &TA) { 1782 return performTypeAdjustment(CGF, This, TA.NonVirtual, 1783 TA.Virtual.Itanium.VCallOffsetOffset, 1784 /*IsReturnAdjustment=*/false); 1785 } 1786 1787 llvm::Value * 1788 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 1789 const ReturnAdjustment &RA) { 1790 return performTypeAdjustment(CGF, Ret, RA.NonVirtual, 1791 RA.Virtual.Itanium.VBaseOffsetOffset, 1792 /*IsReturnAdjustment=*/true); 1793 } 1794 1795 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 1796 RValue RV, QualType ResultType) { 1797 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 1798 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 1799 1800 // Destructor thunks in the ARM ABI have indeterminate results. 1801 llvm::Type *T = CGF.ReturnValue.getElementType(); 1802 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 1803 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 1804 } 1805 1806 /************************** Array allocation cookies **************************/ 1807 1808 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1809 // The array cookie is a size_t; pad that up to the element alignment. 1810 // The cookie is actually right-justified in that space. 1811 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), 1812 CGM.getContext().getTypeAlignInChars(elementType)); 1813 } 1814 1815 Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1816 Address NewPtr, 1817 llvm::Value *NumElements, 1818 const CXXNewExpr *expr, 1819 QualType ElementType) { 1820 assert(requiresArrayCookie(expr)); 1821 1822 unsigned AS = NewPtr.getAddressSpace(); 1823 1824 ASTContext &Ctx = getContext(); 1825 CharUnits SizeSize = CGF.getSizeSize(); 1826 1827 // The size of the cookie. 1828 CharUnits CookieSize = 1829 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 1830 assert(CookieSize == getArrayCookieSizeImpl(ElementType)); 1831 1832 // Compute an offset to the cookie. 1833 Address CookiePtr = NewPtr; 1834 CharUnits CookieOffset = CookieSize - SizeSize; 1835 if (!CookieOffset.isZero()) 1836 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset); 1837 1838 // Write the number of elements into the appropriate slot. 1839 Address NumElementsPtr = 1840 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy); 1841 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr); 1842 1843 // Handle the array cookie specially in ASan. 1844 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 && 1845 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) { 1846 // The store to the CookiePtr does not need to be instrumented. 1847 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI); 1848 llvm::FunctionType *FTy = 1849 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false); 1850 llvm::Constant *F = 1851 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie"); 1852 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer()); 1853 } 1854 1855 // Finally, compute a pointer to the actual data buffer by skipping 1856 // over the cookie completely. 1857 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize); 1858 } 1859 1860 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1861 Address allocPtr, 1862 CharUnits cookieSize) { 1863 // The element size is right-justified in the cookie. 1864 Address numElementsPtr = allocPtr; 1865 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize(); 1866 if (!numElementsOffset.isZero()) 1867 numElementsPtr = 1868 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset); 1869 1870 unsigned AS = allocPtr.getAddressSpace(); 1871 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy); 1872 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0) 1873 return CGF.Builder.CreateLoad(numElementsPtr); 1874 // In asan mode emit a function call instead of a regular load and let the 1875 // run-time deal with it: if the shadow is properly poisoned return the 1876 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs. 1877 // We can't simply ignore this load using nosanitize metadata because 1878 // the metadata may be lost. 1879 llvm::FunctionType *FTy = 1880 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false); 1881 llvm::Constant *F = 1882 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie"); 1883 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer()); 1884 } 1885 1886 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1887 // ARM says that the cookie is always: 1888 // struct array_cookie { 1889 // std::size_t element_size; // element_size != 0 1890 // std::size_t element_count; 1891 // }; 1892 // But the base ABI doesn't give anything an alignment greater than 1893 // 8, so we can dismiss this as typical ABI-author blindness to 1894 // actual language complexity and round up to the element alignment. 1895 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), 1896 CGM.getContext().getTypeAlignInChars(elementType)); 1897 } 1898 1899 Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1900 Address newPtr, 1901 llvm::Value *numElements, 1902 const CXXNewExpr *expr, 1903 QualType elementType) { 1904 assert(requiresArrayCookie(expr)); 1905 1906 // The cookie is always at the start of the buffer. 1907 Address cookie = newPtr; 1908 1909 // The first element is the element size. 1910 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy); 1911 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, 1912 getContext().getTypeSizeInChars(elementType).getQuantity()); 1913 CGF.Builder.CreateStore(elementSize, cookie); 1914 1915 // The second element is the element count. 1916 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize()); 1917 CGF.Builder.CreateStore(numElements, cookie); 1918 1919 // Finally, compute a pointer to the actual data buffer by skipping 1920 // over the cookie completely. 1921 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); 1922 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize); 1923 } 1924 1925 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1926 Address allocPtr, 1927 CharUnits cookieSize) { 1928 // The number of elements is at offset sizeof(size_t) relative to 1929 // the allocated pointer. 1930 Address numElementsPtr 1931 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize()); 1932 1933 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy); 1934 return CGF.Builder.CreateLoad(numElementsPtr); 1935 } 1936 1937 /*********************** Static local initialization **************************/ 1938 1939 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1940 llvm::PointerType *GuardPtrTy) { 1941 // int __cxa_guard_acquire(__guard *guard_object); 1942 llvm::FunctionType *FTy = 1943 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1944 GuardPtrTy, /*isVarArg=*/false); 1945 return CGM.CreateRuntimeFunction( 1946 FTy, "__cxa_guard_acquire", 1947 llvm::AttributeList::get(CGM.getLLVMContext(), 1948 llvm::AttributeList::FunctionIndex, 1949 llvm::Attribute::NoUnwind)); 1950 } 1951 1952 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1953 llvm::PointerType *GuardPtrTy) { 1954 // void __cxa_guard_release(__guard *guard_object); 1955 llvm::FunctionType *FTy = 1956 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1957 return CGM.CreateRuntimeFunction( 1958 FTy, "__cxa_guard_release", 1959 llvm::AttributeList::get(CGM.getLLVMContext(), 1960 llvm::AttributeList::FunctionIndex, 1961 llvm::Attribute::NoUnwind)); 1962 } 1963 1964 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1965 llvm::PointerType *GuardPtrTy) { 1966 // void __cxa_guard_abort(__guard *guard_object); 1967 llvm::FunctionType *FTy = 1968 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1969 return CGM.CreateRuntimeFunction( 1970 FTy, "__cxa_guard_abort", 1971 llvm::AttributeList::get(CGM.getLLVMContext(), 1972 llvm::AttributeList::FunctionIndex, 1973 llvm::Attribute::NoUnwind)); 1974 } 1975 1976 namespace { 1977 struct CallGuardAbort final : EHScopeStack::Cleanup { 1978 llvm::GlobalVariable *Guard; 1979 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1980 1981 void Emit(CodeGenFunction &CGF, Flags flags) override { 1982 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), 1983 Guard); 1984 } 1985 }; 1986 } 1987 1988 /// The ARM code here follows the Itanium code closely enough that we 1989 /// just special-case it at particular places. 1990 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1991 const VarDecl &D, 1992 llvm::GlobalVariable *var, 1993 bool shouldPerformInit) { 1994 CGBuilderTy &Builder = CGF.Builder; 1995 1996 // Inline variables that weren't instantiated from variable templates have 1997 // partially-ordered initialization within their translation unit. 1998 bool NonTemplateInline = 1999 D.isInline() && 2000 !isTemplateInstantiation(D.getTemplateSpecializationKind()); 2001 2002 // We only need to use thread-safe statics for local non-TLS variables and 2003 // inline variables; other global initialization is always single-threaded 2004 // or (through lazy dynamic loading in multiple threads) unsequenced. 2005 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && 2006 (D.isLocalVarDecl() || NonTemplateInline) && 2007 !D.getTLSKind(); 2008 2009 // If we have a global variable with internal linkage and thread-safe statics 2010 // are disabled, we can just let the guard variable be of type i8. 2011 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); 2012 2013 llvm::IntegerType *guardTy; 2014 CharUnits guardAlignment; 2015 if (useInt8GuardVariable) { 2016 guardTy = CGF.Int8Ty; 2017 guardAlignment = CharUnits::One(); 2018 } else { 2019 // Guard variables are 64 bits in the generic ABI and size width on ARM 2020 // (i.e. 32-bit on AArch32, 64-bit on AArch64). 2021 if (UseARMGuardVarABI) { 2022 guardTy = CGF.SizeTy; 2023 guardAlignment = CGF.getSizeAlign(); 2024 } else { 2025 guardTy = CGF.Int64Ty; 2026 guardAlignment = CharUnits::fromQuantity( 2027 CGM.getDataLayout().getABITypeAlignment(guardTy)); 2028 } 2029 } 2030 llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); 2031 2032 // Create the guard variable if we don't already have it (as we 2033 // might if we're double-emitting this function body). 2034 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); 2035 if (!guard) { 2036 // Mangle the name for the guard. 2037 SmallString<256> guardName; 2038 { 2039 llvm::raw_svector_ostream out(guardName); 2040 getMangleContext().mangleStaticGuardVariable(&D, out); 2041 } 2042 2043 // Create the guard variable with a zero-initializer. 2044 // Just absorb linkage and visibility from the guarded variable. 2045 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, 2046 false, var->getLinkage(), 2047 llvm::ConstantInt::get(guardTy, 0), 2048 guardName.str()); 2049 guard->setVisibility(var->getVisibility()); 2050 // If the variable is thread-local, so is its guard variable. 2051 guard->setThreadLocalMode(var->getThreadLocalMode()); 2052 guard->setAlignment(guardAlignment.getQuantity()); 2053 2054 // The ABI says: "It is suggested that it be emitted in the same COMDAT 2055 // group as the associated data object." In practice, this doesn't work for 2056 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm. 2057 llvm::Comdat *C = var->getComdat(); 2058 if (!D.isLocalVarDecl() && C && 2059 (CGM.getTarget().getTriple().isOSBinFormatELF() || 2060 CGM.getTarget().getTriple().isOSBinFormatWasm())) { 2061 guard->setComdat(C); 2062 // An inline variable's guard function is run from the per-TU 2063 // initialization function, not via a dedicated global ctor function, so 2064 // we can't put it in a comdat. 2065 if (!NonTemplateInline) 2066 CGF.CurFn->setComdat(C); 2067 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) { 2068 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName())); 2069 } 2070 2071 CGM.setStaticLocalDeclGuardAddress(&D, guard); 2072 } 2073 2074 Address guardAddr = Address(guard, guardAlignment); 2075 2076 // Test whether the variable has completed initialization. 2077 // 2078 // Itanium C++ ABI 3.3.2: 2079 // The following is pseudo-code showing how these functions can be used: 2080 // if (obj_guard.first_byte == 0) { 2081 // if ( __cxa_guard_acquire (&obj_guard) ) { 2082 // try { 2083 // ... initialize the object ...; 2084 // } catch (...) { 2085 // __cxa_guard_abort (&obj_guard); 2086 // throw; 2087 // } 2088 // ... queue object destructor with __cxa_atexit() ...; 2089 // __cxa_guard_release (&obj_guard); 2090 // } 2091 // } 2092 2093 // Load the first byte of the guard variable. 2094 llvm::LoadInst *LI = 2095 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty)); 2096 2097 // Itanium ABI: 2098 // An implementation supporting thread-safety on multiprocessor 2099 // systems must also guarantee that references to the initialized 2100 // object do not occur before the load of the initialization flag. 2101 // 2102 // In LLVM, we do this by marking the load Acquire. 2103 if (threadsafe) 2104 LI->setAtomic(llvm::AtomicOrdering::Acquire); 2105 2106 // For ARM, we should only check the first bit, rather than the entire byte: 2107 // 2108 // ARM C++ ABI 3.2.3.1: 2109 // To support the potential use of initialization guard variables 2110 // as semaphores that are the target of ARM SWP and LDREX/STREX 2111 // synchronizing instructions we define a static initialization 2112 // guard variable to be a 4-byte aligned, 4-byte word with the 2113 // following inline access protocol. 2114 // #define INITIALIZED 1 2115 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 2116 // if (__cxa_guard_acquire(&obj_guard)) 2117 // ... 2118 // } 2119 // 2120 // and similarly for ARM64: 2121 // 2122 // ARM64 C++ ABI 3.2.2: 2123 // This ABI instead only specifies the value bit 0 of the static guard 2124 // variable; all other bits are platform defined. Bit 0 shall be 0 when the 2125 // variable is not initialized and 1 when it is. 2126 llvm::Value *V = 2127 (UseARMGuardVarABI && !useInt8GuardVariable) 2128 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1)) 2129 : LI; 2130 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized"); 2131 2132 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 2133 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 2134 2135 // Check if the first byte of the guard variable is zero. 2136 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock, 2137 CodeGenFunction::GuardKind::VariableGuard, &D); 2138 2139 CGF.EmitBlock(InitCheckBlock); 2140 2141 // Variables used when coping with thread-safe statics and exceptions. 2142 if (threadsafe) { 2143 // Call __cxa_guard_acquire. 2144 llvm::Value *V 2145 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); 2146 2147 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 2148 2149 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 2150 InitBlock, EndBlock); 2151 2152 // Call __cxa_guard_abort along the exceptional edge. 2153 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard); 2154 2155 CGF.EmitBlock(InitBlock); 2156 } 2157 2158 // Emit the initializer and add a global destructor if appropriate. 2159 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); 2160 2161 if (threadsafe) { 2162 // Pop the guard-abort cleanup if we pushed one. 2163 CGF.PopCleanupBlock(); 2164 2165 // Call __cxa_guard_release. This cannot throw. 2166 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), 2167 guardAddr.getPointer()); 2168 } else { 2169 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr); 2170 } 2171 2172 CGF.EmitBlock(EndBlock); 2173 } 2174 2175 /// Register a global destructor using __cxa_atexit. 2176 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, 2177 llvm::Constant *dtor, 2178 llvm::Constant *addr, 2179 bool TLS) { 2180 const char *Name = "__cxa_atexit"; 2181 if (TLS) { 2182 const llvm::Triple &T = CGF.getTarget().getTriple(); 2183 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit"; 2184 } 2185 2186 // We're assuming that the destructor function is something we can 2187 // reasonably call with the default CC. Go ahead and cast it to the 2188 // right prototype. 2189 llvm::Type *dtorTy = 2190 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); 2191 2192 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); 2193 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; 2194 llvm::FunctionType *atexitTy = 2195 llvm::FunctionType::get(CGF.IntTy, paramTys, false); 2196 2197 // Fetch the actual function. 2198 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); 2199 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit)) 2200 fn->setDoesNotThrow(); 2201 2202 // Create a variable that binds the atexit to this shared object. 2203 llvm::Constant *handle = 2204 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); 2205 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts()); 2206 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 2207 2208 llvm::Value *args[] = { 2209 llvm::ConstantExpr::getBitCast(dtor, dtorTy), 2210 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), 2211 handle 2212 }; 2213 CGF.EmitNounwindRuntimeCall(atexit, args); 2214 } 2215 2216 /// Register a global destructor as best as we know how. 2217 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, 2218 const VarDecl &D, 2219 llvm::Constant *dtor, 2220 llvm::Constant *addr) { 2221 // Use __cxa_atexit if available. 2222 if (CGM.getCodeGenOpts().CXAAtExit) 2223 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); 2224 2225 if (D.getTLSKind()) 2226 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); 2227 2228 // In Apple kexts, we want to add a global destructor entry. 2229 // FIXME: shouldn't this be guarded by some variable? 2230 if (CGM.getLangOpts().AppleKext) { 2231 // Generate a global destructor entry. 2232 return CGM.AddCXXDtorEntry(dtor, addr); 2233 } 2234 2235 CGF.registerGlobalDtorWithAtExit(D, dtor, addr); 2236 } 2237 2238 static bool isThreadWrapperReplaceable(const VarDecl *VD, 2239 CodeGen::CodeGenModule &CGM) { 2240 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!"); 2241 // Darwin prefers to have references to thread local variables to go through 2242 // the thread wrapper instead of directly referencing the backing variable. 2243 return VD->getTLSKind() == VarDecl::TLS_Dynamic && 2244 CGM.getTarget().getTriple().isOSDarwin(); 2245 } 2246 2247 /// Get the appropriate linkage for the wrapper function. This is essentially 2248 /// the weak form of the variable's linkage; every translation unit which needs 2249 /// the wrapper emits a copy, and we want the linker to merge them. 2250 static llvm::GlobalValue::LinkageTypes 2251 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) { 2252 llvm::GlobalValue::LinkageTypes VarLinkage = 2253 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false); 2254 2255 // For internal linkage variables, we don't need an external or weak wrapper. 2256 if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) 2257 return VarLinkage; 2258 2259 // If the thread wrapper is replaceable, give it appropriate linkage. 2260 if (isThreadWrapperReplaceable(VD, CGM)) 2261 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) && 2262 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage)) 2263 return VarLinkage; 2264 return llvm::GlobalValue::WeakODRLinkage; 2265 } 2266 2267 llvm::Function * 2268 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, 2269 llvm::Value *Val) { 2270 // Mangle the name for the thread_local wrapper function. 2271 SmallString<256> WrapperName; 2272 { 2273 llvm::raw_svector_ostream Out(WrapperName); 2274 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); 2275 } 2276 2277 // FIXME: If VD is a definition, we should regenerate the function attributes 2278 // before returning. 2279 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName)) 2280 return cast<llvm::Function>(V); 2281 2282 QualType RetQT = VD->getType(); 2283 if (RetQT->isReferenceType()) 2284 RetQT = RetQT.getNonReferenceType(); 2285 2286 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( 2287 getContext().getPointerType(RetQT), FunctionArgList()); 2288 2289 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI); 2290 llvm::Function *Wrapper = 2291 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM), 2292 WrapperName.str(), &CGM.getModule()); 2293 2294 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper); 2295 2296 if (VD->hasDefinition()) 2297 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper); 2298 2299 // Always resolve references to the wrapper at link time. 2300 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) && 2301 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) && 2302 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()))) 2303 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); 2304 2305 if (isThreadWrapperReplaceable(VD, CGM)) { 2306 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2307 Wrapper->addFnAttr(llvm::Attribute::NoUnwind); 2308 } 2309 return Wrapper; 2310 } 2311 2312 void ItaniumCXXABI::EmitThreadLocalInitFuncs( 2313 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals, 2314 ArrayRef<llvm::Function *> CXXThreadLocalInits, 2315 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) { 2316 llvm::Function *InitFunc = nullptr; 2317 2318 // Separate initializers into those with ordered (or partially-ordered) 2319 // initialization and those with unordered initialization. 2320 llvm::SmallVector<llvm::Function *, 8> OrderedInits; 2321 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits; 2322 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) { 2323 if (isTemplateInstantiation( 2324 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind())) 2325 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] = 2326 CXXThreadLocalInits[I]; 2327 else 2328 OrderedInits.push_back(CXXThreadLocalInits[I]); 2329 } 2330 2331 if (!OrderedInits.empty()) { 2332 // Generate a guarded initialization function. 2333 llvm::FunctionType *FTy = 2334 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 2335 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2336 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI, 2337 SourceLocation(), 2338 /*TLS=*/true); 2339 llvm::GlobalVariable *Guard = new llvm::GlobalVariable( 2340 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false, 2341 llvm::GlobalVariable::InternalLinkage, 2342 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard"); 2343 Guard->setThreadLocal(true); 2344 2345 CharUnits GuardAlign = CharUnits::One(); 2346 Guard->setAlignment(GuardAlign.getQuantity()); 2347 2348 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits, 2349 Address(Guard, GuardAlign)); 2350 // On Darwin platforms, use CXX_FAST_TLS calling convention. 2351 if (CGM.getTarget().getTriple().isOSDarwin()) { 2352 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2353 InitFunc->addFnAttr(llvm::Attribute::NoUnwind); 2354 } 2355 } 2356 2357 // Emit thread wrappers. 2358 for (const VarDecl *VD : CXXThreadLocals) { 2359 llvm::GlobalVariable *Var = 2360 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD))); 2361 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); 2362 2363 // Some targets require that all access to thread local variables go through 2364 // the thread wrapper. This means that we cannot attempt to create a thread 2365 // wrapper or a thread helper. 2366 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) { 2367 Wrapper->setLinkage(llvm::Function::ExternalLinkage); 2368 continue; 2369 } 2370 2371 // Mangle the name for the thread_local initialization function. 2372 SmallString<256> InitFnName; 2373 { 2374 llvm::raw_svector_ostream Out(InitFnName); 2375 getMangleContext().mangleItaniumThreadLocalInit(VD, Out); 2376 } 2377 2378 // If we have a definition for the variable, emit the initialization 2379 // function as an alias to the global Init function (if any). Otherwise, 2380 // produce a declaration of the initialization function. 2381 llvm::GlobalValue *Init = nullptr; 2382 bool InitIsInitFunc = false; 2383 if (VD->hasDefinition()) { 2384 InitIsInitFunc = true; 2385 llvm::Function *InitFuncToUse = InitFunc; 2386 if (isTemplateInstantiation(VD->getTemplateSpecializationKind())) 2387 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl()); 2388 if (InitFuncToUse) 2389 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(), 2390 InitFuncToUse); 2391 } else { 2392 // Emit a weak global function referring to the initialization function. 2393 // This function will not exist if the TU defining the thread_local 2394 // variable in question does not need any dynamic initialization for 2395 // its thread_local variables. 2396 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); 2397 Init = llvm::Function::Create(FnTy, 2398 llvm::GlobalVariable::ExternalWeakLinkage, 2399 InitFnName.str(), &CGM.getModule()); 2400 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2401 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init)); 2402 } 2403 2404 if (Init) 2405 Init->setVisibility(Var->getVisibility()); 2406 2407 llvm::LLVMContext &Context = CGM.getModule().getContext(); 2408 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 2409 CGBuilderTy Builder(CGM, Entry); 2410 if (InitIsInitFunc) { 2411 if (Init) { 2412 llvm::CallInst *CallVal = Builder.CreateCall(Init); 2413 if (isThreadWrapperReplaceable(VD, CGM)) 2414 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2415 } 2416 } else { 2417 // Don't know whether we have an init function. Call it if it exists. 2418 llvm::Value *Have = Builder.CreateIsNotNull(Init); 2419 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 2420 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 2421 Builder.CreateCondBr(Have, InitBB, ExitBB); 2422 2423 Builder.SetInsertPoint(InitBB); 2424 Builder.CreateCall(Init); 2425 Builder.CreateBr(ExitBB); 2426 2427 Builder.SetInsertPoint(ExitBB); 2428 } 2429 2430 // For a reference, the result of the wrapper function is a pointer to 2431 // the referenced object. 2432 llvm::Value *Val = Var; 2433 if (VD->getType()->isReferenceType()) { 2434 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2435 Val = Builder.CreateAlignedLoad(Val, Align); 2436 } 2437 if (Val->getType() != Wrapper->getReturnType()) 2438 Val = Builder.CreatePointerBitCastOrAddrSpaceCast( 2439 Val, Wrapper->getReturnType(), ""); 2440 Builder.CreateRet(Val); 2441 } 2442 } 2443 2444 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2445 const VarDecl *VD, 2446 QualType LValType) { 2447 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD); 2448 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val); 2449 2450 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper); 2451 CallVal->setCallingConv(Wrapper->getCallingConv()); 2452 2453 LValue LV; 2454 if (VD->getType()->isReferenceType()) 2455 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType); 2456 else 2457 LV = CGF.MakeAddrLValue(CallVal, LValType, 2458 CGF.getContext().getDeclAlign(VD)); 2459 // FIXME: need setObjCGCLValueClass? 2460 return LV; 2461 } 2462 2463 /// Return whether the given global decl needs a VTT parameter, which it does 2464 /// if it's a base constructor or destructor with virtual bases. 2465 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 2466 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2467 2468 // We don't have any virtual bases, just return early. 2469 if (!MD->getParent()->getNumVBases()) 2470 return false; 2471 2472 // Check if we have a base constructor. 2473 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 2474 return true; 2475 2476 // Check if we have a base destructor. 2477 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 2478 return true; 2479 2480 return false; 2481 } 2482 2483 namespace { 2484 class ItaniumRTTIBuilder { 2485 CodeGenModule &CGM; // Per-module state. 2486 llvm::LLVMContext &VMContext; 2487 const ItaniumCXXABI &CXXABI; // Per-module state. 2488 2489 /// Fields - The fields of the RTTI descriptor currently being built. 2490 SmallVector<llvm::Constant *, 16> Fields; 2491 2492 /// GetAddrOfTypeName - Returns the mangled type name of the given type. 2493 llvm::GlobalVariable * 2494 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage); 2495 2496 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 2497 /// descriptor of the given type. 2498 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty); 2499 2500 /// BuildVTablePointer - Build the vtable pointer for the given type. 2501 void BuildVTablePointer(const Type *Ty); 2502 2503 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2504 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b. 2505 void BuildSIClassTypeInfo(const CXXRecordDecl *RD); 2506 2507 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2508 /// classes with bases that do not satisfy the abi::__si_class_type_info 2509 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2510 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD); 2511 2512 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used 2513 /// for pointer types. 2514 void BuildPointerTypeInfo(QualType PointeeTy); 2515 2516 /// BuildObjCObjectTypeInfo - Build the appropriate kind of 2517 /// type_info for an object type. 2518 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty); 2519 2520 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2521 /// struct, used for member pointer types. 2522 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty); 2523 2524 public: 2525 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI) 2526 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {} 2527 2528 // Pointer type info flags. 2529 enum { 2530 /// PTI_Const - Type has const qualifier. 2531 PTI_Const = 0x1, 2532 2533 /// PTI_Volatile - Type has volatile qualifier. 2534 PTI_Volatile = 0x2, 2535 2536 /// PTI_Restrict - Type has restrict qualifier. 2537 PTI_Restrict = 0x4, 2538 2539 /// PTI_Incomplete - Type is incomplete. 2540 PTI_Incomplete = 0x8, 2541 2542 /// PTI_ContainingClassIncomplete - Containing class is incomplete. 2543 /// (in pointer to member). 2544 PTI_ContainingClassIncomplete = 0x10, 2545 2546 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS). 2547 //PTI_TransactionSafe = 0x20, 2548 2549 /// PTI_Noexcept - Pointee is noexcept function (C++1z). 2550 PTI_Noexcept = 0x40, 2551 }; 2552 2553 // VMI type info flags. 2554 enum { 2555 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance. 2556 VMI_NonDiamondRepeat = 0x1, 2557 2558 /// VMI_DiamondShaped - Class is diamond shaped. 2559 VMI_DiamondShaped = 0x2 2560 }; 2561 2562 // Base class type info flags. 2563 enum { 2564 /// BCTI_Virtual - Base class is virtual. 2565 BCTI_Virtual = 0x1, 2566 2567 /// BCTI_Public - Base class is public. 2568 BCTI_Public = 0x2 2569 }; 2570 2571 /// BuildTypeInfo - Build the RTTI type info struct for the given type. 2572 /// 2573 /// \param Force - true to force the creation of this RTTI value 2574 /// \param DLLExport - true to mark the RTTI value as DLLExport 2575 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false, 2576 bool DLLExport = false); 2577 }; 2578 } 2579 2580 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName( 2581 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) { 2582 SmallString<256> Name; 2583 llvm::raw_svector_ostream Out(Name); 2584 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out); 2585 2586 // We know that the mangled name of the type starts at index 4 of the 2587 // mangled name of the typename, so we can just index into it in order to 2588 // get the mangled name of the type. 2589 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 2590 Name.substr(4)); 2591 2592 llvm::GlobalVariable *GV = 2593 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage); 2594 2595 GV->setInitializer(Init); 2596 2597 return GV; 2598 } 2599 2600 llvm::Constant * 2601 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) { 2602 // Mangle the RTTI name. 2603 SmallString<256> Name; 2604 llvm::raw_svector_ostream Out(Name); 2605 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2606 2607 // Look for an existing global. 2608 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name); 2609 2610 if (!GV) { 2611 // Create a new global variable. 2612 // Note for the future: If we would ever like to do deferred emission of 2613 // RTTI, check if emitting vtables opportunistically need any adjustment. 2614 2615 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 2616 /*Constant=*/true, 2617 llvm::GlobalValue::ExternalLinkage, nullptr, 2618 Name); 2619 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2620 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2621 if (RD->hasAttr<DLLImportAttr>()) 2622 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 2623 } 2624 } 2625 2626 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2627 } 2628 2629 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type 2630 /// info for that type is defined in the standard library. 2631 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) { 2632 // Itanium C++ ABI 2.9.2: 2633 // Basic type information (e.g. for "int", "bool", etc.) will be kept in 2634 // the run-time support library. Specifically, the run-time support 2635 // library should contain type_info objects for the types X, X* and 2636 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char, 2637 // unsigned char, signed char, short, unsigned short, int, unsigned int, 2638 // long, unsigned long, long long, unsigned long long, float, double, 2639 // long double, char16_t, char32_t, and the IEEE 754r decimal and 2640 // half-precision floating point types. 2641 // 2642 // GCC also emits RTTI for __int128. 2643 // FIXME: We do not emit RTTI information for decimal types here. 2644 2645 // Types added here must also be added to EmitFundamentalRTTIDescriptors. 2646 switch (Ty->getKind()) { 2647 case BuiltinType::Void: 2648 case BuiltinType::NullPtr: 2649 case BuiltinType::Bool: 2650 case BuiltinType::WChar_S: 2651 case BuiltinType::WChar_U: 2652 case BuiltinType::Char_U: 2653 case BuiltinType::Char_S: 2654 case BuiltinType::UChar: 2655 case BuiltinType::SChar: 2656 case BuiltinType::Short: 2657 case BuiltinType::UShort: 2658 case BuiltinType::Int: 2659 case BuiltinType::UInt: 2660 case BuiltinType::Long: 2661 case BuiltinType::ULong: 2662 case BuiltinType::LongLong: 2663 case BuiltinType::ULongLong: 2664 case BuiltinType::Half: 2665 case BuiltinType::Float: 2666 case BuiltinType::Double: 2667 case BuiltinType::LongDouble: 2668 case BuiltinType::Float16: 2669 case BuiltinType::Float128: 2670 case BuiltinType::Char16: 2671 case BuiltinType::Char32: 2672 case BuiltinType::Int128: 2673 case BuiltinType::UInt128: 2674 return true; 2675 2676 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2677 case BuiltinType::Id: 2678 #include "clang/Basic/OpenCLImageTypes.def" 2679 case BuiltinType::OCLSampler: 2680 case BuiltinType::OCLEvent: 2681 case BuiltinType::OCLClkEvent: 2682 case BuiltinType::OCLQueue: 2683 case BuiltinType::OCLReserveID: 2684 return false; 2685 2686 case BuiltinType::Dependent: 2687 #define BUILTIN_TYPE(Id, SingletonId) 2688 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2689 case BuiltinType::Id: 2690 #include "clang/AST/BuiltinTypes.def" 2691 llvm_unreachable("asking for RRTI for a placeholder type!"); 2692 2693 case BuiltinType::ObjCId: 2694 case BuiltinType::ObjCClass: 2695 case BuiltinType::ObjCSel: 2696 llvm_unreachable("FIXME: Objective-C types are unsupported!"); 2697 } 2698 2699 llvm_unreachable("Invalid BuiltinType Kind!"); 2700 } 2701 2702 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) { 2703 QualType PointeeTy = PointerTy->getPointeeType(); 2704 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy); 2705 if (!BuiltinTy) 2706 return false; 2707 2708 // Check the qualifiers. 2709 Qualifiers Quals = PointeeTy.getQualifiers(); 2710 Quals.removeConst(); 2711 2712 if (!Quals.empty()) 2713 return false; 2714 2715 return TypeInfoIsInStandardLibrary(BuiltinTy); 2716 } 2717 2718 /// IsStandardLibraryRTTIDescriptor - Returns whether the type 2719 /// information for the given type exists in the standard library. 2720 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) { 2721 // Type info for builtin types is defined in the standard library. 2722 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty)) 2723 return TypeInfoIsInStandardLibrary(BuiltinTy); 2724 2725 // Type info for some pointer types to builtin types is defined in the 2726 // standard library. 2727 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2728 return TypeInfoIsInStandardLibrary(PointerTy); 2729 2730 return false; 2731 } 2732 2733 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for 2734 /// the given type exists somewhere else, and that we should not emit the type 2735 /// information in this translation unit. Assumes that it is not a 2736 /// standard-library type. 2737 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, 2738 QualType Ty) { 2739 ASTContext &Context = CGM.getContext(); 2740 2741 // If RTTI is disabled, assume it might be disabled in the 2742 // translation unit that defines any potential key function, too. 2743 if (!Context.getLangOpts().RTTI) return false; 2744 2745 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2746 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2747 if (!RD->hasDefinition()) 2748 return false; 2749 2750 if (!RD->isDynamicClass()) 2751 return false; 2752 2753 // FIXME: this may need to be reconsidered if the key function 2754 // changes. 2755 // N.B. We must always emit the RTTI data ourselves if there exists a key 2756 // function. 2757 bool IsDLLImport = RD->hasAttr<DLLImportAttr>(); 2758 if (CGM.getVTables().isVTableExternal(RD)) 2759 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment() 2760 ? false 2761 : true; 2762 2763 if (IsDLLImport) 2764 return true; 2765 } 2766 2767 return false; 2768 } 2769 2770 /// IsIncompleteClassType - Returns whether the given record type is incomplete. 2771 static bool IsIncompleteClassType(const RecordType *RecordTy) { 2772 return !RecordTy->getDecl()->isCompleteDefinition(); 2773 } 2774 2775 /// ContainsIncompleteClassType - Returns whether the given type contains an 2776 /// incomplete class type. This is true if 2777 /// 2778 /// * The given type is an incomplete class type. 2779 /// * The given type is a pointer type whose pointee type contains an 2780 /// incomplete class type. 2781 /// * The given type is a member pointer type whose class is an incomplete 2782 /// class type. 2783 /// * The given type is a member pointer type whoise pointee type contains an 2784 /// incomplete class type. 2785 /// is an indirect or direct pointer to an incomplete class type. 2786 static bool ContainsIncompleteClassType(QualType Ty) { 2787 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2788 if (IsIncompleteClassType(RecordTy)) 2789 return true; 2790 } 2791 2792 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2793 return ContainsIncompleteClassType(PointerTy->getPointeeType()); 2794 2795 if (const MemberPointerType *MemberPointerTy = 2796 dyn_cast<MemberPointerType>(Ty)) { 2797 // Check if the class type is incomplete. 2798 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass()); 2799 if (IsIncompleteClassType(ClassType)) 2800 return true; 2801 2802 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType()); 2803 } 2804 2805 return false; 2806 } 2807 2808 // CanUseSingleInheritance - Return whether the given record decl has a "single, 2809 // public, non-virtual base at offset zero (i.e. the derived class is dynamic 2810 // iff the base is)", according to Itanium C++ ABI, 2.95p6b. 2811 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) { 2812 // Check the number of bases. 2813 if (RD->getNumBases() != 1) 2814 return false; 2815 2816 // Get the base. 2817 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(); 2818 2819 // Check that the base is not virtual. 2820 if (Base->isVirtual()) 2821 return false; 2822 2823 // Check that the base is public. 2824 if (Base->getAccessSpecifier() != AS_public) 2825 return false; 2826 2827 // Check that the class is dynamic iff the base is. 2828 const CXXRecordDecl *BaseDecl = 2829 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2830 if (!BaseDecl->isEmpty() && 2831 BaseDecl->isDynamicClass() != RD->isDynamicClass()) 2832 return false; 2833 2834 return true; 2835 } 2836 2837 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) { 2838 // abi::__class_type_info. 2839 static const char * const ClassTypeInfo = 2840 "_ZTVN10__cxxabiv117__class_type_infoE"; 2841 // abi::__si_class_type_info. 2842 static const char * const SIClassTypeInfo = 2843 "_ZTVN10__cxxabiv120__si_class_type_infoE"; 2844 // abi::__vmi_class_type_info. 2845 static const char * const VMIClassTypeInfo = 2846 "_ZTVN10__cxxabiv121__vmi_class_type_infoE"; 2847 2848 const char *VTableName = nullptr; 2849 2850 switch (Ty->getTypeClass()) { 2851 #define TYPE(Class, Base) 2852 #define ABSTRACT_TYPE(Class, Base) 2853 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2854 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2855 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2856 #include "clang/AST/TypeNodes.def" 2857 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2858 2859 case Type::LValueReference: 2860 case Type::RValueReference: 2861 llvm_unreachable("References shouldn't get here"); 2862 2863 case Type::Auto: 2864 case Type::DeducedTemplateSpecialization: 2865 llvm_unreachable("Undeduced type shouldn't get here"); 2866 2867 case Type::Pipe: 2868 llvm_unreachable("Pipe types shouldn't get here"); 2869 2870 case Type::Builtin: 2871 // GCC treats vector and complex types as fundamental types. 2872 case Type::Vector: 2873 case Type::ExtVector: 2874 case Type::Complex: 2875 case Type::Atomic: 2876 // FIXME: GCC treats block pointers as fundamental types?! 2877 case Type::BlockPointer: 2878 // abi::__fundamental_type_info. 2879 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE"; 2880 break; 2881 2882 case Type::ConstantArray: 2883 case Type::IncompleteArray: 2884 case Type::VariableArray: 2885 // abi::__array_type_info. 2886 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE"; 2887 break; 2888 2889 case Type::FunctionNoProto: 2890 case Type::FunctionProto: 2891 // abi::__function_type_info. 2892 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE"; 2893 break; 2894 2895 case Type::Enum: 2896 // abi::__enum_type_info. 2897 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE"; 2898 break; 2899 2900 case Type::Record: { 2901 const CXXRecordDecl *RD = 2902 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2903 2904 if (!RD->hasDefinition() || !RD->getNumBases()) { 2905 VTableName = ClassTypeInfo; 2906 } else if (CanUseSingleInheritance(RD)) { 2907 VTableName = SIClassTypeInfo; 2908 } else { 2909 VTableName = VMIClassTypeInfo; 2910 } 2911 2912 break; 2913 } 2914 2915 case Type::ObjCObject: 2916 // Ignore protocol qualifiers. 2917 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr(); 2918 2919 // Handle id and Class. 2920 if (isa<BuiltinType>(Ty)) { 2921 VTableName = ClassTypeInfo; 2922 break; 2923 } 2924 2925 assert(isa<ObjCInterfaceType>(Ty)); 2926 // Fall through. 2927 2928 case Type::ObjCInterface: 2929 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) { 2930 VTableName = SIClassTypeInfo; 2931 } else { 2932 VTableName = ClassTypeInfo; 2933 } 2934 break; 2935 2936 case Type::ObjCObjectPointer: 2937 case Type::Pointer: 2938 // abi::__pointer_type_info. 2939 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE"; 2940 break; 2941 2942 case Type::MemberPointer: 2943 // abi::__pointer_to_member_type_info. 2944 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE"; 2945 break; 2946 } 2947 2948 llvm::Constant *VTable = 2949 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); 2950 2951 llvm::Type *PtrDiffTy = 2952 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 2953 2954 // The vtable address point is 2. 2955 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2); 2956 VTable = 2957 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two); 2958 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy); 2959 2960 Fields.push_back(VTable); 2961 } 2962 2963 /// \brief Return the linkage that the type info and type info name constants 2964 /// should have for the given type. 2965 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM, 2966 QualType Ty) { 2967 // Itanium C++ ABI 2.9.5p7: 2968 // In addition, it and all of the intermediate abi::__pointer_type_info 2969 // structs in the chain down to the abi::__class_type_info for the 2970 // incomplete class type must be prevented from resolving to the 2971 // corresponding type_info structs for the complete class type, possibly 2972 // by making them local static objects. Finally, a dummy class RTTI is 2973 // generated for the incomplete type that will not resolve to the final 2974 // complete class RTTI (because the latter need not exist), possibly by 2975 // making it a local static object. 2976 if (ContainsIncompleteClassType(Ty)) 2977 return llvm::GlobalValue::InternalLinkage; 2978 2979 switch (Ty->getLinkage()) { 2980 case NoLinkage: 2981 case InternalLinkage: 2982 case UniqueExternalLinkage: 2983 return llvm::GlobalValue::InternalLinkage; 2984 2985 case VisibleNoLinkage: 2986 case ModuleInternalLinkage: 2987 case ModuleLinkage: 2988 case ExternalLinkage: 2989 // RTTI is not enabled, which means that this type info struct is going 2990 // to be used for exception handling. Give it linkonce_odr linkage. 2991 if (!CGM.getLangOpts().RTTI) 2992 return llvm::GlobalValue::LinkOnceODRLinkage; 2993 2994 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) { 2995 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2996 if (RD->hasAttr<WeakAttr>()) 2997 return llvm::GlobalValue::WeakODRLinkage; 2998 if (CGM.getTriple().isWindowsItaniumEnvironment()) 2999 if (RD->hasAttr<DLLImportAttr>() && 3000 ShouldUseExternalRTTIDescriptor(CGM, Ty)) 3001 return llvm::GlobalValue::ExternalLinkage; 3002 // MinGW always uses LinkOnceODRLinkage for type info. 3003 if (RD->isDynamicClass() && 3004 !CGM.getContext() 3005 .getTargetInfo() 3006 .getTriple() 3007 .isWindowsGNUEnvironment()) 3008 return CGM.getVTableLinkage(RD); 3009 } 3010 3011 return llvm::GlobalValue::LinkOnceODRLinkage; 3012 } 3013 3014 llvm_unreachable("Invalid linkage!"); 3015 } 3016 3017 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force, 3018 bool DLLExport) { 3019 // We want to operate on the canonical type. 3020 Ty = Ty.getCanonicalType(); 3021 3022 // Check if we've already emitted an RTTI descriptor for this type. 3023 SmallString<256> Name; 3024 llvm::raw_svector_ostream Out(Name); 3025 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 3026 3027 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name); 3028 if (OldGV && !OldGV->isDeclaration()) { 3029 assert(!OldGV->hasAvailableExternallyLinkage() && 3030 "available_externally typeinfos not yet implemented"); 3031 3032 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy); 3033 } 3034 3035 // Check if there is already an external RTTI descriptor for this type. 3036 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty); 3037 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty))) 3038 return GetAddrOfExternalRTTIDescriptor(Ty); 3039 3040 // Emit the standard library with external linkage. 3041 llvm::GlobalVariable::LinkageTypes Linkage; 3042 if (IsStdLib) 3043 Linkage = llvm::GlobalValue::ExternalLinkage; 3044 else 3045 Linkage = getTypeInfoLinkage(CGM, Ty); 3046 3047 // Add the vtable pointer. 3048 BuildVTablePointer(cast<Type>(Ty)); 3049 3050 // And the name. 3051 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage); 3052 llvm::Constant *TypeNameField; 3053 3054 // If we're supposed to demote the visibility, be sure to set a flag 3055 // to use a string comparison for type_info comparisons. 3056 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness = 3057 CXXABI.classifyRTTIUniqueness(Ty, Linkage); 3058 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) { 3059 // The flag is the sign bit, which on ARM64 is defined to be clear 3060 // for global pointers. This is very ARM64-specific. 3061 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty); 3062 llvm::Constant *flag = 3063 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63); 3064 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag); 3065 TypeNameField = 3066 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy); 3067 } else { 3068 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy); 3069 } 3070 Fields.push_back(TypeNameField); 3071 3072 switch (Ty->getTypeClass()) { 3073 #define TYPE(Class, Base) 3074 #define ABSTRACT_TYPE(Class, Base) 3075 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 3076 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3077 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3078 #include "clang/AST/TypeNodes.def" 3079 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 3080 3081 // GCC treats vector types as fundamental types. 3082 case Type::Builtin: 3083 case Type::Vector: 3084 case Type::ExtVector: 3085 case Type::Complex: 3086 case Type::BlockPointer: 3087 // Itanium C++ ABI 2.9.5p4: 3088 // abi::__fundamental_type_info adds no data members to std::type_info. 3089 break; 3090 3091 case Type::LValueReference: 3092 case Type::RValueReference: 3093 llvm_unreachable("References shouldn't get here"); 3094 3095 case Type::Auto: 3096 case Type::DeducedTemplateSpecialization: 3097 llvm_unreachable("Undeduced type shouldn't get here"); 3098 3099 case Type::Pipe: 3100 llvm_unreachable("Pipe type shouldn't get here"); 3101 3102 case Type::ConstantArray: 3103 case Type::IncompleteArray: 3104 case Type::VariableArray: 3105 // Itanium C++ ABI 2.9.5p5: 3106 // abi::__array_type_info adds no data members to std::type_info. 3107 break; 3108 3109 case Type::FunctionNoProto: 3110 case Type::FunctionProto: 3111 // Itanium C++ ABI 2.9.5p5: 3112 // abi::__function_type_info adds no data members to std::type_info. 3113 break; 3114 3115 case Type::Enum: 3116 // Itanium C++ ABI 2.9.5p5: 3117 // abi::__enum_type_info adds no data members to std::type_info. 3118 break; 3119 3120 case Type::Record: { 3121 const CXXRecordDecl *RD = 3122 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 3123 if (!RD->hasDefinition() || !RD->getNumBases()) { 3124 // We don't need to emit any fields. 3125 break; 3126 } 3127 3128 if (CanUseSingleInheritance(RD)) 3129 BuildSIClassTypeInfo(RD); 3130 else 3131 BuildVMIClassTypeInfo(RD); 3132 3133 break; 3134 } 3135 3136 case Type::ObjCObject: 3137 case Type::ObjCInterface: 3138 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty)); 3139 break; 3140 3141 case Type::ObjCObjectPointer: 3142 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 3143 break; 3144 3145 case Type::Pointer: 3146 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType()); 3147 break; 3148 3149 case Type::MemberPointer: 3150 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty)); 3151 break; 3152 3153 case Type::Atomic: 3154 // No fields, at least for the moment. 3155 break; 3156 } 3157 3158 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields); 3159 3160 llvm::Module &M = CGM.getModule(); 3161 llvm::GlobalVariable *GV = 3162 new llvm::GlobalVariable(M, Init->getType(), 3163 /*Constant=*/true, Linkage, Init, Name); 3164 3165 // If there's already an old global variable, replace it with the new one. 3166 if (OldGV) { 3167 GV->takeName(OldGV); 3168 llvm::Constant *NewPtr = 3169 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3170 OldGV->replaceAllUsesWith(NewPtr); 3171 OldGV->eraseFromParent(); 3172 } 3173 3174 if (CGM.supportsCOMDAT() && GV->isWeakForLinker()) 3175 GV->setComdat(M.getOrInsertComdat(GV->getName())); 3176 3177 // The Itanium ABI specifies that type_info objects must be globally 3178 // unique, with one exception: if the type is an incomplete class 3179 // type or a (possibly indirect) pointer to one. That exception 3180 // affects the general case of comparing type_info objects produced 3181 // by the typeid operator, which is why the comparison operators on 3182 // std::type_info generally use the type_info name pointers instead 3183 // of the object addresses. However, the language's built-in uses 3184 // of RTTI generally require class types to be complete, even when 3185 // manipulating pointers to those class types. This allows the 3186 // implementation of dynamic_cast to rely on address equality tests, 3187 // which is much faster. 3188 3189 // All of this is to say that it's important that both the type_info 3190 // object and the type_info name be uniqued when weakly emitted. 3191 3192 // Give the type_info object and name the formal visibility of the 3193 // type itself. 3194 llvm::GlobalValue::VisibilityTypes llvmVisibility; 3195 if (llvm::GlobalValue::isLocalLinkage(Linkage)) 3196 // If the linkage is local, only default visibility makes sense. 3197 llvmVisibility = llvm::GlobalValue::DefaultVisibility; 3198 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden) 3199 llvmVisibility = llvm::GlobalValue::HiddenVisibility; 3200 else 3201 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility()); 3202 3203 TypeName->setVisibility(llvmVisibility); 3204 GV->setVisibility(llvmVisibility); 3205 3206 if (CGM.getTriple().isWindowsItaniumEnvironment()) { 3207 auto RD = Ty->getAsCXXRecordDecl(); 3208 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) { 3209 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3210 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3211 } else if (RD && RD->hasAttr<DLLImportAttr>() && 3212 ShouldUseExternalRTTIDescriptor(CGM, Ty)) { 3213 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3214 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3215 3216 // Because the typename and the typeinfo are DLL import, convert them to 3217 // declarations rather than definitions. The initializers still need to 3218 // be constructed to calculate the type for the declarations. 3219 TypeName->setInitializer(nullptr); 3220 GV->setInitializer(nullptr); 3221 } 3222 } 3223 3224 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 3225 } 3226 3227 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info 3228 /// for the given Objective-C object type. 3229 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) { 3230 // Drop qualifiers. 3231 const Type *T = OT->getBaseType().getTypePtr(); 3232 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T)); 3233 3234 // The builtin types are abi::__class_type_infos and don't require 3235 // extra fields. 3236 if (isa<BuiltinType>(T)) return; 3237 3238 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl(); 3239 ObjCInterfaceDecl *Super = Class->getSuperClass(); 3240 3241 // Root classes are also __class_type_info. 3242 if (!Super) return; 3243 3244 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super); 3245 3246 // Everything else is single inheritance. 3247 llvm::Constant *BaseTypeInfo = 3248 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy); 3249 Fields.push_back(BaseTypeInfo); 3250 } 3251 3252 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 3253 /// inheritance, according to the Itanium C++ ABI, 2.95p6b. 3254 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) { 3255 // Itanium C++ ABI 2.9.5p6b: 3256 // It adds to abi::__class_type_info a single member pointing to the 3257 // type_info structure for the base type, 3258 llvm::Constant *BaseTypeInfo = 3259 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType()); 3260 Fields.push_back(BaseTypeInfo); 3261 } 3262 3263 namespace { 3264 /// SeenBases - Contains virtual and non-virtual bases seen when traversing 3265 /// a class hierarchy. 3266 struct SeenBases { 3267 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases; 3268 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases; 3269 }; 3270 } 3271 3272 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in 3273 /// abi::__vmi_class_type_info. 3274 /// 3275 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 3276 SeenBases &Bases) { 3277 3278 unsigned Flags = 0; 3279 3280 const CXXRecordDecl *BaseDecl = 3281 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3282 3283 if (Base->isVirtual()) { 3284 // Mark the virtual base as seen. 3285 if (!Bases.VirtualBases.insert(BaseDecl).second) { 3286 // If this virtual base has been seen before, then the class is diamond 3287 // shaped. 3288 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped; 3289 } else { 3290 if (Bases.NonVirtualBases.count(BaseDecl)) 3291 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3292 } 3293 } else { 3294 // Mark the non-virtual base as seen. 3295 if (!Bases.NonVirtualBases.insert(BaseDecl).second) { 3296 // If this non-virtual base has been seen before, then the class has non- 3297 // diamond shaped repeated inheritance. 3298 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3299 } else { 3300 if (Bases.VirtualBases.count(BaseDecl)) 3301 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3302 } 3303 } 3304 3305 // Walk all bases. 3306 for (const auto &I : BaseDecl->bases()) 3307 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 3308 3309 return Flags; 3310 } 3311 3312 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) { 3313 unsigned Flags = 0; 3314 SeenBases Bases; 3315 3316 // Walk all bases. 3317 for (const auto &I : RD->bases()) 3318 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 3319 3320 return Flags; 3321 } 3322 3323 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 3324 /// classes with bases that do not satisfy the abi::__si_class_type_info 3325 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 3326 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) { 3327 llvm::Type *UnsignedIntLTy = 3328 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3329 3330 // Itanium C++ ABI 2.9.5p6c: 3331 // __flags is a word with flags describing details about the class 3332 // structure, which may be referenced by using the __flags_masks 3333 // enumeration. These flags refer to both direct and indirect bases. 3334 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD); 3335 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3336 3337 // Itanium C++ ABI 2.9.5p6c: 3338 // __base_count is a word with the number of direct proper base class 3339 // descriptions that follow. 3340 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases())); 3341 3342 if (!RD->getNumBases()) 3343 return; 3344 3345 // Now add the base class descriptions. 3346 3347 // Itanium C++ ABI 2.9.5p6c: 3348 // __base_info[] is an array of base class descriptions -- one for every 3349 // direct proper base. Each description is of the type: 3350 // 3351 // struct abi::__base_class_type_info { 3352 // public: 3353 // const __class_type_info *__base_type; 3354 // long __offset_flags; 3355 // 3356 // enum __offset_flags_masks { 3357 // __virtual_mask = 0x1, 3358 // __public_mask = 0x2, 3359 // __offset_shift = 8 3360 // }; 3361 // }; 3362 3363 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long 3364 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on 3365 // LLP64 platforms. 3366 // FIXME: Consider updating libc++abi to match, and extend this logic to all 3367 // LLP64 platforms. 3368 QualType OffsetFlagsTy = CGM.getContext().LongTy; 3369 const TargetInfo &TI = CGM.getContext().getTargetInfo(); 3370 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth()) 3371 OffsetFlagsTy = CGM.getContext().LongLongTy; 3372 llvm::Type *OffsetFlagsLTy = 3373 CGM.getTypes().ConvertType(OffsetFlagsTy); 3374 3375 for (const auto &Base : RD->bases()) { 3376 // The __base_type member points to the RTTI for the base type. 3377 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType())); 3378 3379 const CXXRecordDecl *BaseDecl = 3380 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 3381 3382 int64_t OffsetFlags = 0; 3383 3384 // All but the lower 8 bits of __offset_flags are a signed offset. 3385 // For a non-virtual base, this is the offset in the object of the base 3386 // subobject. For a virtual base, this is the offset in the virtual table of 3387 // the virtual base offset for the virtual base referenced (negative). 3388 CharUnits Offset; 3389 if (Base.isVirtual()) 3390 Offset = 3391 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl); 3392 else { 3393 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 3394 Offset = Layout.getBaseClassOffset(BaseDecl); 3395 }; 3396 3397 OffsetFlags = uint64_t(Offset.getQuantity()) << 8; 3398 3399 // The low-order byte of __offset_flags contains flags, as given by the 3400 // masks from the enumeration __offset_flags_masks. 3401 if (Base.isVirtual()) 3402 OffsetFlags |= BCTI_Virtual; 3403 if (Base.getAccessSpecifier() == AS_public) 3404 OffsetFlags |= BCTI_Public; 3405 3406 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags)); 3407 } 3408 } 3409 3410 /// Compute the flags for a __pbase_type_info, and remove the corresponding 3411 /// pieces from \p Type. 3412 static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) { 3413 unsigned Flags = 0; 3414 3415 if (Type.isConstQualified()) 3416 Flags |= ItaniumRTTIBuilder::PTI_Const; 3417 if (Type.isVolatileQualified()) 3418 Flags |= ItaniumRTTIBuilder::PTI_Volatile; 3419 if (Type.isRestrictQualified()) 3420 Flags |= ItaniumRTTIBuilder::PTI_Restrict; 3421 Type = Type.getUnqualifiedType(); 3422 3423 // Itanium C++ ABI 2.9.5p7: 3424 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 3425 // incomplete class type, the incomplete target type flag is set. 3426 if (ContainsIncompleteClassType(Type)) 3427 Flags |= ItaniumRTTIBuilder::PTI_Incomplete; 3428 3429 if (auto *Proto = Type->getAs<FunctionProtoType>()) { 3430 if (Proto->isNothrow(Ctx)) { 3431 Flags |= ItaniumRTTIBuilder::PTI_Noexcept; 3432 Type = Ctx.getFunctionType( 3433 Proto->getReturnType(), Proto->getParamTypes(), 3434 Proto->getExtProtoInfo().withExceptionSpec(EST_None)); 3435 } 3436 } 3437 3438 return Flags; 3439 } 3440 3441 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, 3442 /// used for pointer types. 3443 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) { 3444 // Itanium C++ ABI 2.9.5p7: 3445 // __flags is a flag word describing the cv-qualification and other 3446 // attributes of the type pointed to 3447 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); 3448 3449 llvm::Type *UnsignedIntLTy = 3450 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3451 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3452 3453 // Itanium C++ ABI 2.9.5p7: 3454 // __pointee is a pointer to the std::type_info derivation for the 3455 // unqualified type being pointed to. 3456 llvm::Constant *PointeeTypeInfo = 3457 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); 3458 Fields.push_back(PointeeTypeInfo); 3459 } 3460 3461 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 3462 /// struct, used for member pointer types. 3463 void 3464 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) { 3465 QualType PointeeTy = Ty->getPointeeType(); 3466 3467 // Itanium C++ ABI 2.9.5p7: 3468 // __flags is a flag word describing the cv-qualification and other 3469 // attributes of the type pointed to. 3470 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); 3471 3472 const RecordType *ClassType = cast<RecordType>(Ty->getClass()); 3473 if (IsIncompleteClassType(ClassType)) 3474 Flags |= PTI_ContainingClassIncomplete; 3475 3476 llvm::Type *UnsignedIntLTy = 3477 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3478 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3479 3480 // Itanium C++ ABI 2.9.5p7: 3481 // __pointee is a pointer to the std::type_info derivation for the 3482 // unqualified type being pointed to. 3483 llvm::Constant *PointeeTypeInfo = 3484 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); 3485 Fields.push_back(PointeeTypeInfo); 3486 3487 // Itanium C++ ABI 2.9.5p9: 3488 // __context is a pointer to an abi::__class_type_info corresponding to the 3489 // class type containing the member pointed to 3490 // (e.g., the "A" in "int A::*"). 3491 Fields.push_back( 3492 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0))); 3493 } 3494 3495 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) { 3496 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty); 3497 } 3498 3499 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type, 3500 bool DLLExport) { 3501 QualType PointerType = getContext().getPointerType(Type); 3502 QualType PointerTypeConst = getContext().getPointerType(Type.withConst()); 3503 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport); 3504 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true, 3505 DLLExport); 3506 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true, 3507 DLLExport); 3508 } 3509 3510 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) { 3511 // Types added here must also be added to TypeInfoIsInStandardLibrary. 3512 QualType FundamentalTypes[] = { 3513 getContext().VoidTy, getContext().NullPtrTy, 3514 getContext().BoolTy, getContext().WCharTy, 3515 getContext().CharTy, getContext().UnsignedCharTy, 3516 getContext().SignedCharTy, getContext().ShortTy, 3517 getContext().UnsignedShortTy, getContext().IntTy, 3518 getContext().UnsignedIntTy, getContext().LongTy, 3519 getContext().UnsignedLongTy, getContext().LongLongTy, 3520 getContext().UnsignedLongLongTy, getContext().Int128Ty, 3521 getContext().UnsignedInt128Ty, getContext().HalfTy, 3522 getContext().FloatTy, getContext().DoubleTy, 3523 getContext().LongDoubleTy, getContext().Float128Ty, 3524 getContext().Char16Ty, getContext().Char32Ty 3525 }; 3526 for (const QualType &FundamentalType : FundamentalTypes) 3527 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport); 3528 } 3529 3530 /// What sort of uniqueness rules should we use for the RTTI for the 3531 /// given type? 3532 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness( 3533 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const { 3534 if (shouldRTTIBeUnique()) 3535 return RUK_Unique; 3536 3537 // It's only necessary for linkonce_odr or weak_odr linkage. 3538 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage && 3539 Linkage != llvm::GlobalValue::WeakODRLinkage) 3540 return RUK_Unique; 3541 3542 // It's only necessary with default visibility. 3543 if (CanTy->getVisibility() != DefaultVisibility) 3544 return RUK_Unique; 3545 3546 // If we're not required to publish this symbol, hide it. 3547 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage) 3548 return RUK_NonUniqueHidden; 3549 3550 // If we're required to publish this symbol, as we might be under an 3551 // explicit instantiation, leave it with default visibility but 3552 // enable string-comparisons. 3553 assert(Linkage == llvm::GlobalValue::WeakODRLinkage); 3554 return RUK_NonUniqueVisible; 3555 } 3556 3557 // Find out how to codegen the complete destructor and constructor 3558 namespace { 3559 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT }; 3560 } 3561 static StructorCodegen getCodegenToUse(CodeGenModule &CGM, 3562 const CXXMethodDecl *MD) { 3563 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases) 3564 return StructorCodegen::Emit; 3565 3566 // The complete and base structors are not equivalent if there are any virtual 3567 // bases, so emit separate functions. 3568 if (MD->getParent()->getNumVBases()) 3569 return StructorCodegen::Emit; 3570 3571 GlobalDecl AliasDecl; 3572 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 3573 AliasDecl = GlobalDecl(DD, Dtor_Complete); 3574 } else { 3575 const auto *CD = cast<CXXConstructorDecl>(MD); 3576 AliasDecl = GlobalDecl(CD, Ctor_Complete); 3577 } 3578 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3579 3580 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) 3581 return StructorCodegen::RAUW; 3582 3583 // FIXME: Should we allow available_externally aliases? 3584 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 3585 return StructorCodegen::RAUW; 3586 3587 if (llvm::GlobalValue::isWeakForLinker(Linkage)) { 3588 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5). 3589 if (CGM.getTarget().getTriple().isOSBinFormatELF() || 3590 CGM.getTarget().getTriple().isOSBinFormatWasm()) 3591 return StructorCodegen::COMDAT; 3592 return StructorCodegen::Emit; 3593 } 3594 3595 return StructorCodegen::Alias; 3596 } 3597 3598 static void emitConstructorDestructorAlias(CodeGenModule &CGM, 3599 GlobalDecl AliasDecl, 3600 GlobalDecl TargetDecl) { 3601 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3602 3603 StringRef MangledName = CGM.getMangledName(AliasDecl); 3604 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName); 3605 if (Entry && !Entry->isDeclaration()) 3606 return; 3607 3608 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl)); 3609 3610 // Create the alias with no name. 3611 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee); 3612 3613 // Switch any previous uses to the alias. 3614 if (Entry) { 3615 assert(Entry->getType() == Aliasee->getType() && 3616 "declaration exists with different type"); 3617 Alias->takeName(Entry); 3618 Entry->replaceAllUsesWith(Alias); 3619 Entry->eraseFromParent(); 3620 } else { 3621 Alias->setName(MangledName); 3622 } 3623 3624 // Finally, set up the alias with its proper name and attributes. 3625 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 3626 } 3627 3628 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 3629 StructorType Type) { 3630 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 3631 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD); 3632 3633 StructorCodegen CGType = getCodegenToUse(CGM, MD); 3634 3635 if (Type == StructorType::Complete) { 3636 GlobalDecl CompleteDecl; 3637 GlobalDecl BaseDecl; 3638 if (CD) { 3639 CompleteDecl = GlobalDecl(CD, Ctor_Complete); 3640 BaseDecl = GlobalDecl(CD, Ctor_Base); 3641 } else { 3642 CompleteDecl = GlobalDecl(DD, Dtor_Complete); 3643 BaseDecl = GlobalDecl(DD, Dtor_Base); 3644 } 3645 3646 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) { 3647 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl); 3648 return; 3649 } 3650 3651 if (CGType == StructorCodegen::RAUW) { 3652 StringRef MangledName = CGM.getMangledName(CompleteDecl); 3653 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl); 3654 CGM.addReplacement(MangledName, Aliasee); 3655 return; 3656 } 3657 } 3658 3659 // The base destructor is equivalent to the base destructor of its 3660 // base class if there is exactly one non-virtual base class with a 3661 // non-trivial destructor, there are no fields with a non-trivial 3662 // destructor, and the body of the destructor is trivial. 3663 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT && 3664 !CGM.TryEmitBaseDestructorAsAlias(DD)) 3665 return; 3666 3667 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type); 3668 3669 if (CGType == StructorCodegen::COMDAT) { 3670 SmallString<256> Buffer; 3671 llvm::raw_svector_ostream Out(Buffer); 3672 if (DD) 3673 getMangleContext().mangleCXXDtorComdat(DD, Out); 3674 else 3675 getMangleContext().mangleCXXCtorComdat(CD, Out); 3676 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str()); 3677 Fn->setComdat(C); 3678 } else { 3679 CGM.maybeSetTrivialComdat(*MD, *Fn); 3680 } 3681 } 3682 3683 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) { 3684 // void *__cxa_begin_catch(void*); 3685 llvm::FunctionType *FTy = llvm::FunctionType::get( 3686 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3687 3688 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); 3689 } 3690 3691 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) { 3692 // void __cxa_end_catch(); 3693 llvm::FunctionType *FTy = 3694 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 3695 3696 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); 3697 } 3698 3699 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) { 3700 // void *__cxa_get_exception_ptr(void*); 3701 llvm::FunctionType *FTy = llvm::FunctionType::get( 3702 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3703 3704 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr"); 3705 } 3706 3707 namespace { 3708 /// A cleanup to call __cxa_end_catch. In many cases, the caught 3709 /// exception type lets us state definitively that the thrown exception 3710 /// type does not have a destructor. In particular: 3711 /// - Catch-alls tell us nothing, so we have to conservatively 3712 /// assume that the thrown exception might have a destructor. 3713 /// - Catches by reference behave according to their base types. 3714 /// - Catches of non-record types will only trigger for exceptions 3715 /// of non-record types, which never have destructors. 3716 /// - Catches of record types can trigger for arbitrary subclasses 3717 /// of the caught type, so we have to assume the actual thrown 3718 /// exception type might have a throwing destructor, even if the 3719 /// caught type's destructor is trivial or nothrow. 3720 struct CallEndCatch final : EHScopeStack::Cleanup { 3721 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {} 3722 bool MightThrow; 3723 3724 void Emit(CodeGenFunction &CGF, Flags flags) override { 3725 if (!MightThrow) { 3726 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM)); 3727 return; 3728 } 3729 3730 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM)); 3731 } 3732 }; 3733 } 3734 3735 /// Emits a call to __cxa_begin_catch and enters a cleanup to call 3736 /// __cxa_end_catch. 3737 /// 3738 /// \param EndMightThrow - true if __cxa_end_catch might throw 3739 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF, 3740 llvm::Value *Exn, 3741 bool EndMightThrow) { 3742 llvm::CallInst *call = 3743 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn); 3744 3745 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow); 3746 3747 return call; 3748 } 3749 3750 /// A "special initializer" callback for initializing a catch 3751 /// parameter during catch initialization. 3752 static void InitCatchParam(CodeGenFunction &CGF, 3753 const VarDecl &CatchParam, 3754 Address ParamAddr, 3755 SourceLocation Loc) { 3756 // Load the exception from where the landing pad saved it. 3757 llvm::Value *Exn = CGF.getExceptionFromSlot(); 3758 3759 CanQualType CatchType = 3760 CGF.CGM.getContext().getCanonicalType(CatchParam.getType()); 3761 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType); 3762 3763 // If we're catching by reference, we can just cast the object 3764 // pointer to the appropriate pointer. 3765 if (isa<ReferenceType>(CatchType)) { 3766 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType(); 3767 bool EndCatchMightThrow = CaughtType->isRecordType(); 3768 3769 // __cxa_begin_catch returns the adjusted object pointer. 3770 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow); 3771 3772 // We have no way to tell the personality function that we're 3773 // catching by reference, so if we're catching a pointer, 3774 // __cxa_begin_catch will actually return that pointer by value. 3775 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) { 3776 QualType PointeeType = PT->getPointeeType(); 3777 3778 // When catching by reference, generally we should just ignore 3779 // this by-value pointer and use the exception object instead. 3780 if (!PointeeType->isRecordType()) { 3781 3782 // Exn points to the struct _Unwind_Exception header, which 3783 // we have to skip past in order to reach the exception data. 3784 unsigned HeaderSize = 3785 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException(); 3786 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize); 3787 3788 // However, if we're catching a pointer-to-record type that won't 3789 // work, because the personality function might have adjusted 3790 // the pointer. There's actually no way for us to fully satisfy 3791 // the language/ABI contract here: we can't use Exn because it 3792 // might have the wrong adjustment, but we can't use the by-value 3793 // pointer because it's off by a level of abstraction. 3794 // 3795 // The current solution is to dump the adjusted pointer into an 3796 // alloca, which breaks language semantics (because changing the 3797 // pointer doesn't change the exception) but at least works. 3798 // The better solution would be to filter out non-exact matches 3799 // and rethrow them, but this is tricky because the rethrow 3800 // really needs to be catchable by other sites at this landing 3801 // pad. The best solution is to fix the personality function. 3802 } else { 3803 // Pull the pointer for the reference type off. 3804 llvm::Type *PtrTy = 3805 cast<llvm::PointerType>(LLVMCatchTy)->getElementType(); 3806 3807 // Create the temporary and write the adjusted pointer into it. 3808 Address ExnPtrTmp = 3809 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp"); 3810 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 3811 CGF.Builder.CreateStore(Casted, ExnPtrTmp); 3812 3813 // Bind the reference to the temporary. 3814 AdjustedExn = ExnPtrTmp.getPointer(); 3815 } 3816 } 3817 3818 llvm::Value *ExnCast = 3819 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref"); 3820 CGF.Builder.CreateStore(ExnCast, ParamAddr); 3821 return; 3822 } 3823 3824 // Scalars and complexes. 3825 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType); 3826 if (TEK != TEK_Aggregate) { 3827 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false); 3828 3829 // If the catch type is a pointer type, __cxa_begin_catch returns 3830 // the pointer by value. 3831 if (CatchType->hasPointerRepresentation()) { 3832 llvm::Value *CastExn = 3833 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted"); 3834 3835 switch (CatchType.getQualifiers().getObjCLifetime()) { 3836 case Qualifiers::OCL_Strong: 3837 CastExn = CGF.EmitARCRetainNonBlock(CastExn); 3838 // fallthrough 3839 3840 case Qualifiers::OCL_None: 3841 case Qualifiers::OCL_ExplicitNone: 3842 case Qualifiers::OCL_Autoreleasing: 3843 CGF.Builder.CreateStore(CastExn, ParamAddr); 3844 return; 3845 3846 case Qualifiers::OCL_Weak: 3847 CGF.EmitARCInitWeak(ParamAddr, CastExn); 3848 return; 3849 } 3850 llvm_unreachable("bad ownership qualifier!"); 3851 } 3852 3853 // Otherwise, it returns a pointer into the exception object. 3854 3855 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 3856 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 3857 3858 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType); 3859 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType); 3860 switch (TEK) { 3861 case TEK_Complex: 3862 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV, 3863 /*init*/ true); 3864 return; 3865 case TEK_Scalar: { 3866 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc); 3867 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true); 3868 return; 3869 } 3870 case TEK_Aggregate: 3871 llvm_unreachable("evaluation kind filtered out!"); 3872 } 3873 llvm_unreachable("bad evaluation kind"); 3874 } 3875 3876 assert(isa<RecordType>(CatchType) && "unexpected catch type!"); 3877 auto catchRD = CatchType->getAsCXXRecordDecl(); 3878 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD); 3879 3880 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 3881 3882 // Check for a copy expression. If we don't have a copy expression, 3883 // that means a trivial copy is okay. 3884 const Expr *copyExpr = CatchParam.getInit(); 3885 if (!copyExpr) { 3886 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true); 3887 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), 3888 caughtExnAlignment); 3889 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType); 3890 return; 3891 } 3892 3893 // We have to call __cxa_get_exception_ptr to get the adjusted 3894 // pointer before copying. 3895 llvm::CallInst *rawAdjustedExn = 3896 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn); 3897 3898 // Cast that to the appropriate type. 3899 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), 3900 caughtExnAlignment); 3901 3902 // The copy expression is defined in terms of an OpaqueValueExpr. 3903 // Find it and map it to the adjusted expression. 3904 CodeGenFunction::OpaqueValueMapping 3905 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr), 3906 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType())); 3907 3908 // Call the copy ctor in a terminate scope. 3909 CGF.EHStack.pushTerminate(); 3910 3911 // Perform the copy construction. 3912 CGF.EmitAggExpr(copyExpr, 3913 AggValueSlot::forAddr(ParamAddr, Qualifiers(), 3914 AggValueSlot::IsNotDestructed, 3915 AggValueSlot::DoesNotNeedGCBarriers, 3916 AggValueSlot::IsNotAliased)); 3917 3918 // Leave the terminate scope. 3919 CGF.EHStack.popTerminate(); 3920 3921 // Undo the opaque value mapping. 3922 opaque.pop(); 3923 3924 // Finally we can call __cxa_begin_catch. 3925 CallBeginCatch(CGF, Exn, true); 3926 } 3927 3928 /// Begins a catch statement by initializing the catch variable and 3929 /// calling __cxa_begin_catch. 3930 void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF, 3931 const CXXCatchStmt *S) { 3932 // We have to be very careful with the ordering of cleanups here: 3933 // C++ [except.throw]p4: 3934 // The destruction [of the exception temporary] occurs 3935 // immediately after the destruction of the object declared in 3936 // the exception-declaration in the handler. 3937 // 3938 // So the precise ordering is: 3939 // 1. Construct catch variable. 3940 // 2. __cxa_begin_catch 3941 // 3. Enter __cxa_end_catch cleanup 3942 // 4. Enter dtor cleanup 3943 // 3944 // We do this by using a slightly abnormal initialization process. 3945 // Delegation sequence: 3946 // - ExitCXXTryStmt opens a RunCleanupsScope 3947 // - EmitAutoVarAlloca creates the variable and debug info 3948 // - InitCatchParam initializes the variable from the exception 3949 // - CallBeginCatch calls __cxa_begin_catch 3950 // - CallBeginCatch enters the __cxa_end_catch cleanup 3951 // - EmitAutoVarCleanups enters the variable destructor cleanup 3952 // - EmitCXXTryStmt emits the code for the catch body 3953 // - EmitCXXTryStmt close the RunCleanupsScope 3954 3955 VarDecl *CatchParam = S->getExceptionDecl(); 3956 if (!CatchParam) { 3957 llvm::Value *Exn = CGF.getExceptionFromSlot(); 3958 CallBeginCatch(CGF, Exn, true); 3959 return; 3960 } 3961 3962 // Emit the local. 3963 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); 3964 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart()); 3965 CGF.EmitAutoVarCleanups(var); 3966 } 3967 3968 /// Get or define the following function: 3969 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn 3970 /// This code is used only in C++. 3971 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) { 3972 llvm::FunctionType *fnTy = 3973 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3974 llvm::Constant *fnRef = CGM.CreateRuntimeFunction( 3975 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true); 3976 3977 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef); 3978 if (fn && fn->empty()) { 3979 fn->setDoesNotThrow(); 3980 fn->setDoesNotReturn(); 3981 3982 // What we really want is to massively penalize inlining without 3983 // forbidding it completely. The difference between that and 3984 // 'noinline' is negligible. 3985 fn->addFnAttr(llvm::Attribute::NoInline); 3986 3987 // Allow this function to be shared across translation units, but 3988 // we don't want it to turn into an exported symbol. 3989 fn->setLinkage(llvm::Function::LinkOnceODRLinkage); 3990 fn->setVisibility(llvm::Function::HiddenVisibility); 3991 if (CGM.supportsCOMDAT()) 3992 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName())); 3993 3994 // Set up the function. 3995 llvm::BasicBlock *entry = 3996 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn); 3997 CGBuilderTy builder(CGM, entry); 3998 3999 // Pull the exception pointer out of the parameter list. 4000 llvm::Value *exn = &*fn->arg_begin(); 4001 4002 // Call __cxa_begin_catch(exn). 4003 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn); 4004 catchCall->setDoesNotThrow(); 4005 catchCall->setCallingConv(CGM.getRuntimeCC()); 4006 4007 // Call std::terminate(). 4008 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn()); 4009 termCall->setDoesNotThrow(); 4010 termCall->setDoesNotReturn(); 4011 termCall->setCallingConv(CGM.getRuntimeCC()); 4012 4013 // std::terminate cannot return. 4014 builder.CreateUnreachable(); 4015 } 4016 4017 return fnRef; 4018 } 4019 4020 llvm::CallInst * 4021 ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF, 4022 llvm::Value *Exn) { 4023 // In C++, we want to call __cxa_begin_catch() before terminating. 4024 if (Exn) { 4025 assert(CGF.CGM.getLangOpts().CPlusPlus); 4026 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn); 4027 } 4028 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn()); 4029 } 4030