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