1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides C++ code generation targeting the Itanium C++ ABI.  The class
11 // in this file generates structures that follow the Itanium C++ ABI, which is
12 // documented at:
13 //  http://www.codesourcery.com/public/cxx-abi/abi.html
14 //  http://www.codesourcery.com/public/cxx-abi/abi-eh.html
15 //
16 // It also supports the closely-related ARM ABI, documented at:
17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "CGCXXABI.h"
22 #include "CGRecordLayout.h"
23 #include "CGVTables.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenModule.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/AST/Type.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Value.h"
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 namespace {
37 class ItaniumCXXABI : public CodeGen::CGCXXABI {
38   /// VTables - All the vtables which have been defined.
39   llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
40 
41 protected:
42   bool UseARMMethodPtrABI;
43   bool UseARMGuardVarABI;
44 
45   ItaniumMangleContext &getMangleContext() {
46     return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
47   }
48 
49 public:
50   ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
51                 bool UseARMMethodPtrABI = false,
52                 bool UseARMGuardVarABI = false) :
53     CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
54     UseARMGuardVarABI(UseARMGuardVarABI) { }
55 
56   bool classifyReturnType(CGFunctionInfo &FI) const override;
57 
58   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
59     // Structures with either a non-trivial destructor or a non-trivial
60     // copy constructor are always indirect.
61     // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
62     // special members.
63     if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
64       return RAA_Indirect;
65     return RAA_Default;
66   }
67 
68   bool isZeroInitializable(const MemberPointerType *MPT) override;
69 
70   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
71 
72   llvm::Value *
73     EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74                                     const Expr *E,
75                                     llvm::Value *&This,
76                                     llvm::Value *MemFnPtr,
77                                     const MemberPointerType *MPT) override;
78 
79   llvm::Value *
80     EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
81                                  llvm::Value *Base,
82                                  llvm::Value *MemPtr,
83                                  const MemberPointerType *MPT) override;
84 
85   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
86                                            const CastExpr *E,
87                                            llvm::Value *Src) override;
88   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
89                                               llvm::Constant *Src) override;
90 
91   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
92 
93   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
94   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
95                                         CharUnits offset) override;
96   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
97   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
98                                      CharUnits ThisAdjustment);
99 
100   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
101                                            llvm::Value *L, llvm::Value *R,
102                                            const MemberPointerType *MPT,
103                                            bool Inequality) override;
104 
105   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
106                                          llvm::Value *Addr,
107                                          const MemberPointerType *MPT) override;
108 
109   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
110                                       QualType type) override;
111 
112   void EmitFundamentalRTTIDescriptor(QualType Type);
113   void EmitFundamentalRTTIDescriptors();
114   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
115 
116   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
117   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
118   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
119                           llvm::Value *ThisPtr,
120                           llvm::Type *StdTypeInfoPtrTy) override;
121 
122   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
123                                           QualType SrcRecordTy) override;
124 
125   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
126                                    QualType SrcRecordTy, QualType DestTy,
127                                    QualType DestRecordTy,
128                                    llvm::BasicBlock *CastEnd) override;
129 
130   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
131                                      QualType SrcRecordTy,
132                                      QualType DestTy) override;
133 
134   bool EmitBadCastCall(CodeGenFunction &CGF) override;
135 
136   llvm::Value *
137     GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
138                               const CXXRecordDecl *ClassDecl,
139                               const CXXRecordDecl *BaseClassDecl) override;
140 
141   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
142                                  CXXCtorType T, CanQualType &ResTy,
143                                  SmallVectorImpl<CanQualType> &ArgTys) override;
144 
145   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
146 
147   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
148                                 CXXDtorType T, CanQualType &ResTy,
149                                 SmallVectorImpl<CanQualType> &ArgTys) override;
150 
151   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
152                               CXXDtorType DT) const override {
153     // Itanium does not emit any destructor variant as an inline thunk.
154     // Delegating may occur as an optimization, but all variants are either
155     // emitted with external linkage or as linkonce if they are inline and used.
156     return false;
157   }
158 
159   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
160 
161   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
162                                  FunctionArgList &Params) override;
163 
164   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
165 
166   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
167                                       const CXXConstructorDecl *D,
168                                       CXXCtorType Type, bool ForVirtualBase,
169                                       bool Delegating,
170                                       CallArgList &Args) override;
171 
172   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
173                           CXXDtorType Type, bool ForVirtualBase,
174                           bool Delegating, llvm::Value *This) override;
175 
176   void emitVTableDefinitions(CodeGenVTables &CGVT,
177                              const CXXRecordDecl *RD) override;
178 
179   llvm::Value *getVTableAddressPointInStructor(
180       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
181       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
182       bool &NeedsVirtualOffset) override;
183 
184   llvm::Constant *
185   getVTableAddressPointForConstExpr(BaseSubobject Base,
186                                     const CXXRecordDecl *VTableClass) override;
187 
188   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
189                                         CharUnits VPtrOffset) override;
190 
191   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
192                                          llvm::Value *This,
193                                          llvm::Type *Ty) override;
194 
195   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
196                                  const CXXDestructorDecl *Dtor,
197                                  CXXDtorType DtorType, llvm::Value *This,
198                                  const CXXMemberCallExpr *CE) override;
199 
200   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
201 
202   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
203                        bool ReturnAdjustment) override {
204     // Allow inlining of thunks by emitting them with available_externally
205     // linkage together with vtables when needed.
206     if (ForVTable)
207       Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
208   }
209 
210   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
211                                      const ThisAdjustment &TA) override;
212 
213   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
214                                        const ReturnAdjustment &RA) override;
215 
216   StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
217   StringRef GetDeletedVirtualCallName() override
218     { return "__cxa_deleted_virtual"; }
219 
220   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
221   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
222                                      llvm::Value *NewPtr,
223                                      llvm::Value *NumElements,
224                                      const CXXNewExpr *expr,
225                                      QualType ElementType) override;
226   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
227                                    llvm::Value *allocPtr,
228                                    CharUnits cookieSize) override;
229 
230   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
231                        llvm::GlobalVariable *DeclPtr,
232                        bool PerformInit) override;
233   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
234                           llvm::Constant *dtor, llvm::Constant *addr) override;
235 
236   llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
237                                                 llvm::GlobalVariable *Var);
238   void EmitThreadLocalInitFuncs(
239       ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
240       llvm::Function *InitFunc) override;
241   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
242                                       QualType LValType) override;
243 
244   bool NeedsVTTParameter(GlobalDecl GD) override;
245 
246   /**************************** RTTI Uniqueness ******************************/
247 
248 protected:
249   /// Returns true if the ABI requires RTTI type_info objects to be unique
250   /// across a program.
251   virtual bool shouldRTTIBeUnique() const { return true; }
252 
253 public:
254   /// What sort of unique-RTTI behavior should we use?
255   enum RTTIUniquenessKind {
256     /// We are guaranteeing, or need to guarantee, that the RTTI string
257     /// is unique.
258     RUK_Unique,
259 
260     /// We are not guaranteeing uniqueness for the RTTI string, so we
261     /// can demote to hidden visibility but must use string comparisons.
262     RUK_NonUniqueHidden,
263 
264     /// We are not guaranteeing uniqueness for the RTTI string, so we
265     /// have to use string comparisons, but we also have to emit it with
266     /// non-hidden visibility.
267     RUK_NonUniqueVisible
268   };
269 
270   /// Return the required visibility status for the given type and linkage in
271   /// the current ABI.
272   RTTIUniquenessKind
273   classifyRTTIUniqueness(QualType CanTy,
274                          llvm::GlobalValue::LinkageTypes Linkage) const;
275   friend class ItaniumRTTIBuilder;
276 };
277 
278 class ARMCXXABI : public ItaniumCXXABI {
279 public:
280   ARMCXXABI(CodeGen::CodeGenModule &CGM) :
281     ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
282                   /* UseARMGuardVarABI = */ true) {}
283 
284   bool HasThisReturn(GlobalDecl GD) const override {
285     return (isa<CXXConstructorDecl>(GD.getDecl()) || (
286               isa<CXXDestructorDecl>(GD.getDecl()) &&
287               GD.getDtorType() != Dtor_Deleting));
288   }
289 
290   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
291                            QualType ResTy) override;
292 
293   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
294   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
295                                      llvm::Value *NewPtr,
296                                      llvm::Value *NumElements,
297                                      const CXXNewExpr *expr,
298                                      QualType ElementType) override;
299   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
300                                    CharUnits cookieSize) override;
301 };
302 
303 class iOS64CXXABI : public ARMCXXABI {
304 public:
305   iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
306 
307   // ARM64 libraries are prepared for non-unique RTTI.
308   bool shouldRTTIBeUnique() const override { return false; }
309 };
310 }
311 
312 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
313   switch (CGM.getTarget().getCXXABI().getKind()) {
314   // For IR-generation purposes, there's no significant difference
315   // between the ARM and iOS ABIs.
316   case TargetCXXABI::GenericARM:
317   case TargetCXXABI::iOS:
318     return new ARMCXXABI(CGM);
319 
320   case TargetCXXABI::iOS64:
321     return new iOS64CXXABI(CGM);
322 
323   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
324   // include the other 32-bit ARM oddities: constructor/destructor return values
325   // and array cookies.
326   case TargetCXXABI::GenericAArch64:
327     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
328                              /* UseARMGuardVarABI = */ true);
329 
330   case TargetCXXABI::GenericItanium:
331     if (CGM.getContext().getTargetInfo().getTriple().getArch()
332         == llvm::Triple::le32) {
333       // For PNaCl, use ARM-style method pointers so that PNaCl code
334       // does not assume anything about the alignment of function
335       // pointers.
336       return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
337                                /* UseARMGuardVarABI = */ false);
338     }
339     return new ItaniumCXXABI(CGM);
340 
341   case TargetCXXABI::Microsoft:
342     llvm_unreachable("Microsoft ABI is not Itanium-based");
343   }
344   llvm_unreachable("bad ABI kind");
345 }
346 
347 llvm::Type *
348 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
349   if (MPT->isMemberDataPointer())
350     return CGM.PtrDiffTy;
351   return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
352 }
353 
354 /// In the Itanium and ARM ABIs, method pointers have the form:
355 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
356 ///
357 /// In the Itanium ABI:
358 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
359 ///  - the this-adjustment is (memptr.adj)
360 ///  - the virtual offset is (memptr.ptr - 1)
361 ///
362 /// In the ARM ABI:
363 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
364 ///  - the this-adjustment is (memptr.adj >> 1)
365 ///  - the virtual offset is (memptr.ptr)
366 /// ARM uses 'adj' for the virtual flag because Thumb functions
367 /// may be only single-byte aligned.
368 ///
369 /// If the member is virtual, the adjusted 'this' pointer points
370 /// to a vtable pointer from which the virtual offset is applied.
371 ///
372 /// If the member is non-virtual, memptr.ptr is the address of
373 /// the function to call.
374 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
375     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
376     llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
377   CGBuilderTy &Builder = CGF.Builder;
378 
379   const FunctionProtoType *FPT =
380     MPT->getPointeeType()->getAs<FunctionProtoType>();
381   const CXXRecordDecl *RD =
382     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
383 
384   llvm::FunctionType *FTy =
385     CGM.getTypes().GetFunctionType(
386       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
387 
388   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
389 
390   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
391   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
392   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
393 
394   // Extract memptr.adj, which is in the second field.
395   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
396 
397   // Compute the true adjustment.
398   llvm::Value *Adj = RawAdj;
399   if (UseARMMethodPtrABI)
400     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
401 
402   // Apply the adjustment and cast back to the original struct type
403   // for consistency.
404   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
405   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
406   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
407 
408   // Load the function pointer.
409   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
410 
411   // If the LSB in the function pointer is 1, the function pointer points to
412   // a virtual function.
413   llvm::Value *IsVirtual;
414   if (UseARMMethodPtrABI)
415     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
416   else
417     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
418   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
419   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
420 
421   // In the virtual path, the adjustment left 'This' pointing to the
422   // vtable of the correct base subobject.  The "function pointer" is an
423   // offset within the vtable (+1 for the virtual flag on non-ARM).
424   CGF.EmitBlock(FnVirtual);
425 
426   // Cast the adjusted this to a pointer to vtable pointer and load.
427   llvm::Type *VTableTy = Builder.getInt8PtrTy();
428   llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
429 
430   // Apply the offset.
431   llvm::Value *VTableOffset = FnAsInt;
432   if (!UseARMMethodPtrABI)
433     VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
434   VTable = Builder.CreateGEP(VTable, VTableOffset);
435 
436   // Load the virtual function to call.
437   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
438   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
439   CGF.EmitBranch(FnEnd);
440 
441   // In the non-virtual path, the function pointer is actually a
442   // function pointer.
443   CGF.EmitBlock(FnNonVirtual);
444   llvm::Value *NonVirtualFn =
445     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
446 
447   // We're done.
448   CGF.EmitBlock(FnEnd);
449   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
450   Callee->addIncoming(VirtualFn, FnVirtual);
451   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
452   return Callee;
453 }
454 
455 /// Compute an l-value by applying the given pointer-to-member to a
456 /// base object.
457 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
458     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
459     const MemberPointerType *MPT) {
460   assert(MemPtr->getType() == CGM.PtrDiffTy);
461 
462   CGBuilderTy &Builder = CGF.Builder;
463 
464   unsigned AS = Base->getType()->getPointerAddressSpace();
465 
466   // Cast to char*.
467   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
468 
469   // Apply the offset, which we assume is non-null.
470   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
471 
472   // Cast the address to the appropriate pointer type, adopting the
473   // address space of the base pointer.
474   llvm::Type *PType
475     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
476   return Builder.CreateBitCast(Addr, PType);
477 }
478 
479 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
480 /// conversion.
481 ///
482 /// Bitcast conversions are always a no-op under Itanium.
483 ///
484 /// Obligatory offset/adjustment diagram:
485 ///         <-- offset -->          <-- adjustment -->
486 ///   |--------------------------|----------------------|--------------------|
487 ///   ^Derived address point     ^Base address point    ^Member address point
488 ///
489 /// So when converting a base member pointer to a derived member pointer,
490 /// we add the offset to the adjustment because the address point has
491 /// decreased;  and conversely, when converting a derived MP to a base MP
492 /// we subtract the offset from the adjustment because the address point
493 /// has increased.
494 ///
495 /// The standard forbids (at compile time) conversion to and from
496 /// virtual bases, which is why we don't have to consider them here.
497 ///
498 /// The standard forbids (at run time) casting a derived MP to a base
499 /// MP when the derived MP does not point to a member of the base.
500 /// This is why -1 is a reasonable choice for null data member
501 /// pointers.
502 llvm::Value *
503 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
504                                            const CastExpr *E,
505                                            llvm::Value *src) {
506   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
507          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
508          E->getCastKind() == CK_ReinterpretMemberPointer);
509 
510   // Under Itanium, reinterprets don't require any additional processing.
511   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
512 
513   // Use constant emission if we can.
514   if (isa<llvm::Constant>(src))
515     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
516 
517   llvm::Constant *adj = getMemberPointerAdjustment(E);
518   if (!adj) return src;
519 
520   CGBuilderTy &Builder = CGF.Builder;
521   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
522 
523   const MemberPointerType *destTy =
524     E->getType()->castAs<MemberPointerType>();
525 
526   // For member data pointers, this is just a matter of adding the
527   // offset if the source is non-null.
528   if (destTy->isMemberDataPointer()) {
529     llvm::Value *dst;
530     if (isDerivedToBase)
531       dst = Builder.CreateNSWSub(src, adj, "adj");
532     else
533       dst = Builder.CreateNSWAdd(src, adj, "adj");
534 
535     // Null check.
536     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
537     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
538     return Builder.CreateSelect(isNull, src, dst);
539   }
540 
541   // The this-adjustment is left-shifted by 1 on ARM.
542   if (UseARMMethodPtrABI) {
543     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
544     offset <<= 1;
545     adj = llvm::ConstantInt::get(adj->getType(), offset);
546   }
547 
548   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
549   llvm::Value *dstAdj;
550   if (isDerivedToBase)
551     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
552   else
553     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
554 
555   return Builder.CreateInsertValue(src, dstAdj, 1);
556 }
557 
558 llvm::Constant *
559 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
560                                            llvm::Constant *src) {
561   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
562          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
563          E->getCastKind() == CK_ReinterpretMemberPointer);
564 
565   // Under Itanium, reinterprets don't require any additional processing.
566   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
567 
568   // If the adjustment is trivial, we don't need to do anything.
569   llvm::Constant *adj = getMemberPointerAdjustment(E);
570   if (!adj) return src;
571 
572   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
573 
574   const MemberPointerType *destTy =
575     E->getType()->castAs<MemberPointerType>();
576 
577   // For member data pointers, this is just a matter of adding the
578   // offset if the source is non-null.
579   if (destTy->isMemberDataPointer()) {
580     // null maps to null.
581     if (src->isAllOnesValue()) return src;
582 
583     if (isDerivedToBase)
584       return llvm::ConstantExpr::getNSWSub(src, adj);
585     else
586       return llvm::ConstantExpr::getNSWAdd(src, adj);
587   }
588 
589   // The this-adjustment is left-shifted by 1 on ARM.
590   if (UseARMMethodPtrABI) {
591     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
592     offset <<= 1;
593     adj = llvm::ConstantInt::get(adj->getType(), offset);
594   }
595 
596   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
597   llvm::Constant *dstAdj;
598   if (isDerivedToBase)
599     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
600   else
601     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
602 
603   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
604 }
605 
606 llvm::Constant *
607 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
608   // Itanium C++ ABI 2.3:
609   //   A NULL pointer is represented as -1.
610   if (MPT->isMemberDataPointer())
611     return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
612 
613   llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
614   llvm::Constant *Values[2] = { Zero, Zero };
615   return llvm::ConstantStruct::getAnon(Values);
616 }
617 
618 llvm::Constant *
619 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
620                                      CharUnits offset) {
621   // Itanium C++ ABI 2.3:
622   //   A pointer to data member is an offset from the base address of
623   //   the class object containing it, represented as a ptrdiff_t
624   return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
625 }
626 
627 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
628   return BuildMemberPointer(MD, CharUnits::Zero());
629 }
630 
631 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
632                                                   CharUnits ThisAdjustment) {
633   assert(MD->isInstance() && "Member function must not be static!");
634   MD = MD->getCanonicalDecl();
635 
636   CodeGenTypes &Types = CGM.getTypes();
637 
638   // Get the function pointer (or index if this is a virtual function).
639   llvm::Constant *MemPtr[2];
640   if (MD->isVirtual()) {
641     uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
642 
643     const ASTContext &Context = getContext();
644     CharUnits PointerWidth =
645       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
646     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
647 
648     if (UseARMMethodPtrABI) {
649       // ARM C++ ABI 3.2.1:
650       //   This ABI specifies that adj contains twice the this
651       //   adjustment, plus 1 if the member function is virtual. The
652       //   least significant bit of adj then makes exactly the same
653       //   discrimination as the least significant bit of ptr does for
654       //   Itanium.
655       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
656       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
657                                          2 * ThisAdjustment.getQuantity() + 1);
658     } else {
659       // Itanium C++ ABI 2.3:
660       //   For a virtual function, [the pointer field] is 1 plus the
661       //   virtual table offset (in bytes) of the function,
662       //   represented as a ptrdiff_t.
663       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
664       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
665                                          ThisAdjustment.getQuantity());
666     }
667   } else {
668     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
669     llvm::Type *Ty;
670     // Check whether the function has a computable LLVM signature.
671     if (Types.isFuncTypeConvertible(FPT)) {
672       // The function has a computable LLVM signature; use the correct type.
673       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
674     } else {
675       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
676       // function type is incomplete.
677       Ty = CGM.PtrDiffTy;
678     }
679     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
680 
681     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
682     MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
683                                        (UseARMMethodPtrABI ? 2 : 1) *
684                                        ThisAdjustment.getQuantity());
685   }
686 
687   return llvm::ConstantStruct::getAnon(MemPtr);
688 }
689 
690 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
691                                                  QualType MPType) {
692   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
693   const ValueDecl *MPD = MP.getMemberPointerDecl();
694   if (!MPD)
695     return EmitNullMemberPointer(MPT);
696 
697   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
698 
699   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
700     return BuildMemberPointer(MD, ThisAdjustment);
701 
702   CharUnits FieldOffset =
703     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
704   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
705 }
706 
707 /// The comparison algorithm is pretty easy: the member pointers are
708 /// the same if they're either bitwise identical *or* both null.
709 ///
710 /// ARM is different here only because null-ness is more complicated.
711 llvm::Value *
712 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
713                                            llvm::Value *L,
714                                            llvm::Value *R,
715                                            const MemberPointerType *MPT,
716                                            bool Inequality) {
717   CGBuilderTy &Builder = CGF.Builder;
718 
719   llvm::ICmpInst::Predicate Eq;
720   llvm::Instruction::BinaryOps And, Or;
721   if (Inequality) {
722     Eq = llvm::ICmpInst::ICMP_NE;
723     And = llvm::Instruction::Or;
724     Or = llvm::Instruction::And;
725   } else {
726     Eq = llvm::ICmpInst::ICMP_EQ;
727     And = llvm::Instruction::And;
728     Or = llvm::Instruction::Or;
729   }
730 
731   // Member data pointers are easy because there's a unique null
732   // value, so it just comes down to bitwise equality.
733   if (MPT->isMemberDataPointer())
734     return Builder.CreateICmp(Eq, L, R);
735 
736   // For member function pointers, the tautologies are more complex.
737   // The Itanium tautology is:
738   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
739   // The ARM tautology is:
740   //   (L == R) <==> (L.ptr == R.ptr &&
741   //                  (L.adj == R.adj ||
742   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
743   // The inequality tautologies have exactly the same structure, except
744   // applying De Morgan's laws.
745 
746   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
747   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
748 
749   // This condition tests whether L.ptr == R.ptr.  This must always be
750   // true for equality to hold.
751   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
752 
753   // This condition, together with the assumption that L.ptr == R.ptr,
754   // tests whether the pointers are both null.  ARM imposes an extra
755   // condition.
756   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
757   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
758 
759   // This condition tests whether L.adj == R.adj.  If this isn't
760   // true, the pointers are unequal unless they're both null.
761   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
762   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
763   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
764 
765   // Null member function pointers on ARM clear the low bit of Adj,
766   // so the zero condition has to check that neither low bit is set.
767   if (UseARMMethodPtrABI) {
768     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
769 
770     // Compute (l.adj | r.adj) & 1 and test it against zero.
771     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
772     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
773     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
774                                                       "cmp.or.adj");
775     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
776   }
777 
778   // Tie together all our conditions.
779   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
780   Result = Builder.CreateBinOp(And, PtrEq, Result,
781                                Inequality ? "memptr.ne" : "memptr.eq");
782   return Result;
783 }
784 
785 llvm::Value *
786 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
787                                           llvm::Value *MemPtr,
788                                           const MemberPointerType *MPT) {
789   CGBuilderTy &Builder = CGF.Builder;
790 
791   /// For member data pointers, this is just a check against -1.
792   if (MPT->isMemberDataPointer()) {
793     assert(MemPtr->getType() == CGM.PtrDiffTy);
794     llvm::Value *NegativeOne =
795       llvm::Constant::getAllOnesValue(MemPtr->getType());
796     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
797   }
798 
799   // In Itanium, a member function pointer is not null if 'ptr' is not null.
800   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
801 
802   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
803   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
804 
805   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
806   // (the virtual bit) is set.
807   if (UseARMMethodPtrABI) {
808     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
809     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
810     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
811     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
812                                                   "memptr.isvirtual");
813     Result = Builder.CreateOr(Result, IsVirtual);
814   }
815 
816   return Result;
817 }
818 
819 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
820   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
821   if (!RD)
822     return false;
823 
824   // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
825   // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
826   // special members.
827   if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
828     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
829     return true;
830   }
831   return false;
832 }
833 
834 /// The Itanium ABI requires non-zero initialization only for data
835 /// member pointers, for which '0' is a valid offset.
836 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
837   return MPT->getPointeeType()->isFunctionType();
838 }
839 
840 /// The Itanium ABI always places an offset to the complete object
841 /// at entry -2 in the vtable.
842 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
843                                                    llvm::Value *ptr,
844                                                    QualType type) {
845   // Grab the vtable pointer as an intptr_t*.
846   llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
847 
848   // Track back to entry -2 and pull out the offset there.
849   llvm::Value *offsetPtr =
850     CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
851   llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
852   offset->setAlignment(CGF.PointerAlignInBytes);
853 
854   // Apply the offset.
855   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
856   return CGF.Builder.CreateInBoundsGEP(ptr, offset);
857 }
858 
859 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
860   // void *__dynamic_cast(const void *sub,
861   //                      const abi::__class_type_info *src,
862   //                      const abi::__class_type_info *dst,
863   //                      std::ptrdiff_t src2dst_offset);
864 
865   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
866   llvm::Type *PtrDiffTy =
867     CGF.ConvertType(CGF.getContext().getPointerDiffType());
868 
869   llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
870 
871   llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
872 
873   // Mark the function as nounwind readonly.
874   llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
875                                             llvm::Attribute::ReadOnly };
876   llvm::AttributeSet Attrs = llvm::AttributeSet::get(
877       CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
878 
879   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
880 }
881 
882 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
883   // void __cxa_bad_cast();
884   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
885   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
886 }
887 
888 /// \brief Compute the src2dst_offset hint as described in the
889 /// Itanium C++ ABI [2.9.7]
890 static CharUnits computeOffsetHint(ASTContext &Context,
891                                    const CXXRecordDecl *Src,
892                                    const CXXRecordDecl *Dst) {
893   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
894                      /*DetectVirtual=*/false);
895 
896   // If Dst is not derived from Src we can skip the whole computation below and
897   // return that Src is not a public base of Dst.  Record all inheritance paths.
898   if (!Dst->isDerivedFrom(Src, Paths))
899     return CharUnits::fromQuantity(-2ULL);
900 
901   unsigned NumPublicPaths = 0;
902   CharUnits Offset;
903 
904   // Now walk all possible inheritance paths.
905   for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
906        ++I) {
907     if (I->Access != AS_public) // Ignore non-public inheritance.
908       continue;
909 
910     ++NumPublicPaths;
911 
912     for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
913       // If the path contains a virtual base class we can't give any hint.
914       // -1: no hint.
915       if (J->Base->isVirtual())
916         return CharUnits::fromQuantity(-1ULL);
917 
918       if (NumPublicPaths > 1) // Won't use offsets, skip computation.
919         continue;
920 
921       // Accumulate the base class offsets.
922       const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
923       Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
924     }
925   }
926 
927   // -2: Src is not a public base of Dst.
928   if (NumPublicPaths == 0)
929     return CharUnits::fromQuantity(-2ULL);
930 
931   // -3: Src is a multiple public base type but never a virtual base type.
932   if (NumPublicPaths > 1)
933     return CharUnits::fromQuantity(-3ULL);
934 
935   // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
936   // Return the offset of Src from the origin of Dst.
937   return Offset;
938 }
939 
940 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
941   // void __cxa_bad_typeid();
942   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
943 
944   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
945 }
946 
947 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
948                                               QualType SrcRecordTy) {
949   return IsDeref;
950 }
951 
952 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
953   llvm::Value *Fn = getBadTypeidFn(CGF);
954   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
955   CGF.Builder.CreateUnreachable();
956 }
957 
958 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
959                                        QualType SrcRecordTy,
960                                        llvm::Value *ThisPtr,
961                                        llvm::Type *StdTypeInfoPtrTy) {
962   llvm::Value *Value =
963       CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
964 
965   // Load the type info.
966   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
967   return CGF.Builder.CreateLoad(Value);
968 }
969 
970 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
971                                                        QualType SrcRecordTy) {
972   return SrcIsPtr;
973 }
974 
975 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
976     CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
977     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
978   llvm::Type *PtrDiffLTy =
979       CGF.ConvertType(CGF.getContext().getPointerDiffType());
980   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
981 
982   llvm::Value *SrcRTTI =
983       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
984   llvm::Value *DestRTTI =
985       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
986 
987   // Compute the offset hint.
988   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
989   const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
990   llvm::Value *OffsetHint = llvm::ConstantInt::get(
991       PtrDiffLTy,
992       computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
993 
994   // Emit the call to __dynamic_cast.
995   Value = CGF.EmitCastToVoidPtr(Value);
996 
997   llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
998   Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
999   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1000 
1001   /// C++ [expr.dynamic.cast]p9:
1002   ///   A failed cast to reference type throws std::bad_cast
1003   if (DestTy->isReferenceType()) {
1004     llvm::BasicBlock *BadCastBlock =
1005         CGF.createBasicBlock("dynamic_cast.bad_cast");
1006 
1007     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1008     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1009 
1010     CGF.EmitBlock(BadCastBlock);
1011     EmitBadCastCall(CGF);
1012   }
1013 
1014   return Value;
1015 }
1016 
1017 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1018                                                   llvm::Value *Value,
1019                                                   QualType SrcRecordTy,
1020                                                   QualType DestTy) {
1021   llvm::Type *PtrDiffLTy =
1022       CGF.ConvertType(CGF.getContext().getPointerDiffType());
1023   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1024 
1025   // Get the vtable pointer.
1026   llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1027 
1028   // Get the offset-to-top from the vtable.
1029   llvm::Value *OffsetToTop =
1030       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1031   OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1032 
1033   // Finally, add the offset to the pointer.
1034   Value = CGF.EmitCastToVoidPtr(Value);
1035   Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1036 
1037   return CGF.Builder.CreateBitCast(Value, DestLTy);
1038 }
1039 
1040 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1041   llvm::Value *Fn = getBadCastFn(CGF);
1042   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1043   CGF.Builder.CreateUnreachable();
1044   return true;
1045 }
1046 
1047 llvm::Value *
1048 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1049                                          llvm::Value *This,
1050                                          const CXXRecordDecl *ClassDecl,
1051                                          const CXXRecordDecl *BaseClassDecl) {
1052   llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1053   CharUnits VBaseOffsetOffset =
1054       CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1055                                                                BaseClassDecl);
1056 
1057   llvm::Value *VBaseOffsetPtr =
1058     CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1059                                    "vbase.offset.ptr");
1060   VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1061                                              CGM.PtrDiffTy->getPointerTo());
1062 
1063   llvm::Value *VBaseOffset =
1064     CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1065 
1066   return VBaseOffset;
1067 }
1068 
1069 /// The generic ABI passes 'this', plus a VTT if it's initializing a
1070 /// base subobject.
1071 void
1072 ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
1073                                          CXXCtorType Type, CanQualType &ResTy,
1074                                          SmallVectorImpl<CanQualType> &ArgTys) {
1075   ASTContext &Context = getContext();
1076 
1077   // All parameters are already in place except VTT, which goes after 'this'.
1078   // These are Clang types, so we don't need to worry about sret yet.
1079 
1080   // Check if we need to add a VTT parameter (which has type void **).
1081   if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
1082     ArgTys.insert(ArgTys.begin() + 1,
1083                   Context.getPointerType(Context.VoidPtrTy));
1084 }
1085 
1086 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1087   // Just make sure we're in sync with TargetCXXABI.
1088   assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1089 
1090   // The constructor used for constructing this as a base class;
1091   // ignores virtual bases.
1092   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1093 
1094   // The constructor used for constructing this as a complete class;
1095   // constucts the virtual bases, then calls the base constructor.
1096   if (!D->getParent()->isAbstract()) {
1097     // We don't need to emit the complete ctor if the class is abstract.
1098     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1099   }
1100 }
1101 
1102 /// The generic ABI passes 'this', plus a VTT if it's destroying a
1103 /// base subobject.
1104 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
1105                                              CXXDtorType Type,
1106                                              CanQualType &ResTy,
1107                                 SmallVectorImpl<CanQualType> &ArgTys) {
1108   ASTContext &Context = getContext();
1109 
1110   // 'this' parameter is already there, as well as 'this' return if
1111   // HasThisReturn(GlobalDecl(Dtor, Type)) is true
1112 
1113   // Check if we need to add a VTT parameter (which has type void **).
1114   if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
1115     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
1116 }
1117 
1118 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1119   // The destructor used for destructing this as a base class; ignores
1120   // virtual bases.
1121   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1122 
1123   // The destructor used for destructing this as a most-derived class;
1124   // call the base destructor and then destructs any virtual bases.
1125   CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1126 
1127   // The destructor in a virtual table is always a 'deleting'
1128   // destructor, which calls the complete destructor and then uses the
1129   // appropriate operator delete.
1130   if (D->isVirtual())
1131     CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1132 }
1133 
1134 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1135                                               QualType &ResTy,
1136                                               FunctionArgList &Params) {
1137   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1138   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1139 
1140   // Check if we need a VTT parameter as well.
1141   if (NeedsVTTParameter(CGF.CurGD)) {
1142     ASTContext &Context = getContext();
1143 
1144     // FIXME: avoid the fake decl
1145     QualType T = Context.getPointerType(Context.VoidPtrTy);
1146     ImplicitParamDecl *VTTDecl
1147       = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
1148                                   &Context.Idents.get("vtt"), T);
1149     Params.insert(Params.begin() + 1, VTTDecl);
1150     getStructorImplicitParamDecl(CGF) = VTTDecl;
1151   }
1152 }
1153 
1154 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1155   /// Initialize the 'this' slot.
1156   EmitThisParam(CGF);
1157 
1158   /// Initialize the 'vtt' slot if needed.
1159   if (getStructorImplicitParamDecl(CGF)) {
1160     getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1161         CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1162   }
1163 
1164   /// If this is a function that the ABI specifies returns 'this', initialize
1165   /// the return slot to 'this' at the start of the function.
1166   ///
1167   /// Unlike the setting of return types, this is done within the ABI
1168   /// implementation instead of by clients of CGCXXABI because:
1169   /// 1) getThisValue is currently protected
1170   /// 2) in theory, an ABI could implement 'this' returns some other way;
1171   ///    HasThisReturn only specifies a contract, not the implementation
1172   if (HasThisReturn(CGF.CurGD))
1173     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1174 }
1175 
1176 unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1177     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1178     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1179   if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1180     return 0;
1181 
1182   // Insert the implicit 'vtt' argument as the second argument.
1183   llvm::Value *VTT =
1184       CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1185   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1186   Args.insert(Args.begin() + 1,
1187               CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1188   return 1;  // Added one arg.
1189 }
1190 
1191 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1192                                        const CXXDestructorDecl *DD,
1193                                        CXXDtorType Type, bool ForVirtualBase,
1194                                        bool Delegating, llvm::Value *This) {
1195   GlobalDecl GD(DD, Type);
1196   llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1197   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1198 
1199   llvm::Value *Callee = nullptr;
1200   if (getContext().getLangOpts().AppleKext)
1201     Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1202 
1203   if (!Callee)
1204     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1205 
1206   CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1207                                   VTTTy, nullptr);
1208 }
1209 
1210 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1211                                           const CXXRecordDecl *RD) {
1212   llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1213   if (VTable->hasInitializer())
1214     return;
1215 
1216   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1217   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1218   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1219   llvm::Constant *RTTI =
1220       CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
1221 
1222   // Create and set the initializer.
1223   llvm::Constant *Init = CGVT.CreateVTableInitializer(
1224       RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
1225       VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
1226   VTable->setInitializer(Init);
1227 
1228   // Set the correct linkage.
1229   VTable->setLinkage(Linkage);
1230 
1231   // Set the right visibility.
1232   CGM.setGlobalVisibility(VTable, RD);
1233 
1234   // If this is the magic class __cxxabiv1::__fundamental_type_info,
1235   // we will emit the typeinfo for the fundamental types. This is the
1236   // same behaviour as GCC.
1237   const DeclContext *DC = RD->getDeclContext();
1238   if (RD->getIdentifier() &&
1239       RD->getIdentifier()->isStr("__fundamental_type_info") &&
1240       isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1241       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1242       DC->getParent()->isTranslationUnit())
1243     EmitFundamentalRTTIDescriptors();
1244 }
1245 
1246 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1247     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1248     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1249   bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1250   NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1251 
1252   llvm::Value *VTableAddressPoint;
1253   if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1254     // Get the secondary vpointer index.
1255     uint64_t VirtualPointerIndex =
1256         CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1257 
1258     /// Load the VTT.
1259     llvm::Value *VTT = CGF.LoadCXXVTT();
1260     if (VirtualPointerIndex)
1261       VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1262 
1263     // And load the address point from the VTT.
1264     VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1265   } else {
1266     llvm::Constant *VTable =
1267         CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1268     uint64_t AddressPoint = CGM.getItaniumVTableContext()
1269                                 .getVTableLayout(VTableClass)
1270                                 .getAddressPoint(Base);
1271     VTableAddressPoint =
1272         CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1273   }
1274 
1275   return VTableAddressPoint;
1276 }
1277 
1278 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1279     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1280   llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1281 
1282   // Find the appropriate vtable within the vtable group.
1283   uint64_t AddressPoint = CGM.getItaniumVTableContext()
1284                               .getVTableLayout(VTableClass)
1285                               .getAddressPoint(Base);
1286   llvm::Value *Indices[] = {
1287     llvm::ConstantInt::get(CGM.Int64Ty, 0),
1288     llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1289   };
1290 
1291   return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1292 }
1293 
1294 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1295                                                      CharUnits VPtrOffset) {
1296   assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1297 
1298   llvm::GlobalVariable *&VTable = VTables[RD];
1299   if (VTable)
1300     return VTable;
1301 
1302   // Queue up this v-table for possible deferred emission.
1303   CGM.addDeferredVTable(RD);
1304 
1305   SmallString<256> OutName;
1306   llvm::raw_svector_ostream Out(OutName);
1307   getMangleContext().mangleCXXVTable(RD, Out);
1308   Out.flush();
1309   StringRef Name = OutName.str();
1310 
1311   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1312   llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1313       CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1314 
1315   VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1316       Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1317   VTable->setUnnamedAddr(true);
1318 
1319   if (RD->hasAttr<DLLImportAttr>())
1320     VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1321   else if (RD->hasAttr<DLLExportAttr>())
1322     VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1323 
1324   return VTable;
1325 }
1326 
1327 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1328                                                       GlobalDecl GD,
1329                                                       llvm::Value *This,
1330                                                       llvm::Type *Ty) {
1331   GD = GD.getCanonicalDecl();
1332   Ty = Ty->getPointerTo()->getPointerTo();
1333   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1334 
1335   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1336   llvm::Value *VFuncPtr =
1337       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1338   return CGF.Builder.CreateLoad(VFuncPtr);
1339 }
1340 
1341 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1342                                               const CXXDestructorDecl *Dtor,
1343                                               CXXDtorType DtorType,
1344                                               llvm::Value *This,
1345                                               const CXXMemberCallExpr *CE) {
1346   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1347   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1348 
1349   const CGFunctionInfo *FInfo
1350     = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1351   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1352   llvm::Value *Callee =
1353       getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
1354 
1355   CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1356                                   /*ImplicitParam=*/nullptr, QualType(), CE);
1357 }
1358 
1359 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1360   CodeGenVTables &VTables = CGM.getVTables();
1361   llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1362   VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1363 }
1364 
1365 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1366                                           llvm::Value *Ptr,
1367                                           int64_t NonVirtualAdjustment,
1368                                           int64_t VirtualAdjustment,
1369                                           bool IsReturnAdjustment) {
1370   if (!NonVirtualAdjustment && !VirtualAdjustment)
1371     return Ptr;
1372 
1373   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1374   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1375 
1376   if (NonVirtualAdjustment && !IsReturnAdjustment) {
1377     // Perform the non-virtual adjustment for a base-to-derived cast.
1378     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1379   }
1380 
1381   if (VirtualAdjustment) {
1382     llvm::Type *PtrDiffTy =
1383         CGF.ConvertType(CGF.getContext().getPointerDiffType());
1384 
1385     // Perform the virtual adjustment.
1386     llvm::Value *VTablePtrPtr =
1387         CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1388 
1389     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1390 
1391     llvm::Value *OffsetPtr =
1392         CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1393 
1394     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1395 
1396     // Load the adjustment offset from the vtable.
1397     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1398 
1399     // Adjust our pointer.
1400     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1401   }
1402 
1403   if (NonVirtualAdjustment && IsReturnAdjustment) {
1404     // Perform the non-virtual adjustment for a derived-to-base cast.
1405     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1406   }
1407 
1408   // Cast back to the original type.
1409   return CGF.Builder.CreateBitCast(V, Ptr->getType());
1410 }
1411 
1412 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1413                                                   llvm::Value *This,
1414                                                   const ThisAdjustment &TA) {
1415   return performTypeAdjustment(CGF, This, TA.NonVirtual,
1416                                TA.Virtual.Itanium.VCallOffsetOffset,
1417                                /*IsReturnAdjustment=*/false);
1418 }
1419 
1420 llvm::Value *
1421 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1422                                        const ReturnAdjustment &RA) {
1423   return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1424                                RA.Virtual.Itanium.VBaseOffsetOffset,
1425                                /*IsReturnAdjustment=*/true);
1426 }
1427 
1428 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1429                                     RValue RV, QualType ResultType) {
1430   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1431     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1432 
1433   // Destructor thunks in the ARM ABI have indeterminate results.
1434   llvm::Type *T =
1435     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1436   RValue Undef = RValue::get(llvm::UndefValue::get(T));
1437   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1438 }
1439 
1440 /************************** Array allocation cookies **************************/
1441 
1442 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1443   // The array cookie is a size_t; pad that up to the element alignment.
1444   // The cookie is actually right-justified in that space.
1445   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1446                   CGM.getContext().getTypeAlignInChars(elementType));
1447 }
1448 
1449 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1450                                                   llvm::Value *NewPtr,
1451                                                   llvm::Value *NumElements,
1452                                                   const CXXNewExpr *expr,
1453                                                   QualType ElementType) {
1454   assert(requiresArrayCookie(expr));
1455 
1456   unsigned AS = NewPtr->getType()->getPointerAddressSpace();
1457 
1458   ASTContext &Ctx = getContext();
1459   QualType SizeTy = Ctx.getSizeType();
1460   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1461 
1462   // The size of the cookie.
1463   CharUnits CookieSize =
1464     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1465   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1466 
1467   // Compute an offset to the cookie.
1468   llvm::Value *CookiePtr = NewPtr;
1469   CharUnits CookieOffset = CookieSize - SizeSize;
1470   if (!CookieOffset.isZero())
1471     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1472                                                  CookieOffset.getQuantity());
1473 
1474   // Write the number of elements into the appropriate slot.
1475   llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1476   llvm::Value *NumElementsPtr =
1477       CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1478   llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1479   if (CGM.getLangOpts().Sanitize.Address &&
1480       expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
1481     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1482     llvm::FunctionType *FTy =
1483         llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1484     llvm::Constant *F =
1485         CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1486     CGF.Builder.CreateCall(F, NumElementsPtr);
1487   }
1488 
1489   // Finally, compute a pointer to the actual data buffer by skipping
1490   // over the cookie completely.
1491   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1492                                                 CookieSize.getQuantity());
1493 }
1494 
1495 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1496                                                 llvm::Value *allocPtr,
1497                                                 CharUnits cookieSize) {
1498   // The element size is right-justified in the cookie.
1499   llvm::Value *numElementsPtr = allocPtr;
1500   CharUnits numElementsOffset =
1501     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1502   if (!numElementsOffset.isZero())
1503     numElementsPtr =
1504       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1505                                              numElementsOffset.getQuantity());
1506 
1507   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1508   numElementsPtr =
1509     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1510   llvm::Instruction *LI = CGF.Builder.CreateLoad(numElementsPtr);
1511   if (CGM.getLangOpts().Sanitize.Address)
1512     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(LI);
1513   return LI;
1514 }
1515 
1516 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1517   // ARM says that the cookie is always:
1518   //   struct array_cookie {
1519   //     std::size_t element_size; // element_size != 0
1520   //     std::size_t element_count;
1521   //   };
1522   // But the base ABI doesn't give anything an alignment greater than
1523   // 8, so we can dismiss this as typical ABI-author blindness to
1524   // actual language complexity and round up to the element alignment.
1525   return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1526                   CGM.getContext().getTypeAlignInChars(elementType));
1527 }
1528 
1529 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1530                                               llvm::Value *newPtr,
1531                                               llvm::Value *numElements,
1532                                               const CXXNewExpr *expr,
1533                                               QualType elementType) {
1534   assert(requiresArrayCookie(expr));
1535 
1536   // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1537   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1538 
1539   // The cookie is always at the start of the buffer.
1540   llvm::Value *cookie = newPtr;
1541 
1542   // The first element is the element size.
1543   cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1544   llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1545                  getContext().getTypeSizeInChars(elementType).getQuantity());
1546   CGF.Builder.CreateStore(elementSize, cookie);
1547 
1548   // The second element is the element count.
1549   cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1550   CGF.Builder.CreateStore(numElements, cookie);
1551 
1552   // Finally, compute a pointer to the actual data buffer by skipping
1553   // over the cookie completely.
1554   CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1555   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1556                                                 cookieSize.getQuantity());
1557 }
1558 
1559 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1560                                             llvm::Value *allocPtr,
1561                                             CharUnits cookieSize) {
1562   // The number of elements is at offset sizeof(size_t) relative to
1563   // the allocated pointer.
1564   llvm::Value *numElementsPtr
1565     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
1566 
1567   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1568   numElementsPtr =
1569     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1570   return CGF.Builder.CreateLoad(numElementsPtr);
1571 }
1572 
1573 /*********************** Static local initialization **************************/
1574 
1575 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1576                                          llvm::PointerType *GuardPtrTy) {
1577   // int __cxa_guard_acquire(__guard *guard_object);
1578   llvm::FunctionType *FTy =
1579     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1580                             GuardPtrTy, /*isVarArg=*/false);
1581   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1582                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1583                                               llvm::AttributeSet::FunctionIndex,
1584                                                  llvm::Attribute::NoUnwind));
1585 }
1586 
1587 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1588                                          llvm::PointerType *GuardPtrTy) {
1589   // void __cxa_guard_release(__guard *guard_object);
1590   llvm::FunctionType *FTy =
1591     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1592   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1593                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1594                                               llvm::AttributeSet::FunctionIndex,
1595                                                  llvm::Attribute::NoUnwind));
1596 }
1597 
1598 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1599                                        llvm::PointerType *GuardPtrTy) {
1600   // void __cxa_guard_abort(__guard *guard_object);
1601   llvm::FunctionType *FTy =
1602     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1603   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1604                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1605                                               llvm::AttributeSet::FunctionIndex,
1606                                                  llvm::Attribute::NoUnwind));
1607 }
1608 
1609 namespace {
1610   struct CallGuardAbort : EHScopeStack::Cleanup {
1611     llvm::GlobalVariable *Guard;
1612     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1613 
1614     void Emit(CodeGenFunction &CGF, Flags flags) override {
1615       CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1616                                   Guard);
1617     }
1618   };
1619 }
1620 
1621 /// The ARM code here follows the Itanium code closely enough that we
1622 /// just special-case it at particular places.
1623 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1624                                     const VarDecl &D,
1625                                     llvm::GlobalVariable *var,
1626                                     bool shouldPerformInit) {
1627   CGBuilderTy &Builder = CGF.Builder;
1628 
1629   // We only need to use thread-safe statics for local non-TLS variables;
1630   // global initialization is always single-threaded.
1631   bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1632                     D.isLocalVarDecl() && !D.getTLSKind();
1633 
1634   // If we have a global variable with internal linkage and thread-safe statics
1635   // are disabled, we can just let the guard variable be of type i8.
1636   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1637 
1638   llvm::IntegerType *guardTy;
1639   if (useInt8GuardVariable) {
1640     guardTy = CGF.Int8Ty;
1641   } else {
1642     // Guard variables are 64 bits in the generic ABI and size width on ARM
1643     // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1644     guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
1645   }
1646   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
1647 
1648   // Create the guard variable if we don't already have it (as we
1649   // might if we're double-emitting this function body).
1650   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1651   if (!guard) {
1652     // Mangle the name for the guard.
1653     SmallString<256> guardName;
1654     {
1655       llvm::raw_svector_ostream out(guardName);
1656       getMangleContext().mangleStaticGuardVariable(&D, out);
1657       out.flush();
1658     }
1659 
1660     // Create the guard variable with a zero-initializer.
1661     // Just absorb linkage and visibility from the guarded variable.
1662     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1663                                      false, var->getLinkage(),
1664                                      llvm::ConstantInt::get(guardTy, 0),
1665                                      guardName.str());
1666     guard->setVisibility(var->getVisibility());
1667     // If the variable is thread-local, so is its guard variable.
1668     guard->setThreadLocalMode(var->getThreadLocalMode());
1669 
1670     CGM.setStaticLocalDeclGuardAddress(&D, guard);
1671   }
1672 
1673   // Test whether the variable has completed initialization.
1674   //
1675   // Itanium C++ ABI 3.3.2:
1676   //   The following is pseudo-code showing how these functions can be used:
1677   //     if (obj_guard.first_byte == 0) {
1678   //       if ( __cxa_guard_acquire (&obj_guard) ) {
1679   //         try {
1680   //           ... initialize the object ...;
1681   //         } catch (...) {
1682   //            __cxa_guard_abort (&obj_guard);
1683   //            throw;
1684   //         }
1685   //         ... queue object destructor with __cxa_atexit() ...;
1686   //         __cxa_guard_release (&obj_guard);
1687   //       }
1688   //     }
1689 
1690   // Load the first byte of the guard variable.
1691   llvm::LoadInst *LI =
1692       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
1693   LI->setAlignment(1);
1694 
1695   // Itanium ABI:
1696   //   An implementation supporting thread-safety on multiprocessor
1697   //   systems must also guarantee that references to the initialized
1698   //   object do not occur before the load of the initialization flag.
1699   //
1700   // In LLVM, we do this by marking the load Acquire.
1701   if (threadsafe)
1702     LI->setAtomic(llvm::Acquire);
1703 
1704   // For ARM, we should only check the first bit, rather than the entire byte:
1705   //
1706   // ARM C++ ABI 3.2.3.1:
1707   //   To support the potential use of initialization guard variables
1708   //   as semaphores that are the target of ARM SWP and LDREX/STREX
1709   //   synchronizing instructions we define a static initialization
1710   //   guard variable to be a 4-byte aligned, 4-byte word with the
1711   //   following inline access protocol.
1712   //     #define INITIALIZED 1
1713   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
1714   //       if (__cxa_guard_acquire(&obj_guard))
1715   //         ...
1716   //     }
1717   //
1718   // and similarly for ARM64:
1719   //
1720   // ARM64 C++ ABI 3.2.2:
1721   //   This ABI instead only specifies the value bit 0 of the static guard
1722   //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
1723   //   variable is not initialized and 1 when it is.
1724   llvm::Value *V =
1725       (UseARMGuardVarABI && !useInt8GuardVariable)
1726           ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1727           : LI;
1728   llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1729 
1730   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1731   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1732 
1733   // Check if the first byte of the guard variable is zero.
1734   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
1735 
1736   CGF.EmitBlock(InitCheckBlock);
1737 
1738   // Variables used when coping with thread-safe statics and exceptions.
1739   if (threadsafe) {
1740     // Call __cxa_guard_acquire.
1741     llvm::Value *V
1742       = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
1743 
1744     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1745 
1746     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1747                          InitBlock, EndBlock);
1748 
1749     // Call __cxa_guard_abort along the exceptional edge.
1750     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
1751 
1752     CGF.EmitBlock(InitBlock);
1753   }
1754 
1755   // Emit the initializer and add a global destructor if appropriate.
1756   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
1757 
1758   if (threadsafe) {
1759     // Pop the guard-abort cleanup if we pushed one.
1760     CGF.PopCleanupBlock();
1761 
1762     // Call __cxa_guard_release.  This cannot throw.
1763     CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
1764   } else {
1765     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
1766   }
1767 
1768   CGF.EmitBlock(EndBlock);
1769 }
1770 
1771 /// Register a global destructor using __cxa_atexit.
1772 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1773                                         llvm::Constant *dtor,
1774                                         llvm::Constant *addr,
1775                                         bool TLS) {
1776   const char *Name = "__cxa_atexit";
1777   if (TLS) {
1778     const llvm::Triple &T = CGF.getTarget().getTriple();
1779     Name = T.isMacOSX() ?  "_tlv_atexit" : "__cxa_thread_atexit";
1780   }
1781 
1782   // We're assuming that the destructor function is something we can
1783   // reasonably call with the default CC.  Go ahead and cast it to the
1784   // right prototype.
1785   llvm::Type *dtorTy =
1786     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1787 
1788   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1789   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1790   llvm::FunctionType *atexitTy =
1791     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1792 
1793   // Fetch the actual function.
1794   llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
1795   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1796     fn->setDoesNotThrow();
1797 
1798   // Create a variable that binds the atexit to this shared object.
1799   llvm::Constant *handle =
1800     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1801 
1802   llvm::Value *args[] = {
1803     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1804     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1805     handle
1806   };
1807   CGF.EmitNounwindRuntimeCall(atexit, args);
1808 }
1809 
1810 /// Register a global destructor as best as we know how.
1811 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1812                                        const VarDecl &D,
1813                                        llvm::Constant *dtor,
1814                                        llvm::Constant *addr) {
1815   // Use __cxa_atexit if available.
1816   if (CGM.getCodeGenOpts().CXAAtExit)
1817     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1818 
1819   if (D.getTLSKind())
1820     CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
1821 
1822   // In Apple kexts, we want to add a global destructor entry.
1823   // FIXME: shouldn't this be guarded by some variable?
1824   if (CGM.getLangOpts().AppleKext) {
1825     // Generate a global destructor entry.
1826     return CGM.AddCXXDtorEntry(dtor, addr);
1827   }
1828 
1829   CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
1830 }
1831 
1832 static bool isThreadWrapperReplaceable(const VarDecl *VD,
1833                                        CodeGen::CodeGenModule &CGM) {
1834   assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1835   // OS X prefers to have references to thread local variables to go through
1836   // the thread wrapper instead of directly referencing the backing variable.
1837   return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1838          CGM.getTarget().getTriple().isMacOSX();
1839 }
1840 
1841 /// Get the appropriate linkage for the wrapper function. This is essentially
1842 /// the weak form of the variable's linkage; every translation unit which needs
1843 /// the wrapper emits a copy, and we want the linker to merge them.
1844 static llvm::GlobalValue::LinkageTypes
1845 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1846   llvm::GlobalValue::LinkageTypes VarLinkage =
1847       CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1848 
1849   // For internal linkage variables, we don't need an external or weak wrapper.
1850   if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1851     return VarLinkage;
1852 
1853   // If the thread wrapper is replaceable, give it appropriate linkage.
1854   if (isThreadWrapperReplaceable(VD, CGM)) {
1855     if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1856         llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1857       return llvm::GlobalVariable::WeakAnyLinkage;
1858     return VarLinkage;
1859   }
1860   return llvm::GlobalValue::WeakODRLinkage;
1861 }
1862 
1863 llvm::Function *
1864 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1865                                              llvm::GlobalVariable *Var) {
1866   // Mangle the name for the thread_local wrapper function.
1867   SmallString<256> WrapperName;
1868   {
1869     llvm::raw_svector_ostream Out(WrapperName);
1870     getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1871     Out.flush();
1872   }
1873 
1874   if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1875     return cast<llvm::Function>(V);
1876 
1877   llvm::Type *RetTy = Var->getType();
1878   if (VD->getType()->isReferenceType())
1879     RetTy = RetTy->getPointerElementType();
1880 
1881   llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1882   llvm::Function *Wrapper =
1883       llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1884                              WrapperName.str(), &CGM.getModule());
1885   // Always resolve references to the wrapper at link time.
1886   if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
1887     Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1888   return Wrapper;
1889 }
1890 
1891 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1892     ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1893     llvm::Function *InitFunc) {
1894   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1895     const VarDecl *VD = Decls[I].first;
1896     llvm::GlobalVariable *Var = Decls[I].second;
1897 
1898     // Some targets require that all access to thread local variables go through
1899     // the thread wrapper.  This means that we cannot attempt to create a thread
1900     // wrapper or a thread helper.
1901     if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1902       continue;
1903 
1904     // Mangle the name for the thread_local initialization function.
1905     SmallString<256> InitFnName;
1906     {
1907       llvm::raw_svector_ostream Out(InitFnName);
1908       getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1909       Out.flush();
1910     }
1911 
1912     // If we have a definition for the variable, emit the initialization
1913     // function as an alias to the global Init function (if any). Otherwise,
1914     // produce a declaration of the initialization function.
1915     llvm::GlobalValue *Init = nullptr;
1916     bool InitIsInitFunc = false;
1917     if (VD->hasDefinition()) {
1918       InitIsInitFunc = true;
1919       if (InitFunc)
1920         Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1921                                          InitFunc);
1922     } else {
1923       // Emit a weak global function referring to the initialization function.
1924       // This function will not exist if the TU defining the thread_local
1925       // variable in question does not need any dynamic initialization for
1926       // its thread_local variables.
1927       llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1928       Init = llvm::Function::Create(
1929           FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1930           &CGM.getModule());
1931     }
1932 
1933     if (Init)
1934       Init->setVisibility(Var->getVisibility());
1935 
1936     llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1937     llvm::LLVMContext &Context = CGM.getModule().getContext();
1938     llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1939     CGBuilderTy Builder(Entry);
1940     if (InitIsInitFunc) {
1941       if (Init)
1942         Builder.CreateCall(Init);
1943     } else {
1944       // Don't know whether we have an init function. Call it if it exists.
1945       llvm::Value *Have = Builder.CreateIsNotNull(Init);
1946       llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1947       llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1948       Builder.CreateCondBr(Have, InitBB, ExitBB);
1949 
1950       Builder.SetInsertPoint(InitBB);
1951       Builder.CreateCall(Init);
1952       Builder.CreateBr(ExitBB);
1953 
1954       Builder.SetInsertPoint(ExitBB);
1955     }
1956 
1957     // For a reference, the result of the wrapper function is a pointer to
1958     // the referenced object.
1959     llvm::Value *Val = Var;
1960     if (VD->getType()->isReferenceType()) {
1961       llvm::LoadInst *LI = Builder.CreateLoad(Val);
1962       LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1963       Val = LI;
1964     }
1965 
1966     Builder.CreateRet(Val);
1967   }
1968 }
1969 
1970 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1971                                                    const VarDecl *VD,
1972                                                    QualType LValType) {
1973   QualType T = VD->getType();
1974   llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1975   llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1976   llvm::Function *Wrapper =
1977       getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1978 
1979   Val = CGF.Builder.CreateCall(Wrapper);
1980 
1981   LValue LV;
1982   if (VD->getType()->isReferenceType())
1983     LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
1984   else
1985     LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
1986   // FIXME: need setObjCGCLValueClass?
1987   return LV;
1988 }
1989 
1990 /// Return whether the given global decl needs a VTT parameter, which it does
1991 /// if it's a base constructor or destructor with virtual bases.
1992 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1993   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1994 
1995   // We don't have any virtual bases, just return early.
1996   if (!MD->getParent()->getNumVBases())
1997     return false;
1998 
1999   // Check if we have a base constructor.
2000   if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2001     return true;
2002 
2003   // Check if we have a base destructor.
2004   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2005     return true;
2006 
2007   return false;
2008 }
2009 
2010 namespace {
2011 class ItaniumRTTIBuilder {
2012   CodeGenModule &CGM;  // Per-module state.
2013   llvm::LLVMContext &VMContext;
2014   const ItaniumCXXABI &CXXABI;  // Per-module state.
2015 
2016   /// Fields - The fields of the RTTI descriptor currently being built.
2017   SmallVector<llvm::Constant *, 16> Fields;
2018 
2019   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2020   llvm::GlobalVariable *
2021   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2022 
2023   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2024   /// descriptor of the given type.
2025   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2026 
2027   /// BuildVTablePointer - Build the vtable pointer for the given type.
2028   void BuildVTablePointer(const Type *Ty);
2029 
2030   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2031   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2032   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2033 
2034   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2035   /// classes with bases that do not satisfy the abi::__si_class_type_info
2036   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2037   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2038 
2039   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2040   /// for pointer types.
2041   void BuildPointerTypeInfo(QualType PointeeTy);
2042 
2043   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2044   /// type_info for an object type.
2045   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2046 
2047   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2048   /// struct, used for member pointer types.
2049   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2050 
2051 public:
2052   ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2053       : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2054 
2055   // Pointer type info flags.
2056   enum {
2057     /// PTI_Const - Type has const qualifier.
2058     PTI_Const = 0x1,
2059 
2060     /// PTI_Volatile - Type has volatile qualifier.
2061     PTI_Volatile = 0x2,
2062 
2063     /// PTI_Restrict - Type has restrict qualifier.
2064     PTI_Restrict = 0x4,
2065 
2066     /// PTI_Incomplete - Type is incomplete.
2067     PTI_Incomplete = 0x8,
2068 
2069     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2070     /// (in pointer to member).
2071     PTI_ContainingClassIncomplete = 0x10
2072   };
2073 
2074   // VMI type info flags.
2075   enum {
2076     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2077     VMI_NonDiamondRepeat = 0x1,
2078 
2079     /// VMI_DiamondShaped - Class is diamond shaped.
2080     VMI_DiamondShaped = 0x2
2081   };
2082 
2083   // Base class type info flags.
2084   enum {
2085     /// BCTI_Virtual - Base class is virtual.
2086     BCTI_Virtual = 0x1,
2087 
2088     /// BCTI_Public - Base class is public.
2089     BCTI_Public = 0x2
2090   };
2091 
2092   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2093   ///
2094   /// \param Force - true to force the creation of this RTTI value
2095   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2096 };
2097 }
2098 
2099 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2100     QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2101   SmallString<256> OutName;
2102   llvm::raw_svector_ostream Out(OutName);
2103   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2104   Out.flush();
2105   StringRef Name = OutName.str();
2106 
2107   // We know that the mangled name of the type starts at index 4 of the
2108   // mangled name of the typename, so we can just index into it in order to
2109   // get the mangled name of the type.
2110   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2111                                                             Name.substr(4));
2112 
2113   llvm::GlobalVariable *GV =
2114     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2115 
2116   GV->setInitializer(Init);
2117 
2118   return GV;
2119 }
2120 
2121 llvm::Constant *
2122 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2123   // Mangle the RTTI name.
2124   SmallString<256> OutName;
2125   llvm::raw_svector_ostream Out(OutName);
2126   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2127   Out.flush();
2128   StringRef Name = OutName.str();
2129 
2130   // Look for an existing global.
2131   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2132 
2133   if (!GV) {
2134     // Create a new global variable.
2135     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2136                                   /*Constant=*/true,
2137                                   llvm::GlobalValue::ExternalLinkage, nullptr,
2138                                   Name);
2139   }
2140 
2141   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2142 }
2143 
2144 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2145 /// info for that type is defined in the standard library.
2146 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2147   // Itanium C++ ABI 2.9.2:
2148   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
2149   //   the run-time support library. Specifically, the run-time support
2150   //   library should contain type_info objects for the types X, X* and
2151   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2152   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
2153   //   long, unsigned long, long long, unsigned long long, float, double,
2154   //   long double, char16_t, char32_t, and the IEEE 754r decimal and
2155   //   half-precision floating point types.
2156   switch (Ty->getKind()) {
2157     case BuiltinType::Void:
2158     case BuiltinType::NullPtr:
2159     case BuiltinType::Bool:
2160     case BuiltinType::WChar_S:
2161     case BuiltinType::WChar_U:
2162     case BuiltinType::Char_U:
2163     case BuiltinType::Char_S:
2164     case BuiltinType::UChar:
2165     case BuiltinType::SChar:
2166     case BuiltinType::Short:
2167     case BuiltinType::UShort:
2168     case BuiltinType::Int:
2169     case BuiltinType::UInt:
2170     case BuiltinType::Long:
2171     case BuiltinType::ULong:
2172     case BuiltinType::LongLong:
2173     case BuiltinType::ULongLong:
2174     case BuiltinType::Half:
2175     case BuiltinType::Float:
2176     case BuiltinType::Double:
2177     case BuiltinType::LongDouble:
2178     case BuiltinType::Char16:
2179     case BuiltinType::Char32:
2180     case BuiltinType::Int128:
2181     case BuiltinType::UInt128:
2182     case BuiltinType::OCLImage1d:
2183     case BuiltinType::OCLImage1dArray:
2184     case BuiltinType::OCLImage1dBuffer:
2185     case BuiltinType::OCLImage2d:
2186     case BuiltinType::OCLImage2dArray:
2187     case BuiltinType::OCLImage3d:
2188     case BuiltinType::OCLSampler:
2189     case BuiltinType::OCLEvent:
2190       return true;
2191 
2192     case BuiltinType::Dependent:
2193 #define BUILTIN_TYPE(Id, SingletonId)
2194 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2195     case BuiltinType::Id:
2196 #include "clang/AST/BuiltinTypes.def"
2197       llvm_unreachable("asking for RRTI for a placeholder type!");
2198 
2199     case BuiltinType::ObjCId:
2200     case BuiltinType::ObjCClass:
2201     case BuiltinType::ObjCSel:
2202       llvm_unreachable("FIXME: Objective-C types are unsupported!");
2203   }
2204 
2205   llvm_unreachable("Invalid BuiltinType Kind!");
2206 }
2207 
2208 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2209   QualType PointeeTy = PointerTy->getPointeeType();
2210   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2211   if (!BuiltinTy)
2212     return false;
2213 
2214   // Check the qualifiers.
2215   Qualifiers Quals = PointeeTy.getQualifiers();
2216   Quals.removeConst();
2217 
2218   if (!Quals.empty())
2219     return false;
2220 
2221   return TypeInfoIsInStandardLibrary(BuiltinTy);
2222 }
2223 
2224 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
2225 /// information for the given type exists in the standard library.
2226 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2227   // Type info for builtin types is defined in the standard library.
2228   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2229     return TypeInfoIsInStandardLibrary(BuiltinTy);
2230 
2231   // Type info for some pointer types to builtin types is defined in the
2232   // standard library.
2233   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2234     return TypeInfoIsInStandardLibrary(PointerTy);
2235 
2236   return false;
2237 }
2238 
2239 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2240 /// the given type exists somewhere else, and that we should not emit the type
2241 /// information in this translation unit.  Assumes that it is not a
2242 /// standard-library type.
2243 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2244                                             QualType Ty) {
2245   ASTContext &Context = CGM.getContext();
2246 
2247   // If RTTI is disabled, assume it might be disabled in the
2248   // translation unit that defines any potential key function, too.
2249   if (!Context.getLangOpts().RTTI) return false;
2250 
2251   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2252     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2253     if (!RD->hasDefinition())
2254       return false;
2255 
2256     if (!RD->isDynamicClass())
2257       return false;
2258 
2259     // FIXME: this may need to be reconsidered if the key function
2260     // changes.
2261     return CGM.getVTables().isVTableExternal(RD);
2262   }
2263 
2264   return false;
2265 }
2266 
2267 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
2268 static bool IsIncompleteClassType(const RecordType *RecordTy) {
2269   return !RecordTy->getDecl()->isCompleteDefinition();
2270 }
2271 
2272 /// ContainsIncompleteClassType - Returns whether the given type contains an
2273 /// incomplete class type. This is true if
2274 ///
2275 ///   * The given type is an incomplete class type.
2276 ///   * The given type is a pointer type whose pointee type contains an
2277 ///     incomplete class type.
2278 ///   * The given type is a member pointer type whose class is an incomplete
2279 ///     class type.
2280 ///   * The given type is a member pointer type whoise pointee type contains an
2281 ///     incomplete class type.
2282 /// is an indirect or direct pointer to an incomplete class type.
2283 static bool ContainsIncompleteClassType(QualType Ty) {
2284   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2285     if (IsIncompleteClassType(RecordTy))
2286       return true;
2287   }
2288 
2289   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2290     return ContainsIncompleteClassType(PointerTy->getPointeeType());
2291 
2292   if (const MemberPointerType *MemberPointerTy =
2293       dyn_cast<MemberPointerType>(Ty)) {
2294     // Check if the class type is incomplete.
2295     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2296     if (IsIncompleteClassType(ClassType))
2297       return true;
2298 
2299     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2300   }
2301 
2302   return false;
2303 }
2304 
2305 // CanUseSingleInheritance - Return whether the given record decl has a "single,
2306 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
2307 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2308 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2309   // Check the number of bases.
2310   if (RD->getNumBases() != 1)
2311     return false;
2312 
2313   // Get the base.
2314   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2315 
2316   // Check that the base is not virtual.
2317   if (Base->isVirtual())
2318     return false;
2319 
2320   // Check that the base is public.
2321   if (Base->getAccessSpecifier() != AS_public)
2322     return false;
2323 
2324   // Check that the class is dynamic iff the base is.
2325   const CXXRecordDecl *BaseDecl =
2326     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2327   if (!BaseDecl->isEmpty() &&
2328       BaseDecl->isDynamicClass() != RD->isDynamicClass())
2329     return false;
2330 
2331   return true;
2332 }
2333 
2334 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2335   // abi::__class_type_info.
2336   static const char * const ClassTypeInfo =
2337     "_ZTVN10__cxxabiv117__class_type_infoE";
2338   // abi::__si_class_type_info.
2339   static const char * const SIClassTypeInfo =
2340     "_ZTVN10__cxxabiv120__si_class_type_infoE";
2341   // abi::__vmi_class_type_info.
2342   static const char * const VMIClassTypeInfo =
2343     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2344 
2345   const char *VTableName = nullptr;
2346 
2347   switch (Ty->getTypeClass()) {
2348 #define TYPE(Class, Base)
2349 #define ABSTRACT_TYPE(Class, Base)
2350 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2351 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2352 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2353 #include "clang/AST/TypeNodes.def"
2354     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2355 
2356   case Type::LValueReference:
2357   case Type::RValueReference:
2358     llvm_unreachable("References shouldn't get here");
2359 
2360   case Type::Auto:
2361     llvm_unreachable("Undeduced auto type shouldn't get here");
2362 
2363   case Type::Builtin:
2364   // GCC treats vector and complex types as fundamental types.
2365   case Type::Vector:
2366   case Type::ExtVector:
2367   case Type::Complex:
2368   case Type::Atomic:
2369   // FIXME: GCC treats block pointers as fundamental types?!
2370   case Type::BlockPointer:
2371     // abi::__fundamental_type_info.
2372     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2373     break;
2374 
2375   case Type::ConstantArray:
2376   case Type::IncompleteArray:
2377   case Type::VariableArray:
2378     // abi::__array_type_info.
2379     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2380     break;
2381 
2382   case Type::FunctionNoProto:
2383   case Type::FunctionProto:
2384     // abi::__function_type_info.
2385     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2386     break;
2387 
2388   case Type::Enum:
2389     // abi::__enum_type_info.
2390     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2391     break;
2392 
2393   case Type::Record: {
2394     const CXXRecordDecl *RD =
2395       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2396 
2397     if (!RD->hasDefinition() || !RD->getNumBases()) {
2398       VTableName = ClassTypeInfo;
2399     } else if (CanUseSingleInheritance(RD)) {
2400       VTableName = SIClassTypeInfo;
2401     } else {
2402       VTableName = VMIClassTypeInfo;
2403     }
2404 
2405     break;
2406   }
2407 
2408   case Type::ObjCObject:
2409     // Ignore protocol qualifiers.
2410     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2411 
2412     // Handle id and Class.
2413     if (isa<BuiltinType>(Ty)) {
2414       VTableName = ClassTypeInfo;
2415       break;
2416     }
2417 
2418     assert(isa<ObjCInterfaceType>(Ty));
2419     // Fall through.
2420 
2421   case Type::ObjCInterface:
2422     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2423       VTableName = SIClassTypeInfo;
2424     } else {
2425       VTableName = ClassTypeInfo;
2426     }
2427     break;
2428 
2429   case Type::ObjCObjectPointer:
2430   case Type::Pointer:
2431     // abi::__pointer_type_info.
2432     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2433     break;
2434 
2435   case Type::MemberPointer:
2436     // abi::__pointer_to_member_type_info.
2437     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2438     break;
2439   }
2440 
2441   llvm::Constant *VTable =
2442     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2443 
2444   llvm::Type *PtrDiffTy =
2445     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2446 
2447   // The vtable address point is 2.
2448   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2449   VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2450   VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2451 
2452   Fields.push_back(VTable);
2453 }
2454 
2455 /// \brief Return the linkage that the type info and type info name constants
2456 /// should have for the given type.
2457 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2458                                                              QualType Ty) {
2459   // Itanium C++ ABI 2.9.5p7:
2460   //   In addition, it and all of the intermediate abi::__pointer_type_info
2461   //   structs in the chain down to the abi::__class_type_info for the
2462   //   incomplete class type must be prevented from resolving to the
2463   //   corresponding type_info structs for the complete class type, possibly
2464   //   by making them local static objects. Finally, a dummy class RTTI is
2465   //   generated for the incomplete type that will not resolve to the final
2466   //   complete class RTTI (because the latter need not exist), possibly by
2467   //   making it a local static object.
2468   if (ContainsIncompleteClassType(Ty))
2469     return llvm::GlobalValue::InternalLinkage;
2470 
2471   switch (Ty->getLinkage()) {
2472   case NoLinkage:
2473   case InternalLinkage:
2474   case UniqueExternalLinkage:
2475     return llvm::GlobalValue::InternalLinkage;
2476 
2477   case VisibleNoLinkage:
2478   case ExternalLinkage:
2479     if (!CGM.getLangOpts().RTTI) {
2480       // RTTI is not enabled, which means that this type info struct is going
2481       // to be used for exception handling. Give it linkonce_odr linkage.
2482       return llvm::GlobalValue::LinkOnceODRLinkage;
2483     }
2484 
2485     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2486       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2487       if (RD->hasAttr<WeakAttr>())
2488         return llvm::GlobalValue::WeakODRLinkage;
2489       if (RD->isDynamicClass())
2490         return CGM.getVTableLinkage(RD);
2491     }
2492 
2493     return llvm::GlobalValue::LinkOnceODRLinkage;
2494   }
2495 
2496   llvm_unreachable("Invalid linkage!");
2497 }
2498 
2499 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2500   // We want to operate on the canonical type.
2501   Ty = CGM.getContext().getCanonicalType(Ty);
2502 
2503   // Check if we've already emitted an RTTI descriptor for this type.
2504   SmallString<256> OutName;
2505   llvm::raw_svector_ostream Out(OutName);
2506   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2507   Out.flush();
2508   StringRef Name = OutName.str();
2509 
2510   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2511   if (OldGV && !OldGV->isDeclaration()) {
2512     assert(!OldGV->hasAvailableExternallyLinkage() &&
2513            "available_externally typeinfos not yet implemented");
2514 
2515     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2516   }
2517 
2518   // Check if there is already an external RTTI descriptor for this type.
2519   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2520   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2521     return GetAddrOfExternalRTTIDescriptor(Ty);
2522 
2523   // Emit the standard library with external linkage.
2524   llvm::GlobalVariable::LinkageTypes Linkage;
2525   if (IsStdLib)
2526     Linkage = llvm::GlobalValue::ExternalLinkage;
2527   else
2528     Linkage = getTypeInfoLinkage(CGM, Ty);
2529 
2530   // Add the vtable pointer.
2531   BuildVTablePointer(cast<Type>(Ty));
2532 
2533   // And the name.
2534   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2535   llvm::Constant *TypeNameField;
2536 
2537   // If we're supposed to demote the visibility, be sure to set a flag
2538   // to use a string comparison for type_info comparisons.
2539   ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2540       CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2541   if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2542     // The flag is the sign bit, which on ARM64 is defined to be clear
2543     // for global pointers.  This is very ARM64-specific.
2544     TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2545     llvm::Constant *flag =
2546         llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2547     TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2548     TypeNameField =
2549         llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2550   } else {
2551     TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2552   }
2553   Fields.push_back(TypeNameField);
2554 
2555   switch (Ty->getTypeClass()) {
2556 #define TYPE(Class, Base)
2557 #define ABSTRACT_TYPE(Class, Base)
2558 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2559 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2560 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2561 #include "clang/AST/TypeNodes.def"
2562     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2563 
2564   // GCC treats vector types as fundamental types.
2565   case Type::Builtin:
2566   case Type::Vector:
2567   case Type::ExtVector:
2568   case Type::Complex:
2569   case Type::BlockPointer:
2570     // Itanium C++ ABI 2.9.5p4:
2571     // abi::__fundamental_type_info adds no data members to std::type_info.
2572     break;
2573 
2574   case Type::LValueReference:
2575   case Type::RValueReference:
2576     llvm_unreachable("References shouldn't get here");
2577 
2578   case Type::Auto:
2579     llvm_unreachable("Undeduced auto type shouldn't get here");
2580 
2581   case Type::ConstantArray:
2582   case Type::IncompleteArray:
2583   case Type::VariableArray:
2584     // Itanium C++ ABI 2.9.5p5:
2585     // abi::__array_type_info adds no data members to std::type_info.
2586     break;
2587 
2588   case Type::FunctionNoProto:
2589   case Type::FunctionProto:
2590     // Itanium C++ ABI 2.9.5p5:
2591     // abi::__function_type_info adds no data members to std::type_info.
2592     break;
2593 
2594   case Type::Enum:
2595     // Itanium C++ ABI 2.9.5p5:
2596     // abi::__enum_type_info adds no data members to std::type_info.
2597     break;
2598 
2599   case Type::Record: {
2600     const CXXRecordDecl *RD =
2601       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2602     if (!RD->hasDefinition() || !RD->getNumBases()) {
2603       // We don't need to emit any fields.
2604       break;
2605     }
2606 
2607     if (CanUseSingleInheritance(RD))
2608       BuildSIClassTypeInfo(RD);
2609     else
2610       BuildVMIClassTypeInfo(RD);
2611 
2612     break;
2613   }
2614 
2615   case Type::ObjCObject:
2616   case Type::ObjCInterface:
2617     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2618     break;
2619 
2620   case Type::ObjCObjectPointer:
2621     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2622     break;
2623 
2624   case Type::Pointer:
2625     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2626     break;
2627 
2628   case Type::MemberPointer:
2629     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2630     break;
2631 
2632   case Type::Atomic:
2633     // No fields, at least for the moment.
2634     break;
2635   }
2636 
2637   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2638 
2639   llvm::GlobalVariable *GV =
2640     new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2641                              /*Constant=*/true, Linkage, Init, Name);
2642 
2643   // If there's already an old global variable, replace it with the new one.
2644   if (OldGV) {
2645     GV->takeName(OldGV);
2646     llvm::Constant *NewPtr =
2647       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2648     OldGV->replaceAllUsesWith(NewPtr);
2649     OldGV->eraseFromParent();
2650   }
2651 
2652   // The Itanium ABI specifies that type_info objects must be globally
2653   // unique, with one exception: if the type is an incomplete class
2654   // type or a (possibly indirect) pointer to one.  That exception
2655   // affects the general case of comparing type_info objects produced
2656   // by the typeid operator, which is why the comparison operators on
2657   // std::type_info generally use the type_info name pointers instead
2658   // of the object addresses.  However, the language's built-in uses
2659   // of RTTI generally require class types to be complete, even when
2660   // manipulating pointers to those class types.  This allows the
2661   // implementation of dynamic_cast to rely on address equality tests,
2662   // which is much faster.
2663 
2664   // All of this is to say that it's important that both the type_info
2665   // object and the type_info name be uniqued when weakly emitted.
2666 
2667   // Give the type_info object and name the formal visibility of the
2668   // type itself.
2669   llvm::GlobalValue::VisibilityTypes llvmVisibility;
2670   if (llvm::GlobalValue::isLocalLinkage(Linkage))
2671     // If the linkage is local, only default visibility makes sense.
2672     llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2673   else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2674     llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2675   else
2676     llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2677   TypeName->setVisibility(llvmVisibility);
2678   GV->setVisibility(llvmVisibility);
2679 
2680   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2681 }
2682 
2683 /// ComputeQualifierFlags - Compute the pointer type info flags from the
2684 /// given qualifier.
2685 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2686   unsigned Flags = 0;
2687 
2688   if (Quals.hasConst())
2689     Flags |= ItaniumRTTIBuilder::PTI_Const;
2690   if (Quals.hasVolatile())
2691     Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2692   if (Quals.hasRestrict())
2693     Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2694 
2695   return Flags;
2696 }
2697 
2698 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2699 /// for the given Objective-C object type.
2700 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2701   // Drop qualifiers.
2702   const Type *T = OT->getBaseType().getTypePtr();
2703   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2704 
2705   // The builtin types are abi::__class_type_infos and don't require
2706   // extra fields.
2707   if (isa<BuiltinType>(T)) return;
2708 
2709   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2710   ObjCInterfaceDecl *Super = Class->getSuperClass();
2711 
2712   // Root classes are also __class_type_info.
2713   if (!Super) return;
2714 
2715   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2716 
2717   // Everything else is single inheritance.
2718   llvm::Constant *BaseTypeInfo =
2719       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2720   Fields.push_back(BaseTypeInfo);
2721 }
2722 
2723 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2724 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2725 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2726   // Itanium C++ ABI 2.9.5p6b:
2727   // It adds to abi::__class_type_info a single member pointing to the
2728   // type_info structure for the base type,
2729   llvm::Constant *BaseTypeInfo =
2730     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2731   Fields.push_back(BaseTypeInfo);
2732 }
2733 
2734 namespace {
2735   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2736   /// a class hierarchy.
2737   struct SeenBases {
2738     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2739     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2740   };
2741 }
2742 
2743 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2744 /// abi::__vmi_class_type_info.
2745 ///
2746 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2747                                              SeenBases &Bases) {
2748 
2749   unsigned Flags = 0;
2750 
2751   const CXXRecordDecl *BaseDecl =
2752     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2753 
2754   if (Base->isVirtual()) {
2755     // Mark the virtual base as seen.
2756     if (!Bases.VirtualBases.insert(BaseDecl)) {
2757       // If this virtual base has been seen before, then the class is diamond
2758       // shaped.
2759       Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2760     } else {
2761       if (Bases.NonVirtualBases.count(BaseDecl))
2762         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2763     }
2764   } else {
2765     // Mark the non-virtual base as seen.
2766     if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2767       // If this non-virtual base has been seen before, then the class has non-
2768       // diamond shaped repeated inheritance.
2769       Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2770     } else {
2771       if (Bases.VirtualBases.count(BaseDecl))
2772         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2773     }
2774   }
2775 
2776   // Walk all bases.
2777   for (const auto &I : BaseDecl->bases())
2778     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2779 
2780   return Flags;
2781 }
2782 
2783 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2784   unsigned Flags = 0;
2785   SeenBases Bases;
2786 
2787   // Walk all bases.
2788   for (const auto &I : RD->bases())
2789     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2790 
2791   return Flags;
2792 }
2793 
2794 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2795 /// classes with bases that do not satisfy the abi::__si_class_type_info
2796 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2797 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2798   llvm::Type *UnsignedIntLTy =
2799     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2800 
2801   // Itanium C++ ABI 2.9.5p6c:
2802   //   __flags is a word with flags describing details about the class
2803   //   structure, which may be referenced by using the __flags_masks
2804   //   enumeration. These flags refer to both direct and indirect bases.
2805   unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2806   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2807 
2808   // Itanium C++ ABI 2.9.5p6c:
2809   //   __base_count is a word with the number of direct proper base class
2810   //   descriptions that follow.
2811   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2812 
2813   if (!RD->getNumBases())
2814     return;
2815 
2816   llvm::Type *LongLTy =
2817     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2818 
2819   // Now add the base class descriptions.
2820 
2821   // Itanium C++ ABI 2.9.5p6c:
2822   //   __base_info[] is an array of base class descriptions -- one for every
2823   //   direct proper base. Each description is of the type:
2824   //
2825   //   struct abi::__base_class_type_info {
2826   //   public:
2827   //     const __class_type_info *__base_type;
2828   //     long __offset_flags;
2829   //
2830   //     enum __offset_flags_masks {
2831   //       __virtual_mask = 0x1,
2832   //       __public_mask = 0x2,
2833   //       __offset_shift = 8
2834   //     };
2835   //   };
2836   for (const auto &Base : RD->bases()) {
2837     // The __base_type member points to the RTTI for the base type.
2838     Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2839 
2840     const CXXRecordDecl *BaseDecl =
2841       cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2842 
2843     int64_t OffsetFlags = 0;
2844 
2845     // All but the lower 8 bits of __offset_flags are a signed offset.
2846     // For a non-virtual base, this is the offset in the object of the base
2847     // subobject. For a virtual base, this is the offset in the virtual table of
2848     // the virtual base offset for the virtual base referenced (negative).
2849     CharUnits Offset;
2850     if (Base.isVirtual())
2851       Offset =
2852         CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2853     else {
2854       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2855       Offset = Layout.getBaseClassOffset(BaseDecl);
2856     };
2857 
2858     OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2859 
2860     // The low-order byte of __offset_flags contains flags, as given by the
2861     // masks from the enumeration __offset_flags_masks.
2862     if (Base.isVirtual())
2863       OffsetFlags |= BCTI_Virtual;
2864     if (Base.getAccessSpecifier() == AS_public)
2865       OffsetFlags |= BCTI_Public;
2866 
2867     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2868   }
2869 }
2870 
2871 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2872 /// used for pointer types.
2873 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2874   Qualifiers Quals;
2875   QualType UnqualifiedPointeeTy =
2876     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2877 
2878   // Itanium C++ ABI 2.9.5p7:
2879   //   __flags is a flag word describing the cv-qualification and other
2880   //   attributes of the type pointed to
2881   unsigned Flags = ComputeQualifierFlags(Quals);
2882 
2883   // Itanium C++ ABI 2.9.5p7:
2884   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
2885   //   incomplete class type, the incomplete target type flag is set.
2886   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2887     Flags |= PTI_Incomplete;
2888 
2889   llvm::Type *UnsignedIntLTy =
2890     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2891   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2892 
2893   // Itanium C++ ABI 2.9.5p7:
2894   //  __pointee is a pointer to the std::type_info derivation for the
2895   //  unqualified type being pointed to.
2896   llvm::Constant *PointeeTypeInfo =
2897     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2898   Fields.push_back(PointeeTypeInfo);
2899 }
2900 
2901 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2902 /// struct, used for member pointer types.
2903 void
2904 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2905   QualType PointeeTy = Ty->getPointeeType();
2906 
2907   Qualifiers Quals;
2908   QualType UnqualifiedPointeeTy =
2909     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2910 
2911   // Itanium C++ ABI 2.9.5p7:
2912   //   __flags is a flag word describing the cv-qualification and other
2913   //   attributes of the type pointed to.
2914   unsigned Flags = ComputeQualifierFlags(Quals);
2915 
2916   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2917 
2918   // Itanium C++ ABI 2.9.5p7:
2919   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
2920   //   incomplete class type, the incomplete target type flag is set.
2921   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2922     Flags |= PTI_Incomplete;
2923 
2924   if (IsIncompleteClassType(ClassType))
2925     Flags |= PTI_ContainingClassIncomplete;
2926 
2927   llvm::Type *UnsignedIntLTy =
2928     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2929   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2930 
2931   // Itanium C++ ABI 2.9.5p7:
2932   //   __pointee is a pointer to the std::type_info derivation for the
2933   //   unqualified type being pointed to.
2934   llvm::Constant *PointeeTypeInfo =
2935     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2936   Fields.push_back(PointeeTypeInfo);
2937 
2938   // Itanium C++ ABI 2.9.5p9:
2939   //   __context is a pointer to an abi::__class_type_info corresponding to the
2940   //   class type containing the member pointed to
2941   //   (e.g., the "A" in "int A::*").
2942   Fields.push_back(
2943       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2944 }
2945 
2946 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2947   return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2948 }
2949 
2950 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2951   QualType PointerType = getContext().getPointerType(Type);
2952   QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2953   ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2954   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2955   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2956 }
2957 
2958 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2959   QualType FundamentalTypes[] = {
2960       getContext().VoidTy,             getContext().NullPtrTy,
2961       getContext().BoolTy,             getContext().WCharTy,
2962       getContext().CharTy,             getContext().UnsignedCharTy,
2963       getContext().SignedCharTy,       getContext().ShortTy,
2964       getContext().UnsignedShortTy,    getContext().IntTy,
2965       getContext().UnsignedIntTy,      getContext().LongTy,
2966       getContext().UnsignedLongTy,     getContext().LongLongTy,
2967       getContext().UnsignedLongLongTy, getContext().HalfTy,
2968       getContext().FloatTy,            getContext().DoubleTy,
2969       getContext().LongDoubleTy,       getContext().Char16Ty,
2970       getContext().Char32Ty,
2971   };
2972   for (const QualType &FundamentalType : FundamentalTypes)
2973     EmitFundamentalRTTIDescriptor(FundamentalType);
2974 }
2975 
2976 /// What sort of uniqueness rules should we use for the RTTI for the
2977 /// given type?
2978 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2979     QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2980   if (shouldRTTIBeUnique())
2981     return RUK_Unique;
2982 
2983   // It's only necessary for linkonce_odr or weak_odr linkage.
2984   if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2985       Linkage != llvm::GlobalValue::WeakODRLinkage)
2986     return RUK_Unique;
2987 
2988   // It's only necessary with default visibility.
2989   if (CanTy->getVisibility() != DefaultVisibility)
2990     return RUK_Unique;
2991 
2992   // If we're not required to publish this symbol, hide it.
2993   if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
2994     return RUK_NonUniqueHidden;
2995 
2996   // If we're required to publish this symbol, as we might be under an
2997   // explicit instantiation, leave it with default visibility but
2998   // enable string-comparisons.
2999   assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3000   return RUK_NonUniqueVisible;
3001 }
3002