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