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