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