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