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