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