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