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