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