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