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