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