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