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