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