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