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