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