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/DataLayout.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Value.h"
31 
32 using namespace clang;
33 using namespace CodeGen;
34 
35 namespace {
36 class ItaniumCXXABI : public CodeGen::CGCXXABI {
37   /// VTables - All the vtables which have been defined.
38   llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
39 
40 protected:
41   bool UseARMMethodPtrABI;
42   bool UseARMGuardVarABI;
43 
44   ItaniumMangleContext &getMangleContext() {
45     return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
46   }
47 
48 public:
49   ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
50                 bool UseARMMethodPtrABI = false,
51                 bool UseARMGuardVarABI = false) :
52     CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
53     UseARMGuardVarABI(UseARMGuardVarABI) { }
54 
55   bool classifyReturnType(CGFunctionInfo &FI) const override;
56 
57   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
58     // Structures with either a non-trivial destructor or a non-trivial
59     // copy constructor are always indirect.
60     // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
61     // special members.
62     if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
63       return RAA_Indirect;
64     return RAA_Default;
65   }
66 
67   bool isZeroInitializable(const MemberPointerType *MPT) override;
68 
69   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
70 
71   llvm::Value *
72     EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
73                                     const Expr *E,
74                                     llvm::Value *&This,
75                                     llvm::Value *MemFnPtr,
76                                     const MemberPointerType *MPT) override;
77 
78   llvm::Value *
79     EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
80                                  llvm::Value *Base,
81                                  llvm::Value *MemPtr,
82                                  const MemberPointerType *MPT) override;
83 
84   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
85                                            const CastExpr *E,
86                                            llvm::Value *Src) override;
87   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
88                                               llvm::Constant *Src) override;
89 
90   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
91 
92   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
93   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
94                                         CharUnits offset) override;
95   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
96   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
97                                      CharUnits ThisAdjustment);
98 
99   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
100                                            llvm::Value *L, llvm::Value *R,
101                                            const MemberPointerType *MPT,
102                                            bool Inequality) override;
103 
104   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
105                                          llvm::Value *Addr,
106                                          const MemberPointerType *MPT) override;
107 
108   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
109                                       QualType type) override;
110 
111   llvm::Value *
112     GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
113                               const CXXRecordDecl *ClassDecl,
114                               const CXXRecordDecl *BaseClassDecl) override;
115 
116   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
117                                  CXXCtorType T, CanQualType &ResTy,
118                                  SmallVectorImpl<CanQualType> &ArgTys) override;
119 
120   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
121 
122   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
123                                 CXXDtorType T, CanQualType &ResTy,
124                                 SmallVectorImpl<CanQualType> &ArgTys) override;
125 
126   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
127                               CXXDtorType DT) const override {
128     // Itanium does not emit any destructor variant as an inline thunk.
129     // Delegating may occur as an optimization, but all variants are either
130     // emitted with external linkage or as linkonce if they are inline and used.
131     return false;
132   }
133 
134   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
135 
136   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
137                                  FunctionArgList &Params) override;
138 
139   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
140 
141   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
142                                       const CXXConstructorDecl *D,
143                                       CXXCtorType Type, bool ForVirtualBase,
144                                       bool Delegating,
145                                       CallArgList &Args) override;
146 
147   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
148                           CXXDtorType Type, bool ForVirtualBase,
149                           bool Delegating, llvm::Value *This) override;
150 
151   void emitVTableDefinitions(CodeGenVTables &CGVT,
152                              const CXXRecordDecl *RD) override;
153 
154   llvm::Value *getVTableAddressPointInStructor(
155       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
156       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
157       bool &NeedsVirtualOffset) override;
158 
159   llvm::Constant *
160   getVTableAddressPointForConstExpr(BaseSubobject Base,
161                                     const CXXRecordDecl *VTableClass) override;
162 
163   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
164                                         CharUnits VPtrOffset) override;
165 
166   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
167                                          llvm::Value *This,
168                                          llvm::Type *Ty) override;
169 
170   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
171                                  const CXXDestructorDecl *Dtor,
172                                  CXXDtorType DtorType, SourceLocation CallLoc,
173                                  llvm::Value *This) override;
174 
175   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
176 
177   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
178                        bool ReturnAdjustment) override {
179     // Allow inlining of thunks by emitting them with available_externally
180     // linkage together with vtables when needed.
181     if (ForVTable)
182       Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
183   }
184 
185   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
186                                      const ThisAdjustment &TA) override;
187 
188   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
189                                        const ReturnAdjustment &RA) override;
190 
191   StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
192   StringRef GetDeletedVirtualCallName() override
193     { return "__cxa_deleted_virtual"; }
194 
195   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
196   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
197                                      llvm::Value *NewPtr,
198                                      llvm::Value *NumElements,
199                                      const CXXNewExpr *expr,
200                                      QualType ElementType) override;
201   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
202                                    llvm::Value *allocPtr,
203                                    CharUnits cookieSize) override;
204 
205   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
206                        llvm::GlobalVariable *DeclPtr,
207                        bool PerformInit) override;
208   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
209                           llvm::Constant *dtor, llvm::Constant *addr) override;
210 
211   llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
212                                                 llvm::GlobalVariable *Var);
213   void EmitThreadLocalInitFuncs(
214       llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
215       llvm::Function *InitFunc) override;
216   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
217                                       QualType LValType) override;
218 
219   bool NeedsVTTParameter(GlobalDecl GD) override;
220 };
221 
222 class ARMCXXABI : public ItaniumCXXABI {
223 public:
224   ARMCXXABI(CodeGen::CodeGenModule &CGM) :
225     ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
226                   /* UseARMGuardVarABI = */ true) {}
227 
228   bool HasThisReturn(GlobalDecl GD) const override {
229     return (isa<CXXConstructorDecl>(GD.getDecl()) || (
230               isa<CXXDestructorDecl>(GD.getDecl()) &&
231               GD.getDtorType() != Dtor_Deleting));
232   }
233 
234   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
235                            QualType ResTy) override;
236 
237   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
238   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
239                                      llvm::Value *NewPtr,
240                                      llvm::Value *NumElements,
241                                      const CXXNewExpr *expr,
242                                      QualType ElementType) override;
243   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
244                                    CharUnits cookieSize) override;
245 };
246 
247 class iOS64CXXABI : public ARMCXXABI {
248 public:
249   iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
250 
251   // ARM64 libraries are prepared for non-unique RTTI.
252   bool shouldRTTIBeUnique() override { return false; }
253 };
254 }
255 
256 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
257   switch (CGM.getTarget().getCXXABI().getKind()) {
258   // For IR-generation purposes, there's no significant difference
259   // between the ARM and iOS ABIs.
260   case TargetCXXABI::GenericARM:
261   case TargetCXXABI::iOS:
262     return new ARMCXXABI(CGM);
263 
264   case TargetCXXABI::iOS64:
265     return new iOS64CXXABI(CGM);
266 
267   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
268   // include the other 32-bit ARM oddities: constructor/destructor return values
269   // and array cookies.
270   case TargetCXXABI::GenericAArch64:
271     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
272                              /* UseARMGuardVarABI = */ true);
273 
274   case TargetCXXABI::GenericItanium:
275     if (CGM.getContext().getTargetInfo().getTriple().getArch()
276         == llvm::Triple::le32) {
277       // For PNaCl, use ARM-style method pointers so that PNaCl code
278       // does not assume anything about the alignment of function
279       // pointers.
280       return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
281                                /* UseARMGuardVarABI = */ false);
282     }
283     return new ItaniumCXXABI(CGM);
284 
285   case TargetCXXABI::Microsoft:
286     llvm_unreachable("Microsoft ABI is not Itanium-based");
287   }
288   llvm_unreachable("bad ABI kind");
289 }
290 
291 llvm::Type *
292 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
293   if (MPT->isMemberDataPointer())
294     return CGM.PtrDiffTy;
295   return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
296 }
297 
298 /// In the Itanium and ARM ABIs, method pointers have the form:
299 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
300 ///
301 /// In the Itanium ABI:
302 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
303 ///  - the this-adjustment is (memptr.adj)
304 ///  - the virtual offset is (memptr.ptr - 1)
305 ///
306 /// In the ARM ABI:
307 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
308 ///  - the this-adjustment is (memptr.adj >> 1)
309 ///  - the virtual offset is (memptr.ptr)
310 /// ARM uses 'adj' for the virtual flag because Thumb functions
311 /// may be only single-byte aligned.
312 ///
313 /// If the member is virtual, the adjusted 'this' pointer points
314 /// to a vtable pointer from which the virtual offset is applied.
315 ///
316 /// If the member is non-virtual, memptr.ptr is the address of
317 /// the function to call.
318 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
319     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
320     llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
321   CGBuilderTy &Builder = CGF.Builder;
322 
323   const FunctionProtoType *FPT =
324     MPT->getPointeeType()->getAs<FunctionProtoType>();
325   const CXXRecordDecl *RD =
326     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
327 
328   llvm::FunctionType *FTy =
329     CGM.getTypes().GetFunctionType(
330       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
331 
332   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
333 
334   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
335   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
336   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
337 
338   // Extract memptr.adj, which is in the second field.
339   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
340 
341   // Compute the true adjustment.
342   llvm::Value *Adj = RawAdj;
343   if (UseARMMethodPtrABI)
344     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
345 
346   // Apply the adjustment and cast back to the original struct type
347   // for consistency.
348   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
349   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
350   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
351 
352   // Load the function pointer.
353   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
354 
355   // If the LSB in the function pointer is 1, the function pointer points to
356   // a virtual function.
357   llvm::Value *IsVirtual;
358   if (UseARMMethodPtrABI)
359     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
360   else
361     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
362   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
363   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
364 
365   // In the virtual path, the adjustment left 'This' pointing to the
366   // vtable of the correct base subobject.  The "function pointer" is an
367   // offset within the vtable (+1 for the virtual flag on non-ARM).
368   CGF.EmitBlock(FnVirtual);
369 
370   // Cast the adjusted this to a pointer to vtable pointer and load.
371   llvm::Type *VTableTy = Builder.getInt8PtrTy();
372   llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
373 
374   // Apply the offset.
375   llvm::Value *VTableOffset = FnAsInt;
376   if (!UseARMMethodPtrABI)
377     VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
378   VTable = Builder.CreateGEP(VTable, VTableOffset);
379 
380   // Load the virtual function to call.
381   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
382   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
383   CGF.EmitBranch(FnEnd);
384 
385   // In the non-virtual path, the function pointer is actually a
386   // function pointer.
387   CGF.EmitBlock(FnNonVirtual);
388   llvm::Value *NonVirtualFn =
389     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
390 
391   // We're done.
392   CGF.EmitBlock(FnEnd);
393   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
394   Callee->addIncoming(VirtualFn, FnVirtual);
395   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
396   return Callee;
397 }
398 
399 /// Compute an l-value by applying the given pointer-to-member to a
400 /// base object.
401 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
402     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
403     const MemberPointerType *MPT) {
404   assert(MemPtr->getType() == CGM.PtrDiffTy);
405 
406   CGBuilderTy &Builder = CGF.Builder;
407 
408   unsigned AS = Base->getType()->getPointerAddressSpace();
409 
410   // Cast to char*.
411   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
412 
413   // Apply the offset, which we assume is non-null.
414   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
415 
416   // Cast the address to the appropriate pointer type, adopting the
417   // address space of the base pointer.
418   llvm::Type *PType
419     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
420   return Builder.CreateBitCast(Addr, PType);
421 }
422 
423 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
424 /// conversion.
425 ///
426 /// Bitcast conversions are always a no-op under Itanium.
427 ///
428 /// Obligatory offset/adjustment diagram:
429 ///         <-- offset -->          <-- adjustment -->
430 ///   |--------------------------|----------------------|--------------------|
431 ///   ^Derived address point     ^Base address point    ^Member address point
432 ///
433 /// So when converting a base member pointer to a derived member pointer,
434 /// we add the offset to the adjustment because the address point has
435 /// decreased;  and conversely, when converting a derived MP to a base MP
436 /// we subtract the offset from the adjustment because the address point
437 /// has increased.
438 ///
439 /// The standard forbids (at compile time) conversion to and from
440 /// virtual bases, which is why we don't have to consider them here.
441 ///
442 /// The standard forbids (at run time) casting a derived MP to a base
443 /// MP when the derived MP does not point to a member of the base.
444 /// This is why -1 is a reasonable choice for null data member
445 /// pointers.
446 llvm::Value *
447 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
448                                            const CastExpr *E,
449                                            llvm::Value *src) {
450   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
451          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
452          E->getCastKind() == CK_ReinterpretMemberPointer);
453 
454   // Under Itanium, reinterprets don't require any additional processing.
455   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
456 
457   // Use constant emission if we can.
458   if (isa<llvm::Constant>(src))
459     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
460 
461   llvm::Constant *adj = getMemberPointerAdjustment(E);
462   if (!adj) return src;
463 
464   CGBuilderTy &Builder = CGF.Builder;
465   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
466 
467   const MemberPointerType *destTy =
468     E->getType()->castAs<MemberPointerType>();
469 
470   // For member data pointers, this is just a matter of adding the
471   // offset if the source is non-null.
472   if (destTy->isMemberDataPointer()) {
473     llvm::Value *dst;
474     if (isDerivedToBase)
475       dst = Builder.CreateNSWSub(src, adj, "adj");
476     else
477       dst = Builder.CreateNSWAdd(src, adj, "adj");
478 
479     // Null check.
480     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
481     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
482     return Builder.CreateSelect(isNull, src, dst);
483   }
484 
485   // The this-adjustment is left-shifted by 1 on ARM.
486   if (UseARMMethodPtrABI) {
487     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
488     offset <<= 1;
489     adj = llvm::ConstantInt::get(adj->getType(), offset);
490   }
491 
492   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
493   llvm::Value *dstAdj;
494   if (isDerivedToBase)
495     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
496   else
497     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
498 
499   return Builder.CreateInsertValue(src, dstAdj, 1);
500 }
501 
502 llvm::Constant *
503 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
504                                            llvm::Constant *src) {
505   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
506          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
507          E->getCastKind() == CK_ReinterpretMemberPointer);
508 
509   // Under Itanium, reinterprets don't require any additional processing.
510   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
511 
512   // If the adjustment is trivial, we don't need to do anything.
513   llvm::Constant *adj = getMemberPointerAdjustment(E);
514   if (!adj) return src;
515 
516   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
517 
518   const MemberPointerType *destTy =
519     E->getType()->castAs<MemberPointerType>();
520 
521   // For member data pointers, this is just a matter of adding the
522   // offset if the source is non-null.
523   if (destTy->isMemberDataPointer()) {
524     // null maps to null.
525     if (src->isAllOnesValue()) return src;
526 
527     if (isDerivedToBase)
528       return llvm::ConstantExpr::getNSWSub(src, adj);
529     else
530       return llvm::ConstantExpr::getNSWAdd(src, adj);
531   }
532 
533   // The this-adjustment is left-shifted by 1 on ARM.
534   if (UseARMMethodPtrABI) {
535     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
536     offset <<= 1;
537     adj = llvm::ConstantInt::get(adj->getType(), offset);
538   }
539 
540   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
541   llvm::Constant *dstAdj;
542   if (isDerivedToBase)
543     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
544   else
545     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
546 
547   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
548 }
549 
550 llvm::Constant *
551 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
552   // Itanium C++ ABI 2.3:
553   //   A NULL pointer is represented as -1.
554   if (MPT->isMemberDataPointer())
555     return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
556 
557   llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
558   llvm::Constant *Values[2] = { Zero, Zero };
559   return llvm::ConstantStruct::getAnon(Values);
560 }
561 
562 llvm::Constant *
563 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
564                                      CharUnits offset) {
565   // Itanium C++ ABI 2.3:
566   //   A pointer to data member is an offset from the base address of
567   //   the class object containing it, represented as a ptrdiff_t
568   return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
569 }
570 
571 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
572   return BuildMemberPointer(MD, CharUnits::Zero());
573 }
574 
575 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
576                                                   CharUnits ThisAdjustment) {
577   assert(MD->isInstance() && "Member function must not be static!");
578   MD = MD->getCanonicalDecl();
579 
580   CodeGenTypes &Types = CGM.getTypes();
581 
582   // Get the function pointer (or index if this is a virtual function).
583   llvm::Constant *MemPtr[2];
584   if (MD->isVirtual()) {
585     uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
586 
587     const ASTContext &Context = getContext();
588     CharUnits PointerWidth =
589       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
590     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
591 
592     if (UseARMMethodPtrABI) {
593       // ARM C++ ABI 3.2.1:
594       //   This ABI specifies that adj contains twice the this
595       //   adjustment, plus 1 if the member function is virtual. The
596       //   least significant bit of adj then makes exactly the same
597       //   discrimination as the least significant bit of ptr does for
598       //   Itanium.
599       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
600       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
601                                          2 * ThisAdjustment.getQuantity() + 1);
602     } else {
603       // Itanium C++ ABI 2.3:
604       //   For a virtual function, [the pointer field] is 1 plus the
605       //   virtual table offset (in bytes) of the function,
606       //   represented as a ptrdiff_t.
607       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
608       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
609                                          ThisAdjustment.getQuantity());
610     }
611   } else {
612     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
613     llvm::Type *Ty;
614     // Check whether the function has a computable LLVM signature.
615     if (Types.isFuncTypeConvertible(FPT)) {
616       // The function has a computable LLVM signature; use the correct type.
617       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
618     } else {
619       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
620       // function type is incomplete.
621       Ty = CGM.PtrDiffTy;
622     }
623     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
624 
625     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
626     MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
627                                        (UseARMMethodPtrABI ? 2 : 1) *
628                                        ThisAdjustment.getQuantity());
629   }
630 
631   return llvm::ConstantStruct::getAnon(MemPtr);
632 }
633 
634 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
635                                                  QualType MPType) {
636   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
637   const ValueDecl *MPD = MP.getMemberPointerDecl();
638   if (!MPD)
639     return EmitNullMemberPointer(MPT);
640 
641   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
642 
643   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
644     return BuildMemberPointer(MD, ThisAdjustment);
645 
646   CharUnits FieldOffset =
647     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
648   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
649 }
650 
651 /// The comparison algorithm is pretty easy: the member pointers are
652 /// the same if they're either bitwise identical *or* both null.
653 ///
654 /// ARM is different here only because null-ness is more complicated.
655 llvm::Value *
656 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
657                                            llvm::Value *L,
658                                            llvm::Value *R,
659                                            const MemberPointerType *MPT,
660                                            bool Inequality) {
661   CGBuilderTy &Builder = CGF.Builder;
662 
663   llvm::ICmpInst::Predicate Eq;
664   llvm::Instruction::BinaryOps And, Or;
665   if (Inequality) {
666     Eq = llvm::ICmpInst::ICMP_NE;
667     And = llvm::Instruction::Or;
668     Or = llvm::Instruction::And;
669   } else {
670     Eq = llvm::ICmpInst::ICMP_EQ;
671     And = llvm::Instruction::And;
672     Or = llvm::Instruction::Or;
673   }
674 
675   // Member data pointers are easy because there's a unique null
676   // value, so it just comes down to bitwise equality.
677   if (MPT->isMemberDataPointer())
678     return Builder.CreateICmp(Eq, L, R);
679 
680   // For member function pointers, the tautologies are more complex.
681   // The Itanium tautology is:
682   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
683   // The ARM tautology is:
684   //   (L == R) <==> (L.ptr == R.ptr &&
685   //                  (L.adj == R.adj ||
686   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
687   // The inequality tautologies have exactly the same structure, except
688   // applying De Morgan's laws.
689 
690   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
691   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
692 
693   // This condition tests whether L.ptr == R.ptr.  This must always be
694   // true for equality to hold.
695   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
696 
697   // This condition, together with the assumption that L.ptr == R.ptr,
698   // tests whether the pointers are both null.  ARM imposes an extra
699   // condition.
700   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
701   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
702 
703   // This condition tests whether L.adj == R.adj.  If this isn't
704   // true, the pointers are unequal unless they're both null.
705   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
706   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
707   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
708 
709   // Null member function pointers on ARM clear the low bit of Adj,
710   // so the zero condition has to check that neither low bit is set.
711   if (UseARMMethodPtrABI) {
712     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
713 
714     // Compute (l.adj | r.adj) & 1 and test it against zero.
715     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
716     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
717     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
718                                                       "cmp.or.adj");
719     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
720   }
721 
722   // Tie together all our conditions.
723   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
724   Result = Builder.CreateBinOp(And, PtrEq, Result,
725                                Inequality ? "memptr.ne" : "memptr.eq");
726   return Result;
727 }
728 
729 llvm::Value *
730 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
731                                           llvm::Value *MemPtr,
732                                           const MemberPointerType *MPT) {
733   CGBuilderTy &Builder = CGF.Builder;
734 
735   /// For member data pointers, this is just a check against -1.
736   if (MPT->isMemberDataPointer()) {
737     assert(MemPtr->getType() == CGM.PtrDiffTy);
738     llvm::Value *NegativeOne =
739       llvm::Constant::getAllOnesValue(MemPtr->getType());
740     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
741   }
742 
743   // In Itanium, a member function pointer is not null if 'ptr' is not null.
744   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
745 
746   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
747   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
748 
749   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
750   // (the virtual bit) is set.
751   if (UseARMMethodPtrABI) {
752     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
753     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
754     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
755     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
756                                                   "memptr.isvirtual");
757     Result = Builder.CreateOr(Result, IsVirtual);
758   }
759 
760   return Result;
761 }
762 
763 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
764   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
765   if (!RD)
766     return false;
767 
768   // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
769   // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
770   // special members.
771   if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
772     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
773     return true;
774   }
775   return false;
776 }
777 
778 /// The Itanium ABI requires non-zero initialization only for data
779 /// member pointers, for which '0' is a valid offset.
780 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
781   return MPT->getPointeeType()->isFunctionType();
782 }
783 
784 /// The Itanium ABI always places an offset to the complete object
785 /// at entry -2 in the vtable.
786 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
787                                                    llvm::Value *ptr,
788                                                    QualType type) {
789   // Grab the vtable pointer as an intptr_t*.
790   llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
791 
792   // Track back to entry -2 and pull out the offset there.
793   llvm::Value *offsetPtr =
794     CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
795   llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
796   offset->setAlignment(CGF.PointerAlignInBytes);
797 
798   // Apply the offset.
799   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
800   return CGF.Builder.CreateInBoundsGEP(ptr, offset);
801 }
802 
803 llvm::Value *
804 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
805                                          llvm::Value *This,
806                                          const CXXRecordDecl *ClassDecl,
807                                          const CXXRecordDecl *BaseClassDecl) {
808   llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
809   CharUnits VBaseOffsetOffset =
810       CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
811                                                                BaseClassDecl);
812 
813   llvm::Value *VBaseOffsetPtr =
814     CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
815                                    "vbase.offset.ptr");
816   VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
817                                              CGM.PtrDiffTy->getPointerTo());
818 
819   llvm::Value *VBaseOffset =
820     CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
821 
822   return VBaseOffset;
823 }
824 
825 /// The generic ABI passes 'this', plus a VTT if it's initializing a
826 /// base subobject.
827 void
828 ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
829                                          CXXCtorType Type, CanQualType &ResTy,
830                                          SmallVectorImpl<CanQualType> &ArgTys) {
831   ASTContext &Context = getContext();
832 
833   // All parameters are already in place except VTT, which goes after 'this'.
834   // These are Clang types, so we don't need to worry about sret yet.
835 
836   // Check if we need to add a VTT parameter (which has type void **).
837   if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
838     ArgTys.insert(ArgTys.begin() + 1,
839                   Context.getPointerType(Context.VoidPtrTy));
840 }
841 
842 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
843   // Just make sure we're in sync with TargetCXXABI.
844   assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
845 
846   // The constructor used for constructing this as a base class;
847   // ignores virtual bases.
848   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
849 
850   // The constructor used for constructing this as a complete class;
851   // constucts the virtual bases, then calls the base constructor.
852   if (!D->getParent()->isAbstract()) {
853     // We don't need to emit the complete ctor if the class is abstract.
854     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
855   }
856 }
857 
858 /// The generic ABI passes 'this', plus a VTT if it's destroying a
859 /// base subobject.
860 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
861                                              CXXDtorType Type,
862                                              CanQualType &ResTy,
863                                 SmallVectorImpl<CanQualType> &ArgTys) {
864   ASTContext &Context = getContext();
865 
866   // 'this' parameter is already there, as well as 'this' return if
867   // HasThisReturn(GlobalDecl(Dtor, Type)) is true
868 
869   // Check if we need to add a VTT parameter (which has type void **).
870   if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
871     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
872 }
873 
874 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
875   // The destructor used for destructing this as a base class; ignores
876   // virtual bases.
877   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
878 
879   // The destructor used for destructing this as a most-derived class;
880   // call the base destructor and then destructs any virtual bases.
881   CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
882 
883   // The destructor in a virtual table is always a 'deleting'
884   // destructor, which calls the complete destructor and then uses the
885   // appropriate operator delete.
886   if (D->isVirtual())
887     CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
888 }
889 
890 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
891                                               QualType &ResTy,
892                                               FunctionArgList &Params) {
893   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
894   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
895 
896   // Check if we need a VTT parameter as well.
897   if (NeedsVTTParameter(CGF.CurGD)) {
898     ASTContext &Context = getContext();
899 
900     // FIXME: avoid the fake decl
901     QualType T = Context.getPointerType(Context.VoidPtrTy);
902     ImplicitParamDecl *VTTDecl
903       = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
904                                   &Context.Idents.get("vtt"), T);
905     Params.insert(Params.begin() + 1, VTTDecl);
906     getStructorImplicitParamDecl(CGF) = VTTDecl;
907   }
908 }
909 
910 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
911   /// Initialize the 'this' slot.
912   EmitThisParam(CGF);
913 
914   /// Initialize the 'vtt' slot if needed.
915   if (getStructorImplicitParamDecl(CGF)) {
916     getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
917         CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
918   }
919 
920   /// If this is a function that the ABI specifies returns 'this', initialize
921   /// the return slot to 'this' at the start of the function.
922   ///
923   /// Unlike the setting of return types, this is done within the ABI
924   /// implementation instead of by clients of CGCXXABI because:
925   /// 1) getThisValue is currently protected
926   /// 2) in theory, an ABI could implement 'this' returns some other way;
927   ///    HasThisReturn only specifies a contract, not the implementation
928   if (HasThisReturn(CGF.CurGD))
929     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
930 }
931 
932 unsigned ItaniumCXXABI::addImplicitConstructorArgs(
933     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
934     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
935   if (!NeedsVTTParameter(GlobalDecl(D, Type)))
936     return 0;
937 
938   // Insert the implicit 'vtt' argument as the second argument.
939   llvm::Value *VTT =
940       CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
941   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
942   Args.insert(Args.begin() + 1,
943               CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
944   return 1;  // Added one arg.
945 }
946 
947 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
948                                        const CXXDestructorDecl *DD,
949                                        CXXDtorType Type, bool ForVirtualBase,
950                                        bool Delegating, llvm::Value *This) {
951   GlobalDecl GD(DD, Type);
952   llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
953   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
954 
955   llvm::Value *Callee = nullptr;
956   if (getContext().getLangOpts().AppleKext)
957     Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
958 
959   if (!Callee)
960     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
961 
962   // FIXME: Provide a source location here.
963   CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
964                         VTT, VTTTy, nullptr, nullptr);
965 }
966 
967 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
968                                           const CXXRecordDecl *RD) {
969   llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
970   if (VTable->hasInitializer())
971     return;
972 
973   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
974   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
975   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
976 
977   // Create and set the initializer.
978   llvm::Constant *Init = CGVT.CreateVTableInitializer(
979       RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
980       VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
981   VTable->setInitializer(Init);
982 
983   // Set the correct linkage.
984   VTable->setLinkage(Linkage);
985 
986   // Set the right visibility.
987   CGM.setGlobalVisibility(VTable, RD);
988 
989   // If this is the magic class __cxxabiv1::__fundamental_type_info,
990   // we will emit the typeinfo for the fundamental types. This is the
991   // same behaviour as GCC.
992   const DeclContext *DC = RD->getDeclContext();
993   if (RD->getIdentifier() &&
994       RD->getIdentifier()->isStr("__fundamental_type_info") &&
995       isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
996       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
997       DC->getParent()->isTranslationUnit())
998     CGM.EmitFundamentalRTTIDescriptors();
999 }
1000 
1001 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1002     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1003     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1004   bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1005   NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1006 
1007   llvm::Value *VTableAddressPoint;
1008   if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1009     // Get the secondary vpointer index.
1010     uint64_t VirtualPointerIndex =
1011         CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1012 
1013     /// Load the VTT.
1014     llvm::Value *VTT = CGF.LoadCXXVTT();
1015     if (VirtualPointerIndex)
1016       VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1017 
1018     // And load the address point from the VTT.
1019     VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1020   } else {
1021     llvm::Constant *VTable =
1022         CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1023     uint64_t AddressPoint = CGM.getItaniumVTableContext()
1024                                 .getVTableLayout(VTableClass)
1025                                 .getAddressPoint(Base);
1026     VTableAddressPoint =
1027         CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1028   }
1029 
1030   return VTableAddressPoint;
1031 }
1032 
1033 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1034     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1035   llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1036 
1037   // Find the appropriate vtable within the vtable group.
1038   uint64_t AddressPoint = CGM.getItaniumVTableContext()
1039                               .getVTableLayout(VTableClass)
1040                               .getAddressPoint(Base);
1041   llvm::Value *Indices[] = {
1042     llvm::ConstantInt::get(CGM.Int64Ty, 0),
1043     llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1044   };
1045 
1046   return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1047 }
1048 
1049 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1050                                                      CharUnits VPtrOffset) {
1051   assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1052 
1053   llvm::GlobalVariable *&VTable = VTables[RD];
1054   if (VTable)
1055     return VTable;
1056 
1057   // Queue up this v-table for possible deferred emission.
1058   CGM.addDeferredVTable(RD);
1059 
1060   SmallString<256> OutName;
1061   llvm::raw_svector_ostream Out(OutName);
1062   getMangleContext().mangleCXXVTable(RD, Out);
1063   Out.flush();
1064   StringRef Name = OutName.str();
1065 
1066   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1067   llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1068       CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1069 
1070   VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1071       Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1072   VTable->setUnnamedAddr(true);
1073 
1074   if (RD->hasAttr<DLLImportAttr>())
1075     VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1076   else if (RD->hasAttr<DLLExportAttr>())
1077     VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1078 
1079   return VTable;
1080 }
1081 
1082 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1083                                                       GlobalDecl GD,
1084                                                       llvm::Value *This,
1085                                                       llvm::Type *Ty) {
1086   GD = GD.getCanonicalDecl();
1087   Ty = Ty->getPointerTo()->getPointerTo();
1088   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1089 
1090   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1091   llvm::Value *VFuncPtr =
1092       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1093   return CGF.Builder.CreateLoad(VFuncPtr);
1094 }
1095 
1096 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1097                                               const CXXDestructorDecl *Dtor,
1098                                               CXXDtorType DtorType,
1099                                               SourceLocation CallLoc,
1100                                               llvm::Value *This) {
1101   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1102 
1103   const CGFunctionInfo *FInfo
1104     = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1105   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1106   llvm::Value *Callee =
1107       getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
1108 
1109   CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1110                         /*ImplicitParam=*/nullptr, QualType(), nullptr,
1111                         nullptr);
1112 }
1113 
1114 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1115   CodeGenVTables &VTables = CGM.getVTables();
1116   llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1117   VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1118 }
1119 
1120 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1121                                           llvm::Value *Ptr,
1122                                           int64_t NonVirtualAdjustment,
1123                                           int64_t VirtualAdjustment,
1124                                           bool IsReturnAdjustment) {
1125   if (!NonVirtualAdjustment && !VirtualAdjustment)
1126     return Ptr;
1127 
1128   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1129   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1130 
1131   if (NonVirtualAdjustment && !IsReturnAdjustment) {
1132     // Perform the non-virtual adjustment for a base-to-derived cast.
1133     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1134   }
1135 
1136   if (VirtualAdjustment) {
1137     llvm::Type *PtrDiffTy =
1138         CGF.ConvertType(CGF.getContext().getPointerDiffType());
1139 
1140     // Perform the virtual adjustment.
1141     llvm::Value *VTablePtrPtr =
1142         CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1143 
1144     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1145 
1146     llvm::Value *OffsetPtr =
1147         CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1148 
1149     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1150 
1151     // Load the adjustment offset from the vtable.
1152     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1153 
1154     // Adjust our pointer.
1155     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1156   }
1157 
1158   if (NonVirtualAdjustment && IsReturnAdjustment) {
1159     // Perform the non-virtual adjustment for a derived-to-base cast.
1160     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1161   }
1162 
1163   // Cast back to the original type.
1164   return CGF.Builder.CreateBitCast(V, Ptr->getType());
1165 }
1166 
1167 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1168                                                   llvm::Value *This,
1169                                                   const ThisAdjustment &TA) {
1170   return performTypeAdjustment(CGF, This, TA.NonVirtual,
1171                                TA.Virtual.Itanium.VCallOffsetOffset,
1172                                /*IsReturnAdjustment=*/false);
1173 }
1174 
1175 llvm::Value *
1176 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1177                                        const ReturnAdjustment &RA) {
1178   return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1179                                RA.Virtual.Itanium.VBaseOffsetOffset,
1180                                /*IsReturnAdjustment=*/true);
1181 }
1182 
1183 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1184                                     RValue RV, QualType ResultType) {
1185   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1186     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1187 
1188   // Destructor thunks in the ARM ABI have indeterminate results.
1189   llvm::Type *T =
1190     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1191   RValue Undef = RValue::get(llvm::UndefValue::get(T));
1192   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1193 }
1194 
1195 /************************** Array allocation cookies **************************/
1196 
1197 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1198   // The array cookie is a size_t; pad that up to the element alignment.
1199   // The cookie is actually right-justified in that space.
1200   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1201                   CGM.getContext().getTypeAlignInChars(elementType));
1202 }
1203 
1204 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1205                                                   llvm::Value *NewPtr,
1206                                                   llvm::Value *NumElements,
1207                                                   const CXXNewExpr *expr,
1208                                                   QualType ElementType) {
1209   assert(requiresArrayCookie(expr));
1210 
1211   unsigned AS = NewPtr->getType()->getPointerAddressSpace();
1212 
1213   ASTContext &Ctx = getContext();
1214   QualType SizeTy = Ctx.getSizeType();
1215   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1216 
1217   // The size of the cookie.
1218   CharUnits CookieSize =
1219     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1220   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1221 
1222   // Compute an offset to the cookie.
1223   llvm::Value *CookiePtr = NewPtr;
1224   CharUnits CookieOffset = CookieSize - SizeSize;
1225   if (!CookieOffset.isZero())
1226     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1227                                                  CookieOffset.getQuantity());
1228 
1229   // Write the number of elements into the appropriate slot.
1230   llvm::Value *NumElementsPtr
1231     = CGF.Builder.CreateBitCast(CookiePtr,
1232                                 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1233   CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1234 
1235   // Finally, compute a pointer to the actual data buffer by skipping
1236   // over the cookie completely.
1237   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1238                                                 CookieSize.getQuantity());
1239 }
1240 
1241 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1242                                                 llvm::Value *allocPtr,
1243                                                 CharUnits cookieSize) {
1244   // The element size is right-justified in the cookie.
1245   llvm::Value *numElementsPtr = allocPtr;
1246   CharUnits numElementsOffset =
1247     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1248   if (!numElementsOffset.isZero())
1249     numElementsPtr =
1250       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1251                                              numElementsOffset.getQuantity());
1252 
1253   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1254   numElementsPtr =
1255     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1256   return CGF.Builder.CreateLoad(numElementsPtr);
1257 }
1258 
1259 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1260   // ARM says that the cookie is always:
1261   //   struct array_cookie {
1262   //     std::size_t element_size; // element_size != 0
1263   //     std::size_t element_count;
1264   //   };
1265   // But the base ABI doesn't give anything an alignment greater than
1266   // 8, so we can dismiss this as typical ABI-author blindness to
1267   // actual language complexity and round up to the element alignment.
1268   return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1269                   CGM.getContext().getTypeAlignInChars(elementType));
1270 }
1271 
1272 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1273                                               llvm::Value *newPtr,
1274                                               llvm::Value *numElements,
1275                                               const CXXNewExpr *expr,
1276                                               QualType elementType) {
1277   assert(requiresArrayCookie(expr));
1278 
1279   // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1280   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1281 
1282   // The cookie is always at the start of the buffer.
1283   llvm::Value *cookie = newPtr;
1284 
1285   // The first element is the element size.
1286   cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1287   llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1288                  getContext().getTypeSizeInChars(elementType).getQuantity());
1289   CGF.Builder.CreateStore(elementSize, cookie);
1290 
1291   // The second element is the element count.
1292   cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1293   CGF.Builder.CreateStore(numElements, cookie);
1294 
1295   // Finally, compute a pointer to the actual data buffer by skipping
1296   // over the cookie completely.
1297   CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1298   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1299                                                 cookieSize.getQuantity());
1300 }
1301 
1302 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1303                                             llvm::Value *allocPtr,
1304                                             CharUnits cookieSize) {
1305   // The number of elements is at offset sizeof(size_t) relative to
1306   // the allocated pointer.
1307   llvm::Value *numElementsPtr
1308     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
1309 
1310   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1311   numElementsPtr =
1312     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1313   return CGF.Builder.CreateLoad(numElementsPtr);
1314 }
1315 
1316 /*********************** Static local initialization **************************/
1317 
1318 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1319                                          llvm::PointerType *GuardPtrTy) {
1320   // int __cxa_guard_acquire(__guard *guard_object);
1321   llvm::FunctionType *FTy =
1322     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1323                             GuardPtrTy, /*isVarArg=*/false);
1324   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1325                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1326                                               llvm::AttributeSet::FunctionIndex,
1327                                                  llvm::Attribute::NoUnwind));
1328 }
1329 
1330 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1331                                          llvm::PointerType *GuardPtrTy) {
1332   // void __cxa_guard_release(__guard *guard_object);
1333   llvm::FunctionType *FTy =
1334     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1335   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1336                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1337                                               llvm::AttributeSet::FunctionIndex,
1338                                                  llvm::Attribute::NoUnwind));
1339 }
1340 
1341 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1342                                        llvm::PointerType *GuardPtrTy) {
1343   // void __cxa_guard_abort(__guard *guard_object);
1344   llvm::FunctionType *FTy =
1345     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1346   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1347                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1348                                               llvm::AttributeSet::FunctionIndex,
1349                                                  llvm::Attribute::NoUnwind));
1350 }
1351 
1352 namespace {
1353   struct CallGuardAbort : EHScopeStack::Cleanup {
1354     llvm::GlobalVariable *Guard;
1355     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1356 
1357     void Emit(CodeGenFunction &CGF, Flags flags) override {
1358       CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1359                                   Guard);
1360     }
1361   };
1362 }
1363 
1364 /// The ARM code here follows the Itanium code closely enough that we
1365 /// just special-case it at particular places.
1366 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1367                                     const VarDecl &D,
1368                                     llvm::GlobalVariable *var,
1369                                     bool shouldPerformInit) {
1370   CGBuilderTy &Builder = CGF.Builder;
1371 
1372   // We only need to use thread-safe statics for local non-TLS variables;
1373   // global initialization is always single-threaded.
1374   bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1375                     D.isLocalVarDecl() && !D.getTLSKind();
1376 
1377   // If we have a global variable with internal linkage and thread-safe statics
1378   // are disabled, we can just let the guard variable be of type i8.
1379   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1380 
1381   llvm::IntegerType *guardTy;
1382   if (useInt8GuardVariable) {
1383     guardTy = CGF.Int8Ty;
1384   } else {
1385     // Guard variables are 64 bits in the generic ABI and size width on ARM
1386     // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1387     guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
1388   }
1389   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
1390 
1391   // Create the guard variable if we don't already have it (as we
1392   // might if we're double-emitting this function body).
1393   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1394   if (!guard) {
1395     // Mangle the name for the guard.
1396     SmallString<256> guardName;
1397     {
1398       llvm::raw_svector_ostream out(guardName);
1399       getMangleContext().mangleStaticGuardVariable(&D, out);
1400       out.flush();
1401     }
1402 
1403     // Create the guard variable with a zero-initializer.
1404     // Just absorb linkage and visibility from the guarded variable.
1405     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1406                                      false, var->getLinkage(),
1407                                      llvm::ConstantInt::get(guardTy, 0),
1408                                      guardName.str());
1409     guard->setVisibility(var->getVisibility());
1410     // If the variable is thread-local, so is its guard variable.
1411     guard->setThreadLocalMode(var->getThreadLocalMode());
1412 
1413     CGM.setStaticLocalDeclGuardAddress(&D, guard);
1414   }
1415 
1416   // Test whether the variable has completed initialization.
1417   //
1418   // Itanium C++ ABI 3.3.2:
1419   //   The following is pseudo-code showing how these functions can be used:
1420   //     if (obj_guard.first_byte == 0) {
1421   //       if ( __cxa_guard_acquire (&obj_guard) ) {
1422   //         try {
1423   //           ... initialize the object ...;
1424   //         } catch (...) {
1425   //            __cxa_guard_abort (&obj_guard);
1426   //            throw;
1427   //         }
1428   //         ... queue object destructor with __cxa_atexit() ...;
1429   //         __cxa_guard_release (&obj_guard);
1430   //       }
1431   //     }
1432 
1433   // Load the first byte of the guard variable.
1434   llvm::LoadInst *LI =
1435       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
1436   LI->setAlignment(1);
1437 
1438   // Itanium ABI:
1439   //   An implementation supporting thread-safety on multiprocessor
1440   //   systems must also guarantee that references to the initialized
1441   //   object do not occur before the load of the initialization flag.
1442   //
1443   // In LLVM, we do this by marking the load Acquire.
1444   if (threadsafe)
1445     LI->setAtomic(llvm::Acquire);
1446 
1447   // For ARM, we should only check the first bit, rather than the entire byte:
1448   //
1449   // ARM C++ ABI 3.2.3.1:
1450   //   To support the potential use of initialization guard variables
1451   //   as semaphores that are the target of ARM SWP and LDREX/STREX
1452   //   synchronizing instructions we define a static initialization
1453   //   guard variable to be a 4-byte aligned, 4-byte word with the
1454   //   following inline access protocol.
1455   //     #define INITIALIZED 1
1456   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
1457   //       if (__cxa_guard_acquire(&obj_guard))
1458   //         ...
1459   //     }
1460   //
1461   // and similarly for ARM64:
1462   //
1463   // ARM64 C++ ABI 3.2.2:
1464   //   This ABI instead only specifies the value bit 0 of the static guard
1465   //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
1466   //   variable is not initialized and 1 when it is.
1467   llvm::Value *V =
1468       (UseARMGuardVarABI && !useInt8GuardVariable)
1469           ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1470           : LI;
1471   llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1472 
1473   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1474   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1475 
1476   // Check if the first byte of the guard variable is zero.
1477   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
1478 
1479   CGF.EmitBlock(InitCheckBlock);
1480 
1481   // Variables used when coping with thread-safe statics and exceptions.
1482   if (threadsafe) {
1483     // Call __cxa_guard_acquire.
1484     llvm::Value *V
1485       = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
1486 
1487     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1488 
1489     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1490                          InitBlock, EndBlock);
1491 
1492     // Call __cxa_guard_abort along the exceptional edge.
1493     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
1494 
1495     CGF.EmitBlock(InitBlock);
1496   }
1497 
1498   // Emit the initializer and add a global destructor if appropriate.
1499   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
1500 
1501   if (threadsafe) {
1502     // Pop the guard-abort cleanup if we pushed one.
1503     CGF.PopCleanupBlock();
1504 
1505     // Call __cxa_guard_release.  This cannot throw.
1506     CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
1507   } else {
1508     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
1509   }
1510 
1511   CGF.EmitBlock(EndBlock);
1512 }
1513 
1514 /// Register a global destructor using __cxa_atexit.
1515 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1516                                         llvm::Constant *dtor,
1517                                         llvm::Constant *addr,
1518                                         bool TLS) {
1519   const char *Name = "__cxa_atexit";
1520   if (TLS) {
1521     const llvm::Triple &T = CGF.getTarget().getTriple();
1522     Name = T.isMacOSX() ?  "_tlv_atexit" : "__cxa_thread_atexit";
1523   }
1524 
1525   // We're assuming that the destructor function is something we can
1526   // reasonably call with the default CC.  Go ahead and cast it to the
1527   // right prototype.
1528   llvm::Type *dtorTy =
1529     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1530 
1531   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1532   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1533   llvm::FunctionType *atexitTy =
1534     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1535 
1536   // Fetch the actual function.
1537   llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
1538   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1539     fn->setDoesNotThrow();
1540 
1541   // Create a variable that binds the atexit to this shared object.
1542   llvm::Constant *handle =
1543     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1544 
1545   llvm::Value *args[] = {
1546     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1547     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1548     handle
1549   };
1550   CGF.EmitNounwindRuntimeCall(atexit, args);
1551 }
1552 
1553 /// Register a global destructor as best as we know how.
1554 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1555                                        const VarDecl &D,
1556                                        llvm::Constant *dtor,
1557                                        llvm::Constant *addr) {
1558   // Use __cxa_atexit if available.
1559   if (CGM.getCodeGenOpts().CXAAtExit)
1560     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1561 
1562   if (D.getTLSKind())
1563     CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
1564 
1565   // In Apple kexts, we want to add a global destructor entry.
1566   // FIXME: shouldn't this be guarded by some variable?
1567   if (CGM.getLangOpts().AppleKext) {
1568     // Generate a global destructor entry.
1569     return CGM.AddCXXDtorEntry(dtor, addr);
1570   }
1571 
1572   CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
1573 }
1574 
1575 /// Get the appropriate linkage for the wrapper function. This is essentially
1576 /// the weak form of the variable's linkage; every translation unit which wneeds
1577 /// the wrapper emits a copy, and we want the linker to merge them.
1578 static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1579     llvm::GlobalValue::LinkageTypes VarLinkage) {
1580   // For internal linkage variables, we don't need an external or weak wrapper.
1581   if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1582     return VarLinkage;
1583   return llvm::GlobalValue::WeakODRLinkage;
1584 }
1585 
1586 llvm::Function *
1587 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1588                                              llvm::GlobalVariable *Var) {
1589   // Mangle the name for the thread_local wrapper function.
1590   SmallString<256> WrapperName;
1591   {
1592     llvm::raw_svector_ostream Out(WrapperName);
1593     getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1594     Out.flush();
1595   }
1596 
1597   if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1598     return cast<llvm::Function>(V);
1599 
1600   llvm::Type *RetTy = Var->getType();
1601   if (VD->getType()->isReferenceType())
1602     RetTy = RetTy->getPointerElementType();
1603 
1604   llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1605   llvm::Function *Wrapper = llvm::Function::Create(
1606       FnTy, getThreadLocalWrapperLinkage(
1607                 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
1608       WrapperName.str(), &CGM.getModule());
1609   // Always resolve references to the wrapper at link time.
1610   if (!Wrapper->hasLocalLinkage())
1611     Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1612   return Wrapper;
1613 }
1614 
1615 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1616     llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1617     llvm::Function *InitFunc) {
1618   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1619     const VarDecl *VD = Decls[I].first;
1620     llvm::GlobalVariable *Var = Decls[I].second;
1621 
1622     // Mangle the name for the thread_local initialization function.
1623     SmallString<256> InitFnName;
1624     {
1625       llvm::raw_svector_ostream Out(InitFnName);
1626       getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1627       Out.flush();
1628     }
1629 
1630     // If we have a definition for the variable, emit the initialization
1631     // function as an alias to the global Init function (if any). Otherwise,
1632     // produce a declaration of the initialization function.
1633     llvm::GlobalValue *Init = nullptr;
1634     bool InitIsInitFunc = false;
1635     if (VD->hasDefinition()) {
1636       InitIsInitFunc = true;
1637       if (InitFunc)
1638         Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1639                                          InitFunc);
1640     } else {
1641       // Emit a weak global function referring to the initialization function.
1642       // This function will not exist if the TU defining the thread_local
1643       // variable in question does not need any dynamic initialization for
1644       // its thread_local variables.
1645       llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1646       Init = llvm::Function::Create(
1647           FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1648           &CGM.getModule());
1649     }
1650 
1651     if (Init)
1652       Init->setVisibility(Var->getVisibility());
1653 
1654     llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1655     llvm::LLVMContext &Context = CGM.getModule().getContext();
1656     llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1657     CGBuilderTy Builder(Entry);
1658     if (InitIsInitFunc) {
1659       if (Init)
1660         Builder.CreateCall(Init);
1661     } else {
1662       // Don't know whether we have an init function. Call it if it exists.
1663       llvm::Value *Have = Builder.CreateIsNotNull(Init);
1664       llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1665       llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1666       Builder.CreateCondBr(Have, InitBB, ExitBB);
1667 
1668       Builder.SetInsertPoint(InitBB);
1669       Builder.CreateCall(Init);
1670       Builder.CreateBr(ExitBB);
1671 
1672       Builder.SetInsertPoint(ExitBB);
1673     }
1674 
1675     // For a reference, the result of the wrapper function is a pointer to
1676     // the referenced object.
1677     llvm::Value *Val = Var;
1678     if (VD->getType()->isReferenceType()) {
1679       llvm::LoadInst *LI = Builder.CreateLoad(Val);
1680       LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1681       Val = LI;
1682     }
1683 
1684     Builder.CreateRet(Val);
1685   }
1686 }
1687 
1688 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1689                                                    const VarDecl *VD,
1690                                                    QualType LValType) {
1691   QualType T = VD->getType();
1692   llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1693   llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1694   llvm::Function *Wrapper =
1695       getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1696 
1697   Val = CGF.Builder.CreateCall(Wrapper);
1698 
1699   LValue LV;
1700   if (VD->getType()->isReferenceType())
1701     LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
1702   else
1703     LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
1704   // FIXME: need setObjCGCLValueClass?
1705   return LV;
1706 }
1707 
1708 /// Return whether the given global decl needs a VTT parameter, which it does
1709 /// if it's a base constructor or destructor with virtual bases.
1710 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1711   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1712 
1713   // We don't have any virtual bases, just return early.
1714   if (!MD->getParent()->getNumVBases())
1715     return false;
1716 
1717   // Check if we have a base constructor.
1718   if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1719     return true;
1720 
1721   // Check if we have a base destructor.
1722   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1723     return true;
1724 
1725   return false;
1726 }
1727