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