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