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 2405 llvm::LLVMContext &Context = CGM.getModule().getContext(); 2406 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 2407 CGBuilderTy Builder(CGM, Entry); 2408 if (InitIsInitFunc) { 2409 if (Init) { 2410 llvm::CallInst *CallVal = Builder.CreateCall(Init); 2411 if (isThreadWrapperReplaceable(VD, CGM)) 2412 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2413 } 2414 } else { 2415 // Don't know whether we have an init function. Call it if it exists. 2416 llvm::Value *Have = Builder.CreateIsNotNull(Init); 2417 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 2418 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 2419 Builder.CreateCondBr(Have, InitBB, ExitBB); 2420 2421 Builder.SetInsertPoint(InitBB); 2422 Builder.CreateCall(Init); 2423 Builder.CreateBr(ExitBB); 2424 2425 Builder.SetInsertPoint(ExitBB); 2426 } 2427 2428 // For a reference, the result of the wrapper function is a pointer to 2429 // the referenced object. 2430 llvm::Value *Val = Var; 2431 if (VD->getType()->isReferenceType()) { 2432 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2433 Val = Builder.CreateAlignedLoad(Val, Align); 2434 } 2435 if (Val->getType() != Wrapper->getReturnType()) 2436 Val = Builder.CreatePointerBitCastOrAddrSpaceCast( 2437 Val, Wrapper->getReturnType(), ""); 2438 Builder.CreateRet(Val); 2439 } 2440 } 2441 2442 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2443 const VarDecl *VD, 2444 QualType LValType) { 2445 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD); 2446 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val); 2447 2448 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper); 2449 CallVal->setCallingConv(Wrapper->getCallingConv()); 2450 2451 LValue LV; 2452 if (VD->getType()->isReferenceType()) 2453 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType); 2454 else 2455 LV = CGF.MakeAddrLValue(CallVal, LValType, 2456 CGF.getContext().getDeclAlign(VD)); 2457 // FIXME: need setObjCGCLValueClass? 2458 return LV; 2459 } 2460 2461 /// Return whether the given global decl needs a VTT parameter, which it does 2462 /// if it's a base constructor or destructor with virtual bases. 2463 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 2464 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2465 2466 // We don't have any virtual bases, just return early. 2467 if (!MD->getParent()->getNumVBases()) 2468 return false; 2469 2470 // Check if we have a base constructor. 2471 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 2472 return true; 2473 2474 // Check if we have a base destructor. 2475 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 2476 return true; 2477 2478 return false; 2479 } 2480 2481 namespace { 2482 class ItaniumRTTIBuilder { 2483 CodeGenModule &CGM; // Per-module state. 2484 llvm::LLVMContext &VMContext; 2485 const ItaniumCXXABI &CXXABI; // Per-module state. 2486 2487 /// Fields - The fields of the RTTI descriptor currently being built. 2488 SmallVector<llvm::Constant *, 16> Fields; 2489 2490 /// GetAddrOfTypeName - Returns the mangled type name of the given type. 2491 llvm::GlobalVariable * 2492 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage); 2493 2494 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 2495 /// descriptor of the given type. 2496 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty); 2497 2498 /// BuildVTablePointer - Build the vtable pointer for the given type. 2499 void BuildVTablePointer(const Type *Ty); 2500 2501 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2502 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b. 2503 void BuildSIClassTypeInfo(const CXXRecordDecl *RD); 2504 2505 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2506 /// classes with bases that do not satisfy the abi::__si_class_type_info 2507 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2508 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD); 2509 2510 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used 2511 /// for pointer types. 2512 void BuildPointerTypeInfo(QualType PointeeTy); 2513 2514 /// BuildObjCObjectTypeInfo - Build the appropriate kind of 2515 /// type_info for an object type. 2516 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty); 2517 2518 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2519 /// struct, used for member pointer types. 2520 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty); 2521 2522 public: 2523 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI) 2524 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {} 2525 2526 // Pointer type info flags. 2527 enum { 2528 /// PTI_Const - Type has const qualifier. 2529 PTI_Const = 0x1, 2530 2531 /// PTI_Volatile - Type has volatile qualifier. 2532 PTI_Volatile = 0x2, 2533 2534 /// PTI_Restrict - Type has restrict qualifier. 2535 PTI_Restrict = 0x4, 2536 2537 /// PTI_Incomplete - Type is incomplete. 2538 PTI_Incomplete = 0x8, 2539 2540 /// PTI_ContainingClassIncomplete - Containing class is incomplete. 2541 /// (in pointer to member). 2542 PTI_ContainingClassIncomplete = 0x10, 2543 2544 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS). 2545 //PTI_TransactionSafe = 0x20, 2546 2547 /// PTI_Noexcept - Pointee is noexcept function (C++1z). 2548 PTI_Noexcept = 0x40, 2549 }; 2550 2551 // VMI type info flags. 2552 enum { 2553 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance. 2554 VMI_NonDiamondRepeat = 0x1, 2555 2556 /// VMI_DiamondShaped - Class is diamond shaped. 2557 VMI_DiamondShaped = 0x2 2558 }; 2559 2560 // Base class type info flags. 2561 enum { 2562 /// BCTI_Virtual - Base class is virtual. 2563 BCTI_Virtual = 0x1, 2564 2565 /// BCTI_Public - Base class is public. 2566 BCTI_Public = 0x2 2567 }; 2568 2569 /// BuildTypeInfo - Build the RTTI type info struct for the given type. 2570 /// 2571 /// \param Force - true to force the creation of this RTTI value 2572 /// \param DLLExport - true to mark the RTTI value as DLLExport 2573 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false, 2574 bool DLLExport = false); 2575 }; 2576 } 2577 2578 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName( 2579 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) { 2580 SmallString<256> Name; 2581 llvm::raw_svector_ostream Out(Name); 2582 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out); 2583 2584 // We know that the mangled name of the type starts at index 4 of the 2585 // mangled name of the typename, so we can just index into it in order to 2586 // get the mangled name of the type. 2587 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 2588 Name.substr(4)); 2589 2590 llvm::GlobalVariable *GV = 2591 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage); 2592 2593 GV->setInitializer(Init); 2594 2595 return GV; 2596 } 2597 2598 llvm::Constant * 2599 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) { 2600 // Mangle the RTTI name. 2601 SmallString<256> Name; 2602 llvm::raw_svector_ostream Out(Name); 2603 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2604 2605 // Look for an existing global. 2606 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name); 2607 2608 if (!GV) { 2609 // Create a new global variable. 2610 // Note for the future: If we would ever like to do deferred emission of 2611 // RTTI, check if emitting vtables opportunistically need any adjustment. 2612 2613 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 2614 /*Constant=*/true, 2615 llvm::GlobalValue::ExternalLinkage, nullptr, 2616 Name); 2617 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2618 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2619 CGM.setGVProperties(GV, RD); 2620 } 2621 } 2622 2623 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2624 } 2625 2626 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type 2627 /// info for that type is defined in the standard library. 2628 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) { 2629 // Itanium C++ ABI 2.9.2: 2630 // Basic type information (e.g. for "int", "bool", etc.) will be kept in 2631 // the run-time support library. Specifically, the run-time support 2632 // library should contain type_info objects for the types X, X* and 2633 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char, 2634 // unsigned char, signed char, short, unsigned short, int, unsigned int, 2635 // long, unsigned long, long long, unsigned long long, float, double, 2636 // long double, char16_t, char32_t, and the IEEE 754r decimal and 2637 // half-precision floating point types. 2638 // 2639 // GCC also emits RTTI for __int128. 2640 // FIXME: We do not emit RTTI information for decimal types here. 2641 2642 // Types added here must also be added to EmitFundamentalRTTIDescriptors. 2643 switch (Ty->getKind()) { 2644 case BuiltinType::Void: 2645 case BuiltinType::NullPtr: 2646 case BuiltinType::Bool: 2647 case BuiltinType::WChar_S: 2648 case BuiltinType::WChar_U: 2649 case BuiltinType::Char_U: 2650 case BuiltinType::Char_S: 2651 case BuiltinType::UChar: 2652 case BuiltinType::SChar: 2653 case BuiltinType::Short: 2654 case BuiltinType::UShort: 2655 case BuiltinType::Int: 2656 case BuiltinType::UInt: 2657 case BuiltinType::Long: 2658 case BuiltinType::ULong: 2659 case BuiltinType::LongLong: 2660 case BuiltinType::ULongLong: 2661 case BuiltinType::Half: 2662 case BuiltinType::Float: 2663 case BuiltinType::Double: 2664 case BuiltinType::LongDouble: 2665 case BuiltinType::Float16: 2666 case BuiltinType::Float128: 2667 case BuiltinType::Char16: 2668 case BuiltinType::Char32: 2669 case BuiltinType::Int128: 2670 case BuiltinType::UInt128: 2671 return true; 2672 2673 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2674 case BuiltinType::Id: 2675 #include "clang/Basic/OpenCLImageTypes.def" 2676 case BuiltinType::OCLSampler: 2677 case BuiltinType::OCLEvent: 2678 case BuiltinType::OCLClkEvent: 2679 case BuiltinType::OCLQueue: 2680 case BuiltinType::OCLReserveID: 2681 return false; 2682 2683 case BuiltinType::Dependent: 2684 #define BUILTIN_TYPE(Id, SingletonId) 2685 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2686 case BuiltinType::Id: 2687 #include "clang/AST/BuiltinTypes.def" 2688 llvm_unreachable("asking for RRTI for a placeholder type!"); 2689 2690 case BuiltinType::ObjCId: 2691 case BuiltinType::ObjCClass: 2692 case BuiltinType::ObjCSel: 2693 llvm_unreachable("FIXME: Objective-C types are unsupported!"); 2694 } 2695 2696 llvm_unreachable("Invalid BuiltinType Kind!"); 2697 } 2698 2699 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) { 2700 QualType PointeeTy = PointerTy->getPointeeType(); 2701 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy); 2702 if (!BuiltinTy) 2703 return false; 2704 2705 // Check the qualifiers. 2706 Qualifiers Quals = PointeeTy.getQualifiers(); 2707 Quals.removeConst(); 2708 2709 if (!Quals.empty()) 2710 return false; 2711 2712 return TypeInfoIsInStandardLibrary(BuiltinTy); 2713 } 2714 2715 /// IsStandardLibraryRTTIDescriptor - Returns whether the type 2716 /// information for the given type exists in the standard library. 2717 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) { 2718 // Type info for builtin types is defined in the standard library. 2719 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty)) 2720 return TypeInfoIsInStandardLibrary(BuiltinTy); 2721 2722 // Type info for some pointer types to builtin types is defined in the 2723 // standard library. 2724 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2725 return TypeInfoIsInStandardLibrary(PointerTy); 2726 2727 return false; 2728 } 2729 2730 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for 2731 /// the given type exists somewhere else, and that we should not emit the type 2732 /// information in this translation unit. Assumes that it is not a 2733 /// standard-library type. 2734 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, 2735 QualType Ty) { 2736 ASTContext &Context = CGM.getContext(); 2737 2738 // If RTTI is disabled, assume it might be disabled in the 2739 // translation unit that defines any potential key function, too. 2740 if (!Context.getLangOpts().RTTI) return false; 2741 2742 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2743 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2744 if (!RD->hasDefinition()) 2745 return false; 2746 2747 if (!RD->isDynamicClass()) 2748 return false; 2749 2750 // FIXME: this may need to be reconsidered if the key function 2751 // changes. 2752 // N.B. We must always emit the RTTI data ourselves if there exists a key 2753 // function. 2754 bool IsDLLImport = RD->hasAttr<DLLImportAttr>(); 2755 2756 // Don't import the RTTI but emit it locally. 2757 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport) 2758 return false; 2759 2760 if (CGM.getVTables().isVTableExternal(RD)) 2761 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment() 2762 ? false 2763 : true; 2764 2765 if (IsDLLImport) 2766 return true; 2767 } 2768 2769 return false; 2770 } 2771 2772 /// IsIncompleteClassType - Returns whether the given record type is incomplete. 2773 static bool IsIncompleteClassType(const RecordType *RecordTy) { 2774 return !RecordTy->getDecl()->isCompleteDefinition(); 2775 } 2776 2777 /// ContainsIncompleteClassType - Returns whether the given type contains an 2778 /// incomplete class type. This is true if 2779 /// 2780 /// * The given type is an incomplete class type. 2781 /// * The given type is a pointer type whose pointee type contains an 2782 /// incomplete class type. 2783 /// * The given type is a member pointer type whose class is an incomplete 2784 /// class type. 2785 /// * The given type is a member pointer type whoise pointee type contains an 2786 /// incomplete class type. 2787 /// is an indirect or direct pointer to an incomplete class type. 2788 static bool ContainsIncompleteClassType(QualType Ty) { 2789 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2790 if (IsIncompleteClassType(RecordTy)) 2791 return true; 2792 } 2793 2794 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2795 return ContainsIncompleteClassType(PointerTy->getPointeeType()); 2796 2797 if (const MemberPointerType *MemberPointerTy = 2798 dyn_cast<MemberPointerType>(Ty)) { 2799 // Check if the class type is incomplete. 2800 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass()); 2801 if (IsIncompleteClassType(ClassType)) 2802 return true; 2803 2804 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType()); 2805 } 2806 2807 return false; 2808 } 2809 2810 // CanUseSingleInheritance - Return whether the given record decl has a "single, 2811 // public, non-virtual base at offset zero (i.e. the derived class is dynamic 2812 // iff the base is)", according to Itanium C++ ABI, 2.95p6b. 2813 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) { 2814 // Check the number of bases. 2815 if (RD->getNumBases() != 1) 2816 return false; 2817 2818 // Get the base. 2819 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(); 2820 2821 // Check that the base is not virtual. 2822 if (Base->isVirtual()) 2823 return false; 2824 2825 // Check that the base is public. 2826 if (Base->getAccessSpecifier() != AS_public) 2827 return false; 2828 2829 // Check that the class is dynamic iff the base is. 2830 const CXXRecordDecl *BaseDecl = 2831 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2832 if (!BaseDecl->isEmpty() && 2833 BaseDecl->isDynamicClass() != RD->isDynamicClass()) 2834 return false; 2835 2836 return true; 2837 } 2838 2839 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) { 2840 // abi::__class_type_info. 2841 static const char * const ClassTypeInfo = 2842 "_ZTVN10__cxxabiv117__class_type_infoE"; 2843 // abi::__si_class_type_info. 2844 static const char * const SIClassTypeInfo = 2845 "_ZTVN10__cxxabiv120__si_class_type_infoE"; 2846 // abi::__vmi_class_type_info. 2847 static const char * const VMIClassTypeInfo = 2848 "_ZTVN10__cxxabiv121__vmi_class_type_infoE"; 2849 2850 const char *VTableName = nullptr; 2851 2852 switch (Ty->getTypeClass()) { 2853 #define TYPE(Class, Base) 2854 #define ABSTRACT_TYPE(Class, Base) 2855 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2856 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2857 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2858 #include "clang/AST/TypeNodes.def" 2859 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2860 2861 case Type::LValueReference: 2862 case Type::RValueReference: 2863 llvm_unreachable("References shouldn't get here"); 2864 2865 case Type::Auto: 2866 case Type::DeducedTemplateSpecialization: 2867 llvm_unreachable("Undeduced type shouldn't get here"); 2868 2869 case Type::Pipe: 2870 llvm_unreachable("Pipe types shouldn't get here"); 2871 2872 case Type::Builtin: 2873 // GCC treats vector and complex types as fundamental types. 2874 case Type::Vector: 2875 case Type::ExtVector: 2876 case Type::Complex: 2877 case Type::Atomic: 2878 // FIXME: GCC treats block pointers as fundamental types?! 2879 case Type::BlockPointer: 2880 // abi::__fundamental_type_info. 2881 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE"; 2882 break; 2883 2884 case Type::ConstantArray: 2885 case Type::IncompleteArray: 2886 case Type::VariableArray: 2887 // abi::__array_type_info. 2888 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE"; 2889 break; 2890 2891 case Type::FunctionNoProto: 2892 case Type::FunctionProto: 2893 // abi::__function_type_info. 2894 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE"; 2895 break; 2896 2897 case Type::Enum: 2898 // abi::__enum_type_info. 2899 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE"; 2900 break; 2901 2902 case Type::Record: { 2903 const CXXRecordDecl *RD = 2904 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2905 2906 if (!RD->hasDefinition() || !RD->getNumBases()) { 2907 VTableName = ClassTypeInfo; 2908 } else if (CanUseSingleInheritance(RD)) { 2909 VTableName = SIClassTypeInfo; 2910 } else { 2911 VTableName = VMIClassTypeInfo; 2912 } 2913 2914 break; 2915 } 2916 2917 case Type::ObjCObject: 2918 // Ignore protocol qualifiers. 2919 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr(); 2920 2921 // Handle id and Class. 2922 if (isa<BuiltinType>(Ty)) { 2923 VTableName = ClassTypeInfo; 2924 break; 2925 } 2926 2927 assert(isa<ObjCInterfaceType>(Ty)); 2928 // Fall through. 2929 2930 case Type::ObjCInterface: 2931 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) { 2932 VTableName = SIClassTypeInfo; 2933 } else { 2934 VTableName = ClassTypeInfo; 2935 } 2936 break; 2937 2938 case Type::ObjCObjectPointer: 2939 case Type::Pointer: 2940 // abi::__pointer_type_info. 2941 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE"; 2942 break; 2943 2944 case Type::MemberPointer: 2945 // abi::__pointer_to_member_type_info. 2946 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE"; 2947 break; 2948 } 2949 2950 llvm::Constant *VTable = 2951 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); 2952 2953 llvm::Type *PtrDiffTy = 2954 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 2955 2956 // The vtable address point is 2. 2957 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2); 2958 VTable = 2959 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two); 2960 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy); 2961 2962 Fields.push_back(VTable); 2963 } 2964 2965 /// \brief Return the linkage that the type info and type info name constants 2966 /// should have for the given type. 2967 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM, 2968 QualType Ty) { 2969 // Itanium C++ ABI 2.9.5p7: 2970 // In addition, it and all of the intermediate abi::__pointer_type_info 2971 // structs in the chain down to the abi::__class_type_info for the 2972 // incomplete class type must be prevented from resolving to the 2973 // corresponding type_info structs for the complete class type, possibly 2974 // by making them local static objects. Finally, a dummy class RTTI is 2975 // generated for the incomplete type that will not resolve to the final 2976 // complete class RTTI (because the latter need not exist), possibly by 2977 // making it a local static object. 2978 if (ContainsIncompleteClassType(Ty)) 2979 return llvm::GlobalValue::InternalLinkage; 2980 2981 switch (Ty->getLinkage()) { 2982 case NoLinkage: 2983 case InternalLinkage: 2984 case UniqueExternalLinkage: 2985 return llvm::GlobalValue::InternalLinkage; 2986 2987 case VisibleNoLinkage: 2988 case ModuleInternalLinkage: 2989 case ModuleLinkage: 2990 case ExternalLinkage: 2991 // RTTI is not enabled, which means that this type info struct is going 2992 // to be used for exception handling. Give it linkonce_odr linkage. 2993 if (!CGM.getLangOpts().RTTI) 2994 return llvm::GlobalValue::LinkOnceODRLinkage; 2995 2996 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) { 2997 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2998 if (RD->hasAttr<WeakAttr>()) 2999 return llvm::GlobalValue::WeakODRLinkage; 3000 if (CGM.getTriple().isWindowsItaniumEnvironment()) 3001 if (RD->hasAttr<DLLImportAttr>() && 3002 ShouldUseExternalRTTIDescriptor(CGM, Ty)) 3003 return llvm::GlobalValue::ExternalLinkage; 3004 // MinGW always uses LinkOnceODRLinkage for type info. 3005 if (RD->isDynamicClass() && 3006 !CGM.getContext() 3007 .getTargetInfo() 3008 .getTriple() 3009 .isWindowsGNUEnvironment()) 3010 return CGM.getVTableLinkage(RD); 3011 } 3012 3013 return llvm::GlobalValue::LinkOnceODRLinkage; 3014 } 3015 3016 llvm_unreachable("Invalid linkage!"); 3017 } 3018 3019 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force, 3020 bool DLLExport) { 3021 // We want to operate on the canonical type. 3022 Ty = Ty.getCanonicalType(); 3023 3024 // Check if we've already emitted an RTTI descriptor for this type. 3025 SmallString<256> Name; 3026 llvm::raw_svector_ostream Out(Name); 3027 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 3028 3029 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name); 3030 if (OldGV && !OldGV->isDeclaration()) { 3031 assert(!OldGV->hasAvailableExternallyLinkage() && 3032 "available_externally typeinfos not yet implemented"); 3033 3034 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy); 3035 } 3036 3037 // Check if there is already an external RTTI descriptor for this type. 3038 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty); 3039 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty))) 3040 return GetAddrOfExternalRTTIDescriptor(Ty); 3041 3042 // Emit the standard library with external linkage. 3043 llvm::GlobalVariable::LinkageTypes Linkage; 3044 if (IsStdLib) 3045 Linkage = llvm::GlobalValue::ExternalLinkage; 3046 else 3047 Linkage = getTypeInfoLinkage(CGM, Ty); 3048 3049 // Add the vtable pointer. 3050 BuildVTablePointer(cast<Type>(Ty)); 3051 3052 // And the name. 3053 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage); 3054 llvm::Constant *TypeNameField; 3055 3056 // If we're supposed to demote the visibility, be sure to set a flag 3057 // to use a string comparison for type_info comparisons. 3058 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness = 3059 CXXABI.classifyRTTIUniqueness(Ty, Linkage); 3060 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) { 3061 // The flag is the sign bit, which on ARM64 is defined to be clear 3062 // for global pointers. This is very ARM64-specific. 3063 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty); 3064 llvm::Constant *flag = 3065 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63); 3066 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag); 3067 TypeNameField = 3068 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy); 3069 } else { 3070 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy); 3071 } 3072 Fields.push_back(TypeNameField); 3073 3074 switch (Ty->getTypeClass()) { 3075 #define TYPE(Class, Base) 3076 #define ABSTRACT_TYPE(Class, Base) 3077 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 3078 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3079 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3080 #include "clang/AST/TypeNodes.def" 3081 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 3082 3083 // GCC treats vector types as fundamental types. 3084 case Type::Builtin: 3085 case Type::Vector: 3086 case Type::ExtVector: 3087 case Type::Complex: 3088 case Type::BlockPointer: 3089 // Itanium C++ ABI 2.9.5p4: 3090 // abi::__fundamental_type_info adds no data members to std::type_info. 3091 break; 3092 3093 case Type::LValueReference: 3094 case Type::RValueReference: 3095 llvm_unreachable("References shouldn't get here"); 3096 3097 case Type::Auto: 3098 case Type::DeducedTemplateSpecialization: 3099 llvm_unreachable("Undeduced type shouldn't get here"); 3100 3101 case Type::Pipe: 3102 llvm_unreachable("Pipe type shouldn't get here"); 3103 3104 case Type::ConstantArray: 3105 case Type::IncompleteArray: 3106 case Type::VariableArray: 3107 // Itanium C++ ABI 2.9.5p5: 3108 // abi::__array_type_info adds no data members to std::type_info. 3109 break; 3110 3111 case Type::FunctionNoProto: 3112 case Type::FunctionProto: 3113 // Itanium C++ ABI 2.9.5p5: 3114 // abi::__function_type_info adds no data members to std::type_info. 3115 break; 3116 3117 case Type::Enum: 3118 // Itanium C++ ABI 2.9.5p5: 3119 // abi::__enum_type_info adds no data members to std::type_info. 3120 break; 3121 3122 case Type::Record: { 3123 const CXXRecordDecl *RD = 3124 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 3125 if (!RD->hasDefinition() || !RD->getNumBases()) { 3126 // We don't need to emit any fields. 3127 break; 3128 } 3129 3130 if (CanUseSingleInheritance(RD)) 3131 BuildSIClassTypeInfo(RD); 3132 else 3133 BuildVMIClassTypeInfo(RD); 3134 3135 break; 3136 } 3137 3138 case Type::ObjCObject: 3139 case Type::ObjCInterface: 3140 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty)); 3141 break; 3142 3143 case Type::ObjCObjectPointer: 3144 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 3145 break; 3146 3147 case Type::Pointer: 3148 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType()); 3149 break; 3150 3151 case Type::MemberPointer: 3152 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty)); 3153 break; 3154 3155 case Type::Atomic: 3156 // No fields, at least for the moment. 3157 break; 3158 } 3159 3160 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields); 3161 3162 llvm::Module &M = CGM.getModule(); 3163 llvm::GlobalVariable *GV = 3164 new llvm::GlobalVariable(M, Init->getType(), 3165 /*Constant=*/true, Linkage, Init, Name); 3166 3167 // If there's already an old global variable, replace it with the new one. 3168 if (OldGV) { 3169 GV->takeName(OldGV); 3170 llvm::Constant *NewPtr = 3171 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3172 OldGV->replaceAllUsesWith(NewPtr); 3173 OldGV->eraseFromParent(); 3174 } 3175 3176 if (CGM.supportsCOMDAT() && GV->isWeakForLinker()) 3177 GV->setComdat(M.getOrInsertComdat(GV->getName())); 3178 3179 // The Itanium ABI specifies that type_info objects must be globally 3180 // unique, with one exception: if the type is an incomplete class 3181 // type or a (possibly indirect) pointer to one. That exception 3182 // affects the general case of comparing type_info objects produced 3183 // by the typeid operator, which is why the comparison operators on 3184 // std::type_info generally use the type_info name pointers instead 3185 // of the object addresses. However, the language's built-in uses 3186 // of RTTI generally require class types to be complete, even when 3187 // manipulating pointers to those class types. This allows the 3188 // implementation of dynamic_cast to rely on address equality tests, 3189 // which is much faster. 3190 3191 // All of this is to say that it's important that both the type_info 3192 // object and the type_info name be uniqued when weakly emitted. 3193 3194 // Give the type_info object and name the formal visibility of the 3195 // type itself. 3196 llvm::GlobalValue::VisibilityTypes llvmVisibility; 3197 if (llvm::GlobalValue::isLocalLinkage(Linkage)) 3198 // If the linkage is local, only default visibility makes sense. 3199 llvmVisibility = llvm::GlobalValue::DefaultVisibility; 3200 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden) 3201 llvmVisibility = llvm::GlobalValue::HiddenVisibility; 3202 else 3203 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility()); 3204 3205 TypeName->setVisibility(llvmVisibility); 3206 CGM.setDSOLocal(TypeName); 3207 3208 GV->setVisibility(llvmVisibility); 3209 CGM.setDSOLocal(GV); 3210 3211 if (CGM.getTriple().isWindowsItaniumEnvironment()) { 3212 auto RD = Ty->getAsCXXRecordDecl(); 3213 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) { 3214 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3215 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3216 } else if (RD && RD->hasAttr<DLLImportAttr>() && 3217 ShouldUseExternalRTTIDescriptor(CGM, Ty)) { 3218 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3219 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3220 3221 // Because the typename and the typeinfo are DLL import, convert them to 3222 // declarations rather than definitions. The initializers still need to 3223 // be constructed to calculate the type for the declarations. 3224 TypeName->setInitializer(nullptr); 3225 GV->setInitializer(nullptr); 3226 } 3227 } 3228 3229 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 3230 } 3231 3232 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info 3233 /// for the given Objective-C object type. 3234 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) { 3235 // Drop qualifiers. 3236 const Type *T = OT->getBaseType().getTypePtr(); 3237 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T)); 3238 3239 // The builtin types are abi::__class_type_infos and don't require 3240 // extra fields. 3241 if (isa<BuiltinType>(T)) return; 3242 3243 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl(); 3244 ObjCInterfaceDecl *Super = Class->getSuperClass(); 3245 3246 // Root classes are also __class_type_info. 3247 if (!Super) return; 3248 3249 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super); 3250 3251 // Everything else is single inheritance. 3252 llvm::Constant *BaseTypeInfo = 3253 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy); 3254 Fields.push_back(BaseTypeInfo); 3255 } 3256 3257 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 3258 /// inheritance, according to the Itanium C++ ABI, 2.95p6b. 3259 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) { 3260 // Itanium C++ ABI 2.9.5p6b: 3261 // It adds to abi::__class_type_info a single member pointing to the 3262 // type_info structure for the base type, 3263 llvm::Constant *BaseTypeInfo = 3264 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType()); 3265 Fields.push_back(BaseTypeInfo); 3266 } 3267 3268 namespace { 3269 /// SeenBases - Contains virtual and non-virtual bases seen when traversing 3270 /// a class hierarchy. 3271 struct SeenBases { 3272 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases; 3273 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases; 3274 }; 3275 } 3276 3277 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in 3278 /// abi::__vmi_class_type_info. 3279 /// 3280 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 3281 SeenBases &Bases) { 3282 3283 unsigned Flags = 0; 3284 3285 const CXXRecordDecl *BaseDecl = 3286 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3287 3288 if (Base->isVirtual()) { 3289 // Mark the virtual base as seen. 3290 if (!Bases.VirtualBases.insert(BaseDecl).second) { 3291 // If this virtual base has been seen before, then the class is diamond 3292 // shaped. 3293 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped; 3294 } else { 3295 if (Bases.NonVirtualBases.count(BaseDecl)) 3296 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3297 } 3298 } else { 3299 // Mark the non-virtual base as seen. 3300 if (!Bases.NonVirtualBases.insert(BaseDecl).second) { 3301 // If this non-virtual base has been seen before, then the class has non- 3302 // diamond shaped repeated inheritance. 3303 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3304 } else { 3305 if (Bases.VirtualBases.count(BaseDecl)) 3306 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3307 } 3308 } 3309 3310 // Walk all bases. 3311 for (const auto &I : BaseDecl->bases()) 3312 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 3313 3314 return Flags; 3315 } 3316 3317 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) { 3318 unsigned Flags = 0; 3319 SeenBases Bases; 3320 3321 // Walk all bases. 3322 for (const auto &I : RD->bases()) 3323 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 3324 3325 return Flags; 3326 } 3327 3328 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 3329 /// classes with bases that do not satisfy the abi::__si_class_type_info 3330 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 3331 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) { 3332 llvm::Type *UnsignedIntLTy = 3333 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3334 3335 // Itanium C++ ABI 2.9.5p6c: 3336 // __flags is a word with flags describing details about the class 3337 // structure, which may be referenced by using the __flags_masks 3338 // enumeration. These flags refer to both direct and indirect bases. 3339 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD); 3340 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3341 3342 // Itanium C++ ABI 2.9.5p6c: 3343 // __base_count is a word with the number of direct proper base class 3344 // descriptions that follow. 3345 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases())); 3346 3347 if (!RD->getNumBases()) 3348 return; 3349 3350 // Now add the base class descriptions. 3351 3352 // Itanium C++ ABI 2.9.5p6c: 3353 // __base_info[] is an array of base class descriptions -- one for every 3354 // direct proper base. Each description is of the type: 3355 // 3356 // struct abi::__base_class_type_info { 3357 // public: 3358 // const __class_type_info *__base_type; 3359 // long __offset_flags; 3360 // 3361 // enum __offset_flags_masks { 3362 // __virtual_mask = 0x1, 3363 // __public_mask = 0x2, 3364 // __offset_shift = 8 3365 // }; 3366 // }; 3367 3368 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long 3369 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on 3370 // LLP64 platforms. 3371 // FIXME: Consider updating libc++abi to match, and extend this logic to all 3372 // LLP64 platforms. 3373 QualType OffsetFlagsTy = CGM.getContext().LongTy; 3374 const TargetInfo &TI = CGM.getContext().getTargetInfo(); 3375 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth()) 3376 OffsetFlagsTy = CGM.getContext().LongLongTy; 3377 llvm::Type *OffsetFlagsLTy = 3378 CGM.getTypes().ConvertType(OffsetFlagsTy); 3379 3380 for (const auto &Base : RD->bases()) { 3381 // The __base_type member points to the RTTI for the base type. 3382 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType())); 3383 3384 const CXXRecordDecl *BaseDecl = 3385 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 3386 3387 int64_t OffsetFlags = 0; 3388 3389 // All but the lower 8 bits of __offset_flags are a signed offset. 3390 // For a non-virtual base, this is the offset in the object of the base 3391 // subobject. For a virtual base, this is the offset in the virtual table of 3392 // the virtual base offset for the virtual base referenced (negative). 3393 CharUnits Offset; 3394 if (Base.isVirtual()) 3395 Offset = 3396 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl); 3397 else { 3398 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 3399 Offset = Layout.getBaseClassOffset(BaseDecl); 3400 }; 3401 3402 OffsetFlags = uint64_t(Offset.getQuantity()) << 8; 3403 3404 // The low-order byte of __offset_flags contains flags, as given by the 3405 // masks from the enumeration __offset_flags_masks. 3406 if (Base.isVirtual()) 3407 OffsetFlags |= BCTI_Virtual; 3408 if (Base.getAccessSpecifier() == AS_public) 3409 OffsetFlags |= BCTI_Public; 3410 3411 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags)); 3412 } 3413 } 3414 3415 /// Compute the flags for a __pbase_type_info, and remove the corresponding 3416 /// pieces from \p Type. 3417 static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) { 3418 unsigned Flags = 0; 3419 3420 if (Type.isConstQualified()) 3421 Flags |= ItaniumRTTIBuilder::PTI_Const; 3422 if (Type.isVolatileQualified()) 3423 Flags |= ItaniumRTTIBuilder::PTI_Volatile; 3424 if (Type.isRestrictQualified()) 3425 Flags |= ItaniumRTTIBuilder::PTI_Restrict; 3426 Type = Type.getUnqualifiedType(); 3427 3428 // Itanium C++ ABI 2.9.5p7: 3429 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 3430 // incomplete class type, the incomplete target type flag is set. 3431 if (ContainsIncompleteClassType(Type)) 3432 Flags |= ItaniumRTTIBuilder::PTI_Incomplete; 3433 3434 if (auto *Proto = Type->getAs<FunctionProtoType>()) { 3435 if (Proto->isNothrow(Ctx)) { 3436 Flags |= ItaniumRTTIBuilder::PTI_Noexcept; 3437 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None); 3438 } 3439 } 3440 3441 return Flags; 3442 } 3443 3444 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, 3445 /// used for pointer types. 3446 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) { 3447 // Itanium C++ ABI 2.9.5p7: 3448 // __flags is a flag word describing the cv-qualification and other 3449 // attributes of the type pointed to 3450 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); 3451 3452 llvm::Type *UnsignedIntLTy = 3453 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3454 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3455 3456 // Itanium C++ ABI 2.9.5p7: 3457 // __pointee is a pointer to the std::type_info derivation for the 3458 // unqualified type being pointed to. 3459 llvm::Constant *PointeeTypeInfo = 3460 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); 3461 Fields.push_back(PointeeTypeInfo); 3462 } 3463 3464 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 3465 /// struct, used for member pointer types. 3466 void 3467 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) { 3468 QualType PointeeTy = Ty->getPointeeType(); 3469 3470 // Itanium C++ ABI 2.9.5p7: 3471 // __flags is a flag word describing the cv-qualification and other 3472 // attributes of the type pointed to. 3473 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); 3474 3475 const RecordType *ClassType = cast<RecordType>(Ty->getClass()); 3476 if (IsIncompleteClassType(ClassType)) 3477 Flags |= PTI_ContainingClassIncomplete; 3478 3479 llvm::Type *UnsignedIntLTy = 3480 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3481 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3482 3483 // Itanium C++ ABI 2.9.5p7: 3484 // __pointee is a pointer to the std::type_info derivation for the 3485 // unqualified type being pointed to. 3486 llvm::Constant *PointeeTypeInfo = 3487 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); 3488 Fields.push_back(PointeeTypeInfo); 3489 3490 // Itanium C++ ABI 2.9.5p9: 3491 // __context is a pointer to an abi::__class_type_info corresponding to the 3492 // class type containing the member pointed to 3493 // (e.g., the "A" in "int A::*"). 3494 Fields.push_back( 3495 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0))); 3496 } 3497 3498 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) { 3499 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty); 3500 } 3501 3502 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type, 3503 bool DLLExport) { 3504 QualType PointerType = getContext().getPointerType(Type); 3505 QualType PointerTypeConst = getContext().getPointerType(Type.withConst()); 3506 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport); 3507 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true, 3508 DLLExport); 3509 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true, 3510 DLLExport); 3511 } 3512 3513 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) { 3514 // Types added here must also be added to TypeInfoIsInStandardLibrary. 3515 QualType FundamentalTypes[] = { 3516 getContext().VoidTy, getContext().NullPtrTy, 3517 getContext().BoolTy, getContext().WCharTy, 3518 getContext().CharTy, getContext().UnsignedCharTy, 3519 getContext().SignedCharTy, getContext().ShortTy, 3520 getContext().UnsignedShortTy, getContext().IntTy, 3521 getContext().UnsignedIntTy, getContext().LongTy, 3522 getContext().UnsignedLongTy, getContext().LongLongTy, 3523 getContext().UnsignedLongLongTy, getContext().Int128Ty, 3524 getContext().UnsignedInt128Ty, getContext().HalfTy, 3525 getContext().FloatTy, getContext().DoubleTy, 3526 getContext().LongDoubleTy, getContext().Float128Ty, 3527 getContext().Char16Ty, getContext().Char32Ty 3528 }; 3529 for (const QualType &FundamentalType : FundamentalTypes) 3530 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport); 3531 } 3532 3533 /// What sort of uniqueness rules should we use for the RTTI for the 3534 /// given type? 3535 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness( 3536 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const { 3537 if (shouldRTTIBeUnique()) 3538 return RUK_Unique; 3539 3540 // It's only necessary for linkonce_odr or weak_odr linkage. 3541 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage && 3542 Linkage != llvm::GlobalValue::WeakODRLinkage) 3543 return RUK_Unique; 3544 3545 // It's only necessary with default visibility. 3546 if (CanTy->getVisibility() != DefaultVisibility) 3547 return RUK_Unique; 3548 3549 // If we're not required to publish this symbol, hide it. 3550 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage) 3551 return RUK_NonUniqueHidden; 3552 3553 // If we're required to publish this symbol, as we might be under an 3554 // explicit instantiation, leave it with default visibility but 3555 // enable string-comparisons. 3556 assert(Linkage == llvm::GlobalValue::WeakODRLinkage); 3557 return RUK_NonUniqueVisible; 3558 } 3559 3560 // Find out how to codegen the complete destructor and constructor 3561 namespace { 3562 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT }; 3563 } 3564 static StructorCodegen getCodegenToUse(CodeGenModule &CGM, 3565 const CXXMethodDecl *MD) { 3566 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases) 3567 return StructorCodegen::Emit; 3568 3569 // The complete and base structors are not equivalent if there are any virtual 3570 // bases, so emit separate functions. 3571 if (MD->getParent()->getNumVBases()) 3572 return StructorCodegen::Emit; 3573 3574 GlobalDecl AliasDecl; 3575 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 3576 AliasDecl = GlobalDecl(DD, Dtor_Complete); 3577 } else { 3578 const auto *CD = cast<CXXConstructorDecl>(MD); 3579 AliasDecl = GlobalDecl(CD, Ctor_Complete); 3580 } 3581 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3582 3583 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) 3584 return StructorCodegen::RAUW; 3585 3586 // FIXME: Should we allow available_externally aliases? 3587 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 3588 return StructorCodegen::RAUW; 3589 3590 if (llvm::GlobalValue::isWeakForLinker(Linkage)) { 3591 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5). 3592 if (CGM.getTarget().getTriple().isOSBinFormatELF() || 3593 CGM.getTarget().getTriple().isOSBinFormatWasm()) 3594 return StructorCodegen::COMDAT; 3595 return StructorCodegen::Emit; 3596 } 3597 3598 return StructorCodegen::Alias; 3599 } 3600 3601 static void emitConstructorDestructorAlias(CodeGenModule &CGM, 3602 GlobalDecl AliasDecl, 3603 GlobalDecl TargetDecl) { 3604 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3605 3606 StringRef MangledName = CGM.getMangledName(AliasDecl); 3607 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName); 3608 if (Entry && !Entry->isDeclaration()) 3609 return; 3610 3611 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl)); 3612 3613 // Create the alias with no name. 3614 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee); 3615 3616 // Switch any previous uses to the alias. 3617 if (Entry) { 3618 assert(Entry->getType() == Aliasee->getType() && 3619 "declaration exists with different type"); 3620 Alias->takeName(Entry); 3621 Entry->replaceAllUsesWith(Alias); 3622 Entry->eraseFromParent(); 3623 } else { 3624 Alias->setName(MangledName); 3625 } 3626 3627 // Finally, set up the alias with its proper name and attributes. 3628 CGM.SetCommonAttributes(AliasDecl, Alias); 3629 } 3630 3631 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 3632 StructorType Type) { 3633 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 3634 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD); 3635 3636 StructorCodegen CGType = getCodegenToUse(CGM, MD); 3637 3638 if (Type == StructorType::Complete) { 3639 GlobalDecl CompleteDecl; 3640 GlobalDecl BaseDecl; 3641 if (CD) { 3642 CompleteDecl = GlobalDecl(CD, Ctor_Complete); 3643 BaseDecl = GlobalDecl(CD, Ctor_Base); 3644 } else { 3645 CompleteDecl = GlobalDecl(DD, Dtor_Complete); 3646 BaseDecl = GlobalDecl(DD, Dtor_Base); 3647 } 3648 3649 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) { 3650 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl); 3651 return; 3652 } 3653 3654 if (CGType == StructorCodegen::RAUW) { 3655 StringRef MangledName = CGM.getMangledName(CompleteDecl); 3656 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl); 3657 CGM.addReplacement(MangledName, Aliasee); 3658 return; 3659 } 3660 } 3661 3662 // The base destructor is equivalent to the base destructor of its 3663 // base class if there is exactly one non-virtual base class with a 3664 // non-trivial destructor, there are no fields with a non-trivial 3665 // destructor, and the body of the destructor is trivial. 3666 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT && 3667 !CGM.TryEmitBaseDestructorAsAlias(DD)) 3668 return; 3669 3670 // FIXME: The deleting destructor is equivalent to the selected operator 3671 // delete if: 3672 // * either the delete is a destroying operator delete or the destructor 3673 // would be trivial if it weren't virtual, 3674 // * the conversion from the 'this' parameter to the first parameter of the 3675 // destructor is equivalent to a bitcast, 3676 // * the destructor does not have an implicit "this" return, and 3677 // * the operator delete has the same calling convention and IR function type 3678 // as the destructor. 3679 // In such cases we should try to emit the deleting dtor as an alias to the 3680 // selected 'operator delete'. 3681 3682 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type); 3683 3684 if (CGType == StructorCodegen::COMDAT) { 3685 SmallString<256> Buffer; 3686 llvm::raw_svector_ostream Out(Buffer); 3687 if (DD) 3688 getMangleContext().mangleCXXDtorComdat(DD, Out); 3689 else 3690 getMangleContext().mangleCXXCtorComdat(CD, Out); 3691 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str()); 3692 Fn->setComdat(C); 3693 } else { 3694 CGM.maybeSetTrivialComdat(*MD, *Fn); 3695 } 3696 } 3697 3698 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) { 3699 // void *__cxa_begin_catch(void*); 3700 llvm::FunctionType *FTy = llvm::FunctionType::get( 3701 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3702 3703 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); 3704 } 3705 3706 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) { 3707 // void __cxa_end_catch(); 3708 llvm::FunctionType *FTy = 3709 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 3710 3711 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); 3712 } 3713 3714 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) { 3715 // void *__cxa_get_exception_ptr(void*); 3716 llvm::FunctionType *FTy = llvm::FunctionType::get( 3717 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3718 3719 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr"); 3720 } 3721 3722 namespace { 3723 /// A cleanup to call __cxa_end_catch. In many cases, the caught 3724 /// exception type lets us state definitively that the thrown exception 3725 /// type does not have a destructor. In particular: 3726 /// - Catch-alls tell us nothing, so we have to conservatively 3727 /// assume that the thrown exception might have a destructor. 3728 /// - Catches by reference behave according to their base types. 3729 /// - Catches of non-record types will only trigger for exceptions 3730 /// of non-record types, which never have destructors. 3731 /// - Catches of record types can trigger for arbitrary subclasses 3732 /// of the caught type, so we have to assume the actual thrown 3733 /// exception type might have a throwing destructor, even if the 3734 /// caught type's destructor is trivial or nothrow. 3735 struct CallEndCatch final : EHScopeStack::Cleanup { 3736 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {} 3737 bool MightThrow; 3738 3739 void Emit(CodeGenFunction &CGF, Flags flags) override { 3740 if (!MightThrow) { 3741 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM)); 3742 return; 3743 } 3744 3745 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM)); 3746 } 3747 }; 3748 } 3749 3750 /// Emits a call to __cxa_begin_catch and enters a cleanup to call 3751 /// __cxa_end_catch. 3752 /// 3753 /// \param EndMightThrow - true if __cxa_end_catch might throw 3754 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF, 3755 llvm::Value *Exn, 3756 bool EndMightThrow) { 3757 llvm::CallInst *call = 3758 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn); 3759 3760 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow); 3761 3762 return call; 3763 } 3764 3765 /// A "special initializer" callback for initializing a catch 3766 /// parameter during catch initialization. 3767 static void InitCatchParam(CodeGenFunction &CGF, 3768 const VarDecl &CatchParam, 3769 Address ParamAddr, 3770 SourceLocation Loc) { 3771 // Load the exception from where the landing pad saved it. 3772 llvm::Value *Exn = CGF.getExceptionFromSlot(); 3773 3774 CanQualType CatchType = 3775 CGF.CGM.getContext().getCanonicalType(CatchParam.getType()); 3776 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType); 3777 3778 // If we're catching by reference, we can just cast the object 3779 // pointer to the appropriate pointer. 3780 if (isa<ReferenceType>(CatchType)) { 3781 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType(); 3782 bool EndCatchMightThrow = CaughtType->isRecordType(); 3783 3784 // __cxa_begin_catch returns the adjusted object pointer. 3785 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow); 3786 3787 // We have no way to tell the personality function that we're 3788 // catching by reference, so if we're catching a pointer, 3789 // __cxa_begin_catch will actually return that pointer by value. 3790 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) { 3791 QualType PointeeType = PT->getPointeeType(); 3792 3793 // When catching by reference, generally we should just ignore 3794 // this by-value pointer and use the exception object instead. 3795 if (!PointeeType->isRecordType()) { 3796 3797 // Exn points to the struct _Unwind_Exception header, which 3798 // we have to skip past in order to reach the exception data. 3799 unsigned HeaderSize = 3800 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException(); 3801 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize); 3802 3803 // However, if we're catching a pointer-to-record type that won't 3804 // work, because the personality function might have adjusted 3805 // the pointer. There's actually no way for us to fully satisfy 3806 // the language/ABI contract here: we can't use Exn because it 3807 // might have the wrong adjustment, but we can't use the by-value 3808 // pointer because it's off by a level of abstraction. 3809 // 3810 // The current solution is to dump the adjusted pointer into an 3811 // alloca, which breaks language semantics (because changing the 3812 // pointer doesn't change the exception) but at least works. 3813 // The better solution would be to filter out non-exact matches 3814 // and rethrow them, but this is tricky because the rethrow 3815 // really needs to be catchable by other sites at this landing 3816 // pad. The best solution is to fix the personality function. 3817 } else { 3818 // Pull the pointer for the reference type off. 3819 llvm::Type *PtrTy = 3820 cast<llvm::PointerType>(LLVMCatchTy)->getElementType(); 3821 3822 // Create the temporary and write the adjusted pointer into it. 3823 Address ExnPtrTmp = 3824 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp"); 3825 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 3826 CGF.Builder.CreateStore(Casted, ExnPtrTmp); 3827 3828 // Bind the reference to the temporary. 3829 AdjustedExn = ExnPtrTmp.getPointer(); 3830 } 3831 } 3832 3833 llvm::Value *ExnCast = 3834 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref"); 3835 CGF.Builder.CreateStore(ExnCast, ParamAddr); 3836 return; 3837 } 3838 3839 // Scalars and complexes. 3840 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType); 3841 if (TEK != TEK_Aggregate) { 3842 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false); 3843 3844 // If the catch type is a pointer type, __cxa_begin_catch returns 3845 // the pointer by value. 3846 if (CatchType->hasPointerRepresentation()) { 3847 llvm::Value *CastExn = 3848 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted"); 3849 3850 switch (CatchType.getQualifiers().getObjCLifetime()) { 3851 case Qualifiers::OCL_Strong: 3852 CastExn = CGF.EmitARCRetainNonBlock(CastExn); 3853 // fallthrough 3854 3855 case Qualifiers::OCL_None: 3856 case Qualifiers::OCL_ExplicitNone: 3857 case Qualifiers::OCL_Autoreleasing: 3858 CGF.Builder.CreateStore(CastExn, ParamAddr); 3859 return; 3860 3861 case Qualifiers::OCL_Weak: 3862 CGF.EmitARCInitWeak(ParamAddr, CastExn); 3863 return; 3864 } 3865 llvm_unreachable("bad ownership qualifier!"); 3866 } 3867 3868 // Otherwise, it returns a pointer into the exception object. 3869 3870 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 3871 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 3872 3873 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType); 3874 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType); 3875 switch (TEK) { 3876 case TEK_Complex: 3877 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV, 3878 /*init*/ true); 3879 return; 3880 case TEK_Scalar: { 3881 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc); 3882 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true); 3883 return; 3884 } 3885 case TEK_Aggregate: 3886 llvm_unreachable("evaluation kind filtered out!"); 3887 } 3888 llvm_unreachable("bad evaluation kind"); 3889 } 3890 3891 assert(isa<RecordType>(CatchType) && "unexpected catch type!"); 3892 auto catchRD = CatchType->getAsCXXRecordDecl(); 3893 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD); 3894 3895 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 3896 3897 // Check for a copy expression. If we don't have a copy expression, 3898 // that means a trivial copy is okay. 3899 const Expr *copyExpr = CatchParam.getInit(); 3900 if (!copyExpr) { 3901 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true); 3902 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), 3903 caughtExnAlignment); 3904 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType); 3905 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType); 3906 CGF.EmitAggregateCopy(Dest, Src, CatchType); 3907 return; 3908 } 3909 3910 // We have to call __cxa_get_exception_ptr to get the adjusted 3911 // pointer before copying. 3912 llvm::CallInst *rawAdjustedExn = 3913 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn); 3914 3915 // Cast that to the appropriate type. 3916 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), 3917 caughtExnAlignment); 3918 3919 // The copy expression is defined in terms of an OpaqueValueExpr. 3920 // Find it and map it to the adjusted expression. 3921 CodeGenFunction::OpaqueValueMapping 3922 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr), 3923 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType())); 3924 3925 // Call the copy ctor in a terminate scope. 3926 CGF.EHStack.pushTerminate(); 3927 3928 // Perform the copy construction. 3929 CGF.EmitAggExpr(copyExpr, 3930 AggValueSlot::forAddr(ParamAddr, Qualifiers(), 3931 AggValueSlot::IsNotDestructed, 3932 AggValueSlot::DoesNotNeedGCBarriers, 3933 AggValueSlot::IsNotAliased)); 3934 3935 // Leave the terminate scope. 3936 CGF.EHStack.popTerminate(); 3937 3938 // Undo the opaque value mapping. 3939 opaque.pop(); 3940 3941 // Finally we can call __cxa_begin_catch. 3942 CallBeginCatch(CGF, Exn, true); 3943 } 3944 3945 /// Begins a catch statement by initializing the catch variable and 3946 /// calling __cxa_begin_catch. 3947 void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF, 3948 const CXXCatchStmt *S) { 3949 // We have to be very careful with the ordering of cleanups here: 3950 // C++ [except.throw]p4: 3951 // The destruction [of the exception temporary] occurs 3952 // immediately after the destruction of the object declared in 3953 // the exception-declaration in the handler. 3954 // 3955 // So the precise ordering is: 3956 // 1. Construct catch variable. 3957 // 2. __cxa_begin_catch 3958 // 3. Enter __cxa_end_catch cleanup 3959 // 4. Enter dtor cleanup 3960 // 3961 // We do this by using a slightly abnormal initialization process. 3962 // Delegation sequence: 3963 // - ExitCXXTryStmt opens a RunCleanupsScope 3964 // - EmitAutoVarAlloca creates the variable and debug info 3965 // - InitCatchParam initializes the variable from the exception 3966 // - CallBeginCatch calls __cxa_begin_catch 3967 // - CallBeginCatch enters the __cxa_end_catch cleanup 3968 // - EmitAutoVarCleanups enters the variable destructor cleanup 3969 // - EmitCXXTryStmt emits the code for the catch body 3970 // - EmitCXXTryStmt close the RunCleanupsScope 3971 3972 VarDecl *CatchParam = S->getExceptionDecl(); 3973 if (!CatchParam) { 3974 llvm::Value *Exn = CGF.getExceptionFromSlot(); 3975 CallBeginCatch(CGF, Exn, true); 3976 return; 3977 } 3978 3979 // Emit the local. 3980 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); 3981 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart()); 3982 CGF.EmitAutoVarCleanups(var); 3983 } 3984 3985 /// Get or define the following function: 3986 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn 3987 /// This code is used only in C++. 3988 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) { 3989 llvm::FunctionType *fnTy = 3990 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3991 llvm::Constant *fnRef = CGM.CreateRuntimeFunction( 3992 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true); 3993 3994 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef); 3995 if (fn && fn->empty()) { 3996 fn->setDoesNotThrow(); 3997 fn->setDoesNotReturn(); 3998 3999 // What we really want is to massively penalize inlining without 4000 // forbidding it completely. The difference between that and 4001 // 'noinline' is negligible. 4002 fn->addFnAttr(llvm::Attribute::NoInline); 4003 4004 // Allow this function to be shared across translation units, but 4005 // we don't want it to turn into an exported symbol. 4006 fn->setLinkage(llvm::Function::LinkOnceODRLinkage); 4007 fn->setVisibility(llvm::Function::HiddenVisibility); 4008 if (CGM.supportsCOMDAT()) 4009 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName())); 4010 4011 // Set up the function. 4012 llvm::BasicBlock *entry = 4013 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn); 4014 CGBuilderTy builder(CGM, entry); 4015 4016 // Pull the exception pointer out of the parameter list. 4017 llvm::Value *exn = &*fn->arg_begin(); 4018 4019 // Call __cxa_begin_catch(exn). 4020 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn); 4021 catchCall->setDoesNotThrow(); 4022 catchCall->setCallingConv(CGM.getRuntimeCC()); 4023 4024 // Call std::terminate(). 4025 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn()); 4026 termCall->setDoesNotThrow(); 4027 termCall->setDoesNotReturn(); 4028 termCall->setCallingConv(CGM.getRuntimeCC()); 4029 4030 // std::terminate cannot return. 4031 builder.CreateUnreachable(); 4032 } 4033 4034 return fnRef; 4035 } 4036 4037 llvm::CallInst * 4038 ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF, 4039 llvm::Value *Exn) { 4040 // In C++, we want to call __cxa_begin_catch() before terminating. 4041 if (Exn) { 4042 assert(CGF.CGM.getLangOpts().CPlusPlus); 4043 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn); 4044 } 4045 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn()); 4046 } 4047 4048 std::pair<llvm::Value *, const CXXRecordDecl *> 4049 ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This, 4050 const CXXRecordDecl *RD) { 4051 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD}; 4052 } 4053