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