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