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