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