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