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