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