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