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