CGCXX.cpp revision b455f0e74be0144ab9738ef574d07bd661959525
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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 contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "Mangle.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "llvm/ADT/StringExtras.h"
26using namespace clang;
27using namespace CodeGen;
28
29void
30CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
31                                               llvm::Constant *DeclPtr) {
32  const llvm::Type *Int8PtrTy =
33    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
34
35  std::vector<const llvm::Type *> Params;
36  Params.push_back(Int8PtrTy);
37
38  // Get the destructor function type
39  const llvm::Type *DtorFnTy =
40    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
41  DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
42
43  Params.clear();
44  Params.push_back(DtorFnTy);
45  Params.push_back(Int8PtrTy);
46  Params.push_back(Int8PtrTy);
47
48  // Get the __cxa_atexit function type
49  // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
50  const llvm::FunctionType *AtExitFnTy =
51    llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
52
53  llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
54                                                       "__cxa_atexit");
55
56  llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
57                                                     "__dso_handle");
58  llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
59                           llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
60                           llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
61  Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
62}
63
64void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
65                                               llvm::Constant *DeclPtr) {
66  assert(D.hasGlobalStorage() &&
67         "VarDecl must have global storage!");
68
69  const Expr *Init = D.getInit();
70  QualType T = D.getType();
71  bool isVolatile = getContext().getCanonicalType(T).isVolatileQualified();
72
73  if (T->isReferenceType()) {
74    ErrorUnsupported(Init, "global variable that binds to a reference");
75  } else if (!hasAggregateLLVMType(T)) {
76    llvm::Value *V = EmitScalarExpr(Init);
77    EmitStoreOfScalar(V, DeclPtr, isVolatile, T);
78  } else if (T->isAnyComplexType()) {
79    EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
80  } else {
81    EmitAggExpr(Init, DeclPtr, isVolatile);
82    // Avoid generating destructor(s) for initialized objects.
83    if (!isa<CXXConstructExpr>(Init))
84      return;
85    const ConstantArrayType *Array = getContext().getAsConstantArrayType(T);
86    if (Array)
87      T = getContext().getBaseElementType(Array);
88
89    if (const RecordType *RT = T->getAs<RecordType>()) {
90      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
91      if (!RD->hasTrivialDestructor()) {
92        llvm::Constant *DtorFn;
93        if (Array) {
94          DtorFn = CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(
95                                                RD->getDestructor(getContext()),
96                                                Array, DeclPtr);
97          DeclPtr =
98            llvm::Constant::getNullValue(llvm::Type::getInt8PtrTy(VMContext));
99        }
100        else
101          DtorFn = CGM.GetAddrOfCXXDestructor(RD->getDestructor(getContext()),
102                                              Dtor_Complete);
103        EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
104      }
105    }
106  }
107}
108
109void
110CodeGenModule::EmitCXXGlobalInitFunc() {
111  if (CXXGlobalInits.empty())
112    return;
113
114  const llvm::FunctionType *FTy
115    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
116                              false);
117
118  // Create our global initialization function.
119  // FIXME: Should this be tweakable by targets?
120  llvm::Function *Fn =
121    llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
122                           "__cxx_global_initialization", &TheModule);
123
124  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
125                                                   &CXXGlobalInits[0],
126                                                   CXXGlobalInits.size());
127  AddGlobalCtor(Fn);
128}
129
130void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
131                                                const VarDecl **Decls,
132                                                unsigned NumDecls) {
133  StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
134                SourceLocation());
135
136  for (unsigned i = 0; i != NumDecls; ++i) {
137    const VarDecl *D = Decls[i];
138
139    llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
140    EmitCXXGlobalVarDeclInit(*D, DeclPtr);
141  }
142  FinishFunction();
143}
144
145void
146CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
147                                               llvm::GlobalVariable *GV) {
148  // FIXME: This should use __cxa_guard_{acquire,release}?
149
150  assert(!getContext().getLangOptions().ThreadsafeStatics &&
151         "thread safe statics are currently not supported!");
152
153  llvm::SmallString<256> GuardVName;
154  CGM.getMangleContext().mangleGuardVariable(&D, GuardVName);
155
156  // Create the guard variable.
157  llvm::GlobalValue *GuardV =
158    new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext),
159                             false, GV->getLinkage(),
160                llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
161                             GuardVName.str());
162
163  // Load the first byte of the guard variable.
164  const llvm::Type *PtrTy
165    = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
166  llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
167                                      "tmp");
168
169  // Compare it against 0.
170  llvm::Value *nullValue
171    = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
172  llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
173
174  llvm::BasicBlock *InitBlock = createBasicBlock("init");
175  llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
176
177  // If the guard variable is 0, jump to the initializer code.
178  Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
179
180  EmitBlock(InitBlock);
181
182  EmitCXXGlobalVarDeclInit(D, GV);
183
184  Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
185                                             1),
186                      Builder.CreateBitCast(GuardV, PtrTy));
187
188  EmitBlock(EndBlock);
189}
190
191RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
192                                          llvm::Value *Callee,
193                                          llvm::Value *This,
194                                          CallExpr::const_arg_iterator ArgBeg,
195                                          CallExpr::const_arg_iterator ArgEnd) {
196  assert(MD->isInstance() &&
197         "Trying to emit a member call expr on a static method!");
198
199  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
200
201  CallArgList Args;
202
203  // Push the this ptr.
204  Args.push_back(std::make_pair(RValue::get(This),
205                                MD->getThisType(getContext())));
206
207  // And the rest of the call args
208  EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
209
210  QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
211  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
212                  Callee, Args, MD);
213}
214
215/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
216/// expr can be devirtualized.
217static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
218  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
219    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
220      // This is a record decl. We know the type and can devirtualize it.
221      return VD->getType()->isRecordType();
222    }
223
224    return false;
225  }
226
227  // We can always devirtualize calls on temporary object expressions.
228  if (isa<CXXTemporaryObjectExpr>(Base))
229    return true;
230
231  // And calls on bound temporaries.
232  if (isa<CXXBindTemporaryExpr>(Base))
233    return true;
234
235  // Check if this is a call expr that returns a record type.
236  if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
237    return CE->getCallReturnType()->isRecordType();
238
239  // We can't devirtualize the call.
240  return false;
241}
242
243RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
244  if (isa<BinaryOperator>(CE->getCallee()))
245    return EmitCXXMemberPointerCallExpr(CE);
246
247  const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
248  const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
249
250  if (MD->isStatic()) {
251    // The method is static, emit it as we would a regular call.
252    llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
253    return EmitCall(Callee, getContext().getPointerType(MD->getType()),
254                    CE->arg_begin(), CE->arg_end(), 0);
255
256  }
257
258  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
259
260  const llvm::Type *Ty =
261    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
262                                   FPT->isVariadic());
263  llvm::Value *This;
264
265  if (ME->isArrow())
266    This = EmitScalarExpr(ME->getBase());
267  else {
268    LValue BaseLV = EmitLValue(ME->getBase());
269    This = BaseLV.getAddress();
270  }
271
272  if (MD->isCopyAssignment() && MD->isTrivial()) {
273    // We don't like to generate the trivial copy assignment operator when
274    // it isn't necessary; just produce the proper effect here.
275    llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
276    EmitAggregateCopy(This, RHS, CE->getType());
277    return RValue::get(This);
278  }
279
280  // C++ [class.virtual]p12:
281  //   Explicit qualification with the scope operator (5.1) suppresses the
282  //   virtual call mechanism.
283  //
284  // We also don't emit a virtual call if the base expression has a record type
285  // because then we know what the type is.
286  llvm::Value *Callee;
287  if (const CXXDestructorDecl *Destructor
288             = dyn_cast<CXXDestructorDecl>(MD)) {
289    if (Destructor->isTrivial())
290      return RValue::get(0);
291    if (MD->isVirtual() && !ME->hasQualifier() &&
292        !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
293      Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty);
294    } else {
295      Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
296    }
297  } else if (MD->isVirtual() && !ME->hasQualifier() &&
298             !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
299    Callee = BuildVirtualCall(MD, This, Ty);
300  } else {
301    Callee = CGM.GetAddrOfFunction(MD, Ty);
302  }
303
304  return EmitCXXMemberCall(MD, Callee, This,
305                           CE->arg_begin(), CE->arg_end());
306}
307
308RValue
309CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) {
310  const BinaryOperator *BO = cast<BinaryOperator>(E->getCallee());
311  const Expr *BaseExpr = BO->getLHS();
312  const Expr *MemFnExpr = BO->getRHS();
313
314  const MemberPointerType *MPT =
315    MemFnExpr->getType()->getAs<MemberPointerType>();
316  const FunctionProtoType *FPT =
317    MPT->getPointeeType()->getAs<FunctionProtoType>();
318  const CXXRecordDecl *RD =
319    cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
320
321  const llvm::FunctionType *FTy =
322    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
323                                   FPT->isVariadic());
324
325  const llvm::Type *Int8PtrTy =
326    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
327
328  // Get the member function pointer.
329  llvm::Value *MemFnPtr =
330    CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn");
331  EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
332
333  // Emit the 'this' pointer.
334  llvm::Value *This;
335
336  if (BO->getOpcode() == BinaryOperator::PtrMemI)
337    This = EmitScalarExpr(BaseExpr);
338  else
339    This = EmitLValue(BaseExpr).getAddress();
340
341  // Adjust it.
342  llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
343  Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
344
345  llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
346  Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
347
348  This = Builder.CreateBitCast(Ptr, This->getType(), "this");
349
350  llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
351
352  const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
353
354  llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
355
356  // If the LSB in the function pointer is 1, the function pointer points to
357  // a virtual function.
358  llvm::Value *IsVirtual
359    = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
360                        "and");
361
362  IsVirtual = Builder.CreateTrunc(IsVirtual,
363                                  llvm::Type::getInt1Ty(VMContext));
364
365  llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
366  llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
367  llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
368
369  Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
370  EmitBlock(FnVirtual);
371
372  const llvm::Type *VTableTy =
373    FTy->getPointerTo()->getPointerTo()->getPointerTo();
374
375  llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy);
376  VTable = Builder.CreateLoad(VTable);
377
378  VTable = Builder.CreateGEP(VTable, FnAsInt, "fn");
379
380  // Since the function pointer is 1 plus the virtual table offset, we
381  // subtract 1 by using a GEP.
382  VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1);
383
384  llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
385
386  EmitBranch(FnEnd);
387  EmitBlock(FnNonVirtual);
388
389  // If the function is not virtual, just load the pointer.
390  llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
391  NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
392
393  EmitBlock(FnEnd);
394
395  llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
396  Callee->reserveOperandSpace(2);
397  Callee->addIncoming(VirtualFn, FnVirtual);
398  Callee->addIncoming(NonVirtualFn, FnNonVirtual);
399
400  CallArgList Args;
401
402  QualType ThisType =
403    getContext().getPointerType(getContext().getTagDeclType(RD));
404
405  // Push the this ptr.
406  Args.push_back(std::make_pair(RValue::get(This), ThisType));
407
408  // And the rest of the call args
409  EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
410  QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType();
411  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
412                  Callee, Args, 0);
413}
414
415RValue
416CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
417                                               const CXXMethodDecl *MD) {
418  assert(MD->isInstance() &&
419         "Trying to emit a member call expr on a static method!");
420
421  if (MD->isCopyAssignment()) {
422    const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
423    if (ClassDecl->hasTrivialCopyAssignment()) {
424      assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
425             "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
426      llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
427      llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
428      QualType Ty = E->getType();
429      EmitAggregateCopy(This, Src, Ty);
430      return RValue::get(This);
431    }
432  }
433
434  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
435  const llvm::Type *Ty =
436    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
437                                   FPT->isVariadic());
438
439  llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
440
441  llvm::Value *Callee;
442  if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0)))
443    Callee = BuildVirtualCall(MD, This, Ty);
444  else
445    Callee = CGM.GetAddrOfFunction(MD, Ty);
446
447  return EmitCXXMemberCall(MD, Callee, This,
448                           E->arg_begin() + 1, E->arg_end());
449}
450
451llvm::Value *CodeGenFunction::LoadCXXThis() {
452  assert(isa<CXXMethodDecl>(CurFuncDecl) &&
453         "Must be in a C++ member function decl to load 'this'");
454  assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
455         "Must be in a C++ member function decl to load 'this'");
456
457  // FIXME: What if we're inside a block?
458  // ans: See how CodeGenFunction::LoadObjCSelf() uses
459  // CodeGenFunction::BlockForwardSelf() for how to do this.
460  return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
461}
462
463/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
464/// for-loop to call the default constructor on individual members of the
465/// array.
466/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
467/// array type and 'ArrayPtr' points to the beginning fo the array.
468/// It is assumed that all relevant checks have been made by the caller.
469void
470CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
471                                          const ConstantArrayType *ArrayTy,
472                                          llvm::Value *ArrayPtr,
473                                          CallExpr::const_arg_iterator ArgBeg,
474                                          CallExpr::const_arg_iterator ArgEnd) {
475
476  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
477  llvm::Value * NumElements =
478    llvm::ConstantInt::get(SizeTy,
479                           getContext().getConstantArrayElementCount(ArrayTy));
480
481  EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
482}
483
484void
485CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
486                                          llvm::Value *NumElements,
487                                          llvm::Value *ArrayPtr,
488                                          CallExpr::const_arg_iterator ArgBeg,
489                                          CallExpr::const_arg_iterator ArgEnd) {
490  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
491
492  // Create a temporary for the loop index and initialize it with 0.
493  llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
494  llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
495  Builder.CreateStore(Zero, IndexPtr);
496
497  // Start the loop with a block that tests the condition.
498  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
499  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
500
501  EmitBlock(CondBlock);
502
503  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
504
505  // Generate: if (loop-index < number-of-elements fall to the loop body,
506  // otherwise, go to the block after the for-loop.
507  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
508  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
509  // If the condition is true, execute the body.
510  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
511
512  EmitBlock(ForBody);
513
514  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
515  // Inside the loop body, emit the constructor call on the array element.
516  Counter = Builder.CreateLoad(IndexPtr);
517  llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
518                                                   "arrayidx");
519
520  // C++ [class.temporary]p4:
521  // There are two contexts in which temporaries are destroyed at a different
522  // point than the end of the full- expression. The first context is when a
523  // default constructor is called to initialize an element of an array.
524  // If the constructor has one or more default arguments, the destruction of
525  // every temporary created in a default argument expression is sequenced
526  // before the construction of the next array element, if any.
527
528  // Keep track of the current number of live temporaries.
529  unsigned OldNumLiveTemporaries = LiveTemporaries.size();
530
531  EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
532
533  // Pop temporaries.
534  while (LiveTemporaries.size() > OldNumLiveTemporaries)
535    PopCXXTemporary();
536
537  EmitBlock(ContinueBlock);
538
539  // Emit the increment of the loop counter.
540  llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
541  Counter = Builder.CreateLoad(IndexPtr);
542  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
543  Builder.CreateStore(NextVal, IndexPtr);
544
545  // Finally, branch back up to the condition for the next iteration.
546  EmitBranch(CondBlock);
547
548  // Emit the fall-through block.
549  EmitBlock(AfterFor, true);
550}
551
552/// EmitCXXAggrDestructorCall - calls the default destructor on array
553/// elements in reverse order of construction.
554void
555CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
556                                           const ArrayType *Array,
557                                           llvm::Value *This) {
558  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
559  assert(CA && "Do we support VLA for destruction ?");
560  uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
561  llvm::Value* ElementCountPtr =
562    llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
563  EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
564}
565
566/// EmitCXXAggrDestructorCall - calls the default destructor on array
567/// elements in reverse order of construction.
568void
569CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
570                                           llvm::Value *UpperCount,
571                                           llvm::Value *This) {
572  llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
573                                            1);
574  // Create a temporary for the loop index and initialize it with count of
575  // array elements.
576  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
577                                           "loop.index");
578  // Index = ElementCount;
579  Builder.CreateStore(UpperCount, IndexPtr);
580
581  // Start the loop with a block that tests the condition.
582  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
583  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
584
585  EmitBlock(CondBlock);
586
587  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
588
589  // Generate: if (loop-index != 0 fall to the loop body,
590  // otherwise, go to the block after the for-loop.
591  llvm::Value* zeroConstant =
592    llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
593  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
594  llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
595                                            "isne");
596  // If the condition is true, execute the body.
597  Builder.CreateCondBr(IsNE, ForBody, AfterFor);
598
599  EmitBlock(ForBody);
600
601  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
602  // Inside the loop body, emit the constructor call on the array element.
603  Counter = Builder.CreateLoad(IndexPtr);
604  Counter = Builder.CreateSub(Counter, One);
605  llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
606  EmitCXXDestructorCall(D, Dtor_Complete, Address);
607
608  EmitBlock(ContinueBlock);
609
610  // Emit the decrement of the loop counter.
611  Counter = Builder.CreateLoad(IndexPtr);
612  Counter = Builder.CreateSub(Counter, One, "dec");
613  Builder.CreateStore(Counter, IndexPtr);
614
615  // Finally, branch back up to the condition for the next iteration.
616  EmitBranch(CondBlock);
617
618  // Emit the fall-through block.
619  EmitBlock(AfterFor, true);
620}
621
622/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
623/// invoked, calls the default destructor on array elements in reverse order of
624/// construction.
625llvm::Constant *
626CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
627                                                 const ArrayType *Array,
628                                                 llvm::Value *This) {
629  static int UniqueCount;
630  FunctionArgList Args;
631  ImplicitParamDecl *Dst =
632    ImplicitParamDecl::Create(getContext(), 0,
633                              SourceLocation(), 0,
634                              getContext().getPointerType(getContext().VoidTy));
635  Args.push_back(std::make_pair(Dst, Dst->getType()));
636
637  llvm::SmallString<16> Name;
638  llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueCount);
639  QualType R = getContext().VoidTy;
640  const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
641  const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
642  llvm::Function *Fn =
643    llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
644                           Name.c_str(),
645                           &CGM.getModule());
646  IdentifierInfo *II
647    = &CGM.getContext().Idents.get(Name.c_str());
648  FunctionDecl *FD = FunctionDecl::Create(getContext(),
649                                          getContext().getTranslationUnitDecl(),
650                                          SourceLocation(), II, R, 0,
651                                          FunctionDecl::Static,
652                                          false, true);
653  StartFunction(FD, R, Fn, Args, SourceLocation());
654  QualType BaseElementTy = getContext().getBaseElementType(Array);
655  const llvm::Type *BasePtr = ConvertType(BaseElementTy);
656  BasePtr = llvm::PointerType::getUnqual(BasePtr);
657  llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
658  EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
659  FinishFunction();
660  llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
661                                              0);
662  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
663  return m;
664}
665
666void
667CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
668                                        CXXCtorType Type,
669                                        llvm::Value *This,
670                                        CallExpr::const_arg_iterator ArgBeg,
671                                        CallExpr::const_arg_iterator ArgEnd) {
672  if (D->isCopyConstructor(getContext())) {
673    const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
674    if (ClassDecl->hasTrivialCopyConstructor()) {
675      assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
676             "EmitCXXConstructorCall - user declared copy constructor");
677      const Expr *E = (*ArgBeg);
678      QualType Ty = E->getType();
679      llvm::Value *Src = EmitLValue(E).getAddress();
680      EmitAggregateCopy(This, Src, Ty);
681      return;
682    }
683  } else if (D->isTrivial()) {
684    // FIXME: Track down why we're trying to generate calls to the trivial
685    // default constructor!
686    return;
687  }
688
689  llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
690
691  EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
692}
693
694void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
695                                            CXXDtorType Type,
696                                            llvm::Value *This) {
697  llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
698
699  CallArgList Args;
700
701  // Push the this ptr.
702  Args.push_back(std::make_pair(RValue::get(This),
703                                DD->getThisType(getContext())));
704
705  // Add a VTT parameter if necessary.
706  // FIXME: This should not be a dummy null parameter!
707  if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) {
708    QualType T = getContext().getPointerType(getContext().VoidPtrTy);
709
710    Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T));
711  }
712
713  // FIXME: We should try to share this code with EmitCXXMemberCall.
714
715  QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType();
716  EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD);
717}
718
719void
720CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
721                                      const CXXConstructExpr *E) {
722  assert(Dest && "Must have a destination!");
723  const CXXConstructorDecl *CD = E->getConstructor();
724  const ConstantArrayType *Array =
725    getContext().getAsConstantArrayType(E->getType());
726  // For a copy constructor, even if it is trivial, must fall thru so
727  // its argument is code-gen'ed.
728  if (!CD->isCopyConstructor(getContext())) {
729    QualType InitType = E->getType();
730    if (Array)
731      InitType = getContext().getBaseElementType(Array);
732    const CXXRecordDecl *RD =
733      cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
734    if (RD->hasTrivialConstructor())
735    return;
736  }
737  // Code gen optimization to eliminate copy constructor and return
738  // its first argument instead.
739  if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
740    const Expr *Arg = E->getArg(0);
741
742    if (const CXXBindTemporaryExpr *BindExpr =
743          dyn_cast<CXXBindTemporaryExpr>(Arg))
744      Arg = BindExpr->getSubExpr();
745
746    EmitAggExpr(Arg, Dest, false);
747    return;
748  }
749  if (Array) {
750    QualType BaseElementTy = getContext().getBaseElementType(Array);
751    const llvm::Type *BasePtr = ConvertType(BaseElementTy);
752    BasePtr = llvm::PointerType::getUnqual(BasePtr);
753    llvm::Value *BaseAddrPtr =
754      Builder.CreateBitCast(Dest, BasePtr);
755    EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
756                               E->arg_begin(), E->arg_end());
757  }
758  else
759    // Call the constructor.
760    EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
761                           E->arg_begin(), E->arg_end());
762}
763
764void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
765  EmitGlobal(GlobalDecl(D, Ctor_Complete));
766  EmitGlobal(GlobalDecl(D, Ctor_Base));
767}
768
769void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
770                                       CXXCtorType Type) {
771
772  llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
773
774  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
775
776  SetFunctionDefinitionAttributes(D, Fn);
777  SetLLVMFunctionAttributesForDefinition(D, Fn);
778}
779
780llvm::Function *
781CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
782                                       CXXCtorType Type) {
783  const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
784  const llvm::FunctionType *FTy =
785    getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
786                               FPT->isVariadic());
787
788  const char *Name = getMangledCXXCtorName(D, Type);
789  return cast<llvm::Function>(
790                      GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
791}
792
793const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
794                                                 CXXCtorType Type) {
795  llvm::SmallString<256> Name;
796  getMangleContext().mangleCXXCtor(D, Type, Name);
797
798  Name += '\0';
799  return UniqueMangledName(Name.begin(), Name.end());
800}
801
802void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
803  if (D->isVirtual())
804    EmitGlobalDefinition(GlobalDecl(D, Dtor_Deleting));
805  EmitGlobalDefinition(GlobalDecl(D, Dtor_Complete));
806  EmitGlobalDefinition(GlobalDecl(D, Dtor_Base));
807}
808
809void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
810                                      CXXDtorType Type) {
811  llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
812
813  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
814
815  SetFunctionDefinitionAttributes(D, Fn);
816  SetLLVMFunctionAttributesForDefinition(D, Fn);
817}
818
819llvm::Function *
820CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
821                                      CXXDtorType Type) {
822  const llvm::FunctionType *FTy =
823    getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
824
825  const char *Name = getMangledCXXDtorName(D, Type);
826  return cast<llvm::Function>(
827                      GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
828}
829
830const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
831                                                 CXXDtorType Type) {
832  llvm::SmallString<256> Name;
833  getMangleContext().mangleCXXDtor(D, Type, Name);
834
835  Name += '\0';
836  return UniqueMangledName(Name.begin(), Name.end());
837}
838
839llvm::Constant *
840CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
841                               bool Extern,
842                               const ThunkAdjustment &ThisAdjustment) {
843  return GenerateCovariantThunk(Fn, GD, Extern,
844                                CovariantThunkAdjustment(ThisAdjustment,
845                                                         ThunkAdjustment()));
846}
847
848llvm::Value *
849CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
850                                   const ThunkAdjustment &Adjustment) {
851  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
852
853  const llvm::Type *OrigTy = V->getType();
854  if (Adjustment.NonVirtual) {
855    // Do the non-virtual adjustment
856    V = Builder.CreateBitCast(V, Int8PtrTy);
857    V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
858    V = Builder.CreateBitCast(V, OrigTy);
859  }
860
861  if (!Adjustment.Virtual)
862    return V;
863
864  assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
865         "vtable entry unaligned");
866
867  // Do the virtual this adjustment
868  const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
869  const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
870
871  llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
872  V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
873  V = Builder.CreateLoad(V, "vtable");
874
875  llvm::Value *VTablePtr = V;
876  uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
877  V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
878  V = Builder.CreateLoad(V);
879  V = Builder.CreateGEP(ThisVal, V);
880
881  return Builder.CreateBitCast(V, OrigTy);
882}
883
884llvm::Constant *
885CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
886                                   GlobalDecl GD, bool Extern,
887                                   const CovariantThunkAdjustment &Adjustment) {
888  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
889  QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
890
891  FunctionArgList Args;
892  ImplicitParamDecl *ThisDecl =
893    ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
894                              MD->getThisType(getContext()));
895  Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
896  for (FunctionDecl::param_const_iterator i = MD->param_begin(),
897         e = MD->param_end();
898       i != e; ++i) {
899    ParmVarDecl *D = *i;
900    Args.push_back(std::make_pair(D, D->getType()));
901  }
902  IdentifierInfo *II
903    = &CGM.getContext().Idents.get("__thunk_named_foo_");
904  FunctionDecl *FD = FunctionDecl::Create(getContext(),
905                                          getContext().getTranslationUnitDecl(),
906                                          SourceLocation(), II, ResultType, 0,
907                                          Extern
908                                            ? FunctionDecl::Extern
909                                            : FunctionDecl::Static,
910                                          false, true);
911  StartFunction(FD, ResultType, Fn, Args, SourceLocation());
912
913  // generate body
914  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
915  const llvm::Type *Ty =
916    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
917                                   FPT->isVariadic());
918  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
919
920  CallArgList CallArgs;
921
922  bool ShouldAdjustReturnPointer = true;
923  QualType ArgType = MD->getThisType(getContext());
924  llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
925  if (!Adjustment.ThisAdjustment.isEmpty()) {
926    // Do the this adjustment.
927    const llvm::Type *OrigTy = Callee->getType();
928    Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
929
930    if (!Adjustment.ReturnAdjustment.isEmpty()) {
931      const CovariantThunkAdjustment &ReturnAdjustment =
932        CovariantThunkAdjustment(ThunkAdjustment(),
933                                 Adjustment.ReturnAdjustment);
934
935      Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
936
937      Callee = Builder.CreateBitCast(Callee, OrigTy);
938      ShouldAdjustReturnPointer = false;
939    }
940  }
941
942  CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
943
944  for (FunctionDecl::param_const_iterator i = MD->param_begin(),
945         e = MD->param_end();
946       i != e; ++i) {
947    ParmVarDecl *D = *i;
948    QualType ArgType = D->getType();
949
950    // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
951    Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
952                                               SourceLocation());
953    CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
954  }
955
956  RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
957                       Callee, CallArgs, MD);
958  if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
959    bool CanBeZero = !(ResultType->isReferenceType()
960    // FIXME: attr nonnull can't be zero either
961                       /* || ResultType->hasAttr<NonNullAttr>() */ );
962    // Do the return result adjustment.
963    if (CanBeZero) {
964      llvm::BasicBlock *NonZeroBlock = createBasicBlock();
965      llvm::BasicBlock *ZeroBlock = createBasicBlock();
966      llvm::BasicBlock *ContBlock = createBasicBlock();
967
968      const llvm::Type *Ty = RV.getScalarVal()->getType();
969      llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
970      Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
971                           NonZeroBlock, ZeroBlock);
972      EmitBlock(NonZeroBlock);
973      llvm::Value *NZ =
974        DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
975      EmitBranch(ContBlock);
976      EmitBlock(ZeroBlock);
977      llvm::Value *Z = RV.getScalarVal();
978      EmitBlock(ContBlock);
979      llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
980      RVOrZero->reserveOperandSpace(2);
981      RVOrZero->addIncoming(NZ, NonZeroBlock);
982      RVOrZero->addIncoming(Z, ZeroBlock);
983      RV = RValue::get(RVOrZero);
984    } else
985      RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
986                                         Adjustment.ReturnAdjustment));
987  }
988
989  if (!ResultType->isVoidType())
990    EmitReturnOfRValue(RV, ResultType);
991
992  FinishFunction();
993  return Fn;
994}
995
996llvm::Constant *
997CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
998                              const ThunkAdjustment &ThisAdjustment) {
999  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1000
1001  // Compute mangled name
1002  llvm::SmallString<256> OutName;
1003  if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
1004    getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
1005                                          OutName);
1006  else
1007    getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
1008  OutName += '\0';
1009  const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
1010
1011  // Get function for mangled name
1012  const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
1013  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1014}
1015
1016llvm::Constant *
1017CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
1018                                   const CovariantThunkAdjustment &Adjustment) {
1019  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1020
1021  // Compute mangled name
1022  llvm::SmallString<256> OutName;
1023  getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
1024  OutName += '\0';
1025  const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
1026
1027  // Get function for mangled name
1028  const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
1029  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1030}
1031
1032void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
1033  CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
1034  if (!AdjPtr)
1035    return;
1036  CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
1037  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1038  for (unsigned i = 0; i < Adj.size(); i++) {
1039    GlobalDecl OGD = Adj[i].first;
1040    const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
1041    QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
1042    CanQualType oret = getContext().getCanonicalType(nc_oret);
1043    QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
1044    CanQualType ret = getContext().getCanonicalType(nc_ret);
1045    ThunkAdjustment ReturnAdjustment;
1046    if (oret != ret) {
1047      QualType qD = nc_ret->getPointeeType();
1048      QualType qB = nc_oret->getPointeeType();
1049      CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
1050      CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
1051      ReturnAdjustment = ComputeThunkAdjustment(D, B);
1052    }
1053    ThunkAdjustment ThisAdjustment = Adj[i].second;
1054    bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
1055    if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
1056      CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
1057      llvm::Constant *FnConst;
1058      if (!ReturnAdjustment.isEmpty())
1059        FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
1060      else
1061        FnConst = GetAddrOfThunk(GD, ThisAdjustment);
1062      if (!isa<llvm::Function>(FnConst)) {
1063        llvm::Constant *SubExpr =
1064            cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
1065        llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
1066        std::string Name = OldFn->getNameStr();
1067        GlobalDeclMap.erase(UniqueMangledName(Name.data(),
1068                                              Name.data() + Name.size() + 1));
1069        llvm::Constant *NewFnConst;
1070        if (!ReturnAdjustment.isEmpty())
1071          NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
1072        else
1073          NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
1074        llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
1075        NewFn->takeName(OldFn);
1076        llvm::Constant *NewPtrForOldDecl =
1077            llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
1078        OldFn->replaceAllUsesWith(NewPtrForOldDecl);
1079        OldFn->eraseFromParent();
1080        FnConst = NewFn;
1081      }
1082      llvm::Function *Fn = cast<llvm::Function>(FnConst);
1083      if (Fn->isDeclaration()) {
1084        llvm::GlobalVariable::LinkageTypes linktype;
1085        linktype = llvm::GlobalValue::WeakAnyLinkage;
1086        if (!Extern)
1087          linktype = llvm::GlobalValue::InternalLinkage;
1088        Fn->setLinkage(linktype);
1089        if (!Features.Exceptions && !Features.ObjCNonFragileABI)
1090          Fn->addFnAttr(llvm::Attribute::NoUnwind);
1091        Fn->setAlignment(2);
1092        CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
1093      }
1094    }
1095  }
1096}
1097
1098llvm::Constant *
1099CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
1100                          const ThunkAdjustment &ThisAdjustment) {
1101  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1102  llvm::SmallString<256> OutName;
1103  if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
1104    getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
1105                                          OutName);
1106  } else
1107    getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
1108
1109  llvm::GlobalVariable::LinkageTypes linktype;
1110  linktype = llvm::GlobalValue::WeakAnyLinkage;
1111  if (!Extern)
1112    linktype = llvm::GlobalValue::InternalLinkage;
1113  llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1114  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1115  const llvm::FunctionType *FTy =
1116    getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1117                               FPT->isVariadic());
1118
1119  llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
1120                                              &getModule());
1121  CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
1122  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1123  return m;
1124}
1125
1126llvm::Constant *
1127CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
1128                                   const CovariantThunkAdjustment &Adjustment) {
1129  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1130  llvm::SmallString<256> OutName;
1131  getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
1132  llvm::GlobalVariable::LinkageTypes linktype;
1133  linktype = llvm::GlobalValue::WeakAnyLinkage;
1134  if (!Extern)
1135    linktype = llvm::GlobalValue::InternalLinkage;
1136  llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1137  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1138  const llvm::FunctionType *FTy =
1139    getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1140                               FPT->isVariadic());
1141
1142  llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
1143                                              &getModule());
1144  CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
1145  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1146  return m;
1147}
1148
1149llvm::Value *
1150CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
1151                                              const CXXRecordDecl *ClassDecl,
1152                                           const CXXRecordDecl *BaseClassDecl) {
1153  const llvm::Type *Int8PtrTy =
1154    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1155
1156  llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1157                                                 Int8PtrTy->getPointerTo());
1158  VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1159
1160  int64_t VBaseOffsetIndex =
1161    CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1162
1163  llvm::Value *VBaseOffsetPtr =
1164    Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
1165  const llvm::Type *PtrDiffTy =
1166    ConvertType(getContext().getPointerDiffType());
1167
1168  VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1169                                         PtrDiffTy->getPointerTo());
1170
1171  llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1172
1173  return VBaseOffset;
1174}
1175
1176static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
1177                                     llvm::Value *This, const llvm::Type *Ty) {
1178  Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
1179
1180  llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1181  Vtable = CGF.Builder.CreateLoad(Vtable);
1182
1183  llvm::Value *VFuncPtr =
1184    CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1185  return CGF.Builder.CreateLoad(VFuncPtr);
1186}
1187
1188llvm::Value *
1189CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1190                                  const llvm::Type *Ty) {
1191  MD = MD->getCanonicalDecl();
1192  uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
1193
1194  return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1195}
1196
1197llvm::Value *
1198CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1199                                  llvm::Value *&This, const llvm::Type *Ty) {
1200  DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
1201  uint64_t VtableIndex =
1202    CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
1203
1204  return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1205}
1206
1207/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1208/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1209/// copy or via a copy constructor call.
1210//  FIXME. Consolidate this with EmitCXXAggrConstructorCall.
1211void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1212                                            llvm::Value *Src,
1213                                            const ArrayType *Array,
1214                                            const CXXRecordDecl *BaseClassDecl,
1215                                            QualType Ty) {
1216  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1217  assert(CA && "VLA cannot be copied over");
1218  bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1219
1220  // Create a temporary for the loop index and initialize it with 0.
1221  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1222                                           "loop.index");
1223  llvm::Value* zeroConstant =
1224    llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1225  Builder.CreateStore(zeroConstant, IndexPtr);
1226  // Start the loop with a block that tests the condition.
1227  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1228  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1229
1230  EmitBlock(CondBlock);
1231
1232  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1233  // Generate: if (loop-index < number-of-elements fall to the loop body,
1234  // otherwise, go to the block after the for-loop.
1235  uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1236  llvm::Value * NumElementsPtr =
1237    llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1238  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1239  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1240                                              "isless");
1241  // If the condition is true, execute the body.
1242  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1243
1244  EmitBlock(ForBody);
1245  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1246  // Inside the loop body, emit the constructor call on the array element.
1247  Counter = Builder.CreateLoad(IndexPtr);
1248  Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1249  Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1250  if (BitwiseCopy)
1251    EmitAggregateCopy(Dest, Src, Ty);
1252  else if (CXXConstructorDecl *BaseCopyCtor =
1253           BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1254    llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1255                                                      Ctor_Complete);
1256    CallArgList CallArgs;
1257    // Push the this (Dest) ptr.
1258    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1259                                      BaseCopyCtor->getThisType(getContext())));
1260
1261    // Push the Src ptr.
1262    CallArgs.push_back(std::make_pair(RValue::get(Src),
1263                                     BaseCopyCtor->getParamDecl(0)->getType()));
1264    QualType ResultType =
1265      BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
1266    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1267             Callee, CallArgs, BaseCopyCtor);
1268  }
1269  EmitBlock(ContinueBlock);
1270
1271  // Emit the increment of the loop counter.
1272  llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1273  Counter = Builder.CreateLoad(IndexPtr);
1274  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1275  Builder.CreateStore(NextVal, IndexPtr);
1276
1277  // Finally, branch back up to the condition for the next iteration.
1278  EmitBranch(CondBlock);
1279
1280  // Emit the fall-through block.
1281  EmitBlock(AfterFor, true);
1282}
1283
1284/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1285/// array of objects from SrcValue to DestValue. Assignment can be either a
1286/// bitwise assignment or via a copy assignment operator function call.
1287/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1288void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1289                                            llvm::Value *Src,
1290                                            const ArrayType *Array,
1291                                            const CXXRecordDecl *BaseClassDecl,
1292                                            QualType Ty) {
1293  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1294  assert(CA && "VLA cannot be asssigned");
1295  bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1296
1297  // Create a temporary for the loop index and initialize it with 0.
1298  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1299                                           "loop.index");
1300  llvm::Value* zeroConstant =
1301  llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1302  Builder.CreateStore(zeroConstant, IndexPtr);
1303  // Start the loop with a block that tests the condition.
1304  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1305  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1306
1307  EmitBlock(CondBlock);
1308
1309  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1310  // Generate: if (loop-index < number-of-elements fall to the loop body,
1311  // otherwise, go to the block after the for-loop.
1312  uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1313  llvm::Value * NumElementsPtr =
1314  llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1315  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1316  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1317                                              "isless");
1318  // If the condition is true, execute the body.
1319  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1320
1321  EmitBlock(ForBody);
1322  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1323  // Inside the loop body, emit the assignment operator call on array element.
1324  Counter = Builder.CreateLoad(IndexPtr);
1325  Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1326  Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1327  const CXXMethodDecl *MD = 0;
1328  if (BitwiseAssign)
1329    EmitAggregateCopy(Dest, Src, Ty);
1330  else {
1331    bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1332                                                               MD);
1333    assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1334    (void)hasCopyAssign;
1335    const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1336    const llvm::Type *LTy =
1337    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1338                                   FPT->isVariadic());
1339    llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
1340
1341    CallArgList CallArgs;
1342    // Push the this (Dest) ptr.
1343    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1344                                      MD->getThisType(getContext())));
1345
1346    // Push the Src ptr.
1347    CallArgs.push_back(std::make_pair(RValue::get(Src),
1348                                      MD->getParamDecl(0)->getType()));
1349    QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
1350    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1351             Callee, CallArgs, MD);
1352  }
1353  EmitBlock(ContinueBlock);
1354
1355  // Emit the increment of the loop counter.
1356  llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1357  Counter = Builder.CreateLoad(IndexPtr);
1358  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1359  Builder.CreateStore(NextVal, IndexPtr);
1360
1361  // Finally, branch back up to the condition for the next iteration.
1362  EmitBranch(CondBlock);
1363
1364  // Emit the fall-through block.
1365  EmitBlock(AfterFor, true);
1366}
1367
1368/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1369/// object from SrcValue to DestValue. Copying can be either a bitwise copy
1370/// or via a copy constructor call.
1371void CodeGenFunction::EmitClassMemberwiseCopy(
1372                        llvm::Value *Dest, llvm::Value *Src,
1373                        const CXXRecordDecl *ClassDecl,
1374                        const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1375  if (ClassDecl) {
1376    Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1377                                 /*NullCheckValue=*/false);
1378    Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1379                                /*NullCheckValue=*/false);
1380  }
1381  if (BaseClassDecl->hasTrivialCopyConstructor()) {
1382    EmitAggregateCopy(Dest, Src, Ty);
1383    return;
1384  }
1385
1386  if (CXXConstructorDecl *BaseCopyCtor =
1387      BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1388    llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1389                                                      Ctor_Complete);
1390    CallArgList CallArgs;
1391    // Push the this (Dest) ptr.
1392    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1393                                      BaseCopyCtor->getThisType(getContext())));
1394
1395    // Push the Src ptr.
1396    CallArgs.push_back(std::make_pair(RValue::get(Src),
1397                       BaseCopyCtor->getParamDecl(0)->getType()));
1398    QualType ResultType =
1399    BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
1400    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1401             Callee, CallArgs, BaseCopyCtor);
1402  }
1403}
1404
1405/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1406/// object from SrcValue to DestValue. Assignment can be either a bitwise
1407/// assignment of via an assignment operator call.
1408// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
1409void CodeGenFunction::EmitClassCopyAssignment(
1410                                        llvm::Value *Dest, llvm::Value *Src,
1411                                        const CXXRecordDecl *ClassDecl,
1412                                        const CXXRecordDecl *BaseClassDecl,
1413                                        QualType Ty) {
1414  if (ClassDecl) {
1415    Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1416                                 /*NullCheckValue=*/false);
1417    Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1418                                /*NullCheckValue=*/false);
1419  }
1420  if (BaseClassDecl->hasTrivialCopyAssignment()) {
1421    EmitAggregateCopy(Dest, Src, Ty);
1422    return;
1423  }
1424
1425  const CXXMethodDecl *MD = 0;
1426  bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1427                                                                 MD);
1428  assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1429  (void)ConstCopyAssignOp;
1430
1431  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1432  const llvm::Type *LTy =
1433    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1434                                   FPT->isVariadic());
1435  llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
1436
1437  CallArgList CallArgs;
1438  // Push the this (Dest) ptr.
1439  CallArgs.push_back(std::make_pair(RValue::get(Dest),
1440                                    MD->getThisType(getContext())));
1441
1442  // Push the Src ptr.
1443  CallArgs.push_back(std::make_pair(RValue::get(Src),
1444                                    MD->getParamDecl(0)->getType()));
1445  QualType ResultType =
1446    MD->getType()->getAs<FunctionType>()->getResultType();
1447  EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1448           Callee, CallArgs, MD);
1449}
1450
1451/// SynthesizeDefaultConstructor - synthesize a default constructor
1452void
1453CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1454                                              CXXCtorType Type,
1455                                              llvm::Function *Fn,
1456                                              const FunctionArgList &Args) {
1457  assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
1458  StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1459                SourceLocation());
1460  EmitCtorPrologue(Ctor, Type);
1461  FinishFunction();
1462}
1463
1464/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1465/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
1466/// The implicitly-defined copy constructor for class X performs a memberwise
1467/// copy of its subobjects. The order of copying is the same as the order of
1468/// initialization of bases and members in a user-defined constructor
1469/// Each subobject is copied in the manner appropriate to its type:
1470///  if the subobject is of class type, the copy constructor for the class is
1471///  used;
1472///  if the subobject is an array, each element is copied, in the manner
1473///  appropriate to the element type;
1474///  if the subobject is of scalar type, the built-in assignment operator is
1475///  used.
1476/// Virtual base class subobjects shall be copied only once by the
1477/// implicitly-defined copy constructor
1478
1479void
1480CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1481                                              CXXCtorType Type,
1482                                              llvm::Function *Fn,
1483                                              const FunctionArgList &Args) {
1484  const CXXRecordDecl *ClassDecl = Ctor->getParent();
1485  assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
1486      "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1487  assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
1488  StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1489                SourceLocation());
1490
1491  FunctionArgList::const_iterator i = Args.begin();
1492  const VarDecl *ThisArg = i->first;
1493  llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1494  llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1495  const VarDecl *SrcArg = (i+1)->first;
1496  llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1497  llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1498
1499  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1500       Base != ClassDecl->bases_end(); ++Base) {
1501    // FIXME. copy constrution of virtual base NYI
1502    if (Base->isVirtual())
1503      continue;
1504
1505    CXXRecordDecl *BaseClassDecl
1506      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1507    EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1508                            Base->getType());
1509  }
1510
1511  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1512       E = ClassDecl->field_end(); I != E; ++I) {
1513    const FieldDecl *Field = *I;
1514
1515    QualType FieldType = getContext().getCanonicalType(Field->getType());
1516    const ConstantArrayType *Array =
1517      getContext().getAsConstantArrayType(FieldType);
1518    if (Array)
1519      FieldType = getContext().getBaseElementType(FieldType);
1520
1521    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1522      CXXRecordDecl *FieldClassDecl
1523        = cast<CXXRecordDecl>(FieldClassType->getDecl());
1524      LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1525      LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1526      if (Array) {
1527        const llvm::Type *BasePtr = ConvertType(FieldType);
1528        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1529        llvm::Value *DestBaseAddrPtr =
1530          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1531        llvm::Value *SrcBaseAddrPtr =
1532          Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1533        EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1534                                    FieldClassDecl, FieldType);
1535      }
1536      else
1537        EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1538                                0 /*ClassDecl*/, FieldClassDecl, FieldType);
1539      continue;
1540    }
1541
1542    if (Field->getType()->isReferenceType()) {
1543      unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1544
1545      llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1546                                                 "lhs.ref");
1547
1548      llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1549                                                 "rhs.ref");
1550
1551      // Load the value in RHS.
1552      RHS = Builder.CreateLoad(RHS);
1553
1554      // And store it in the LHS
1555      Builder.CreateStore(RHS, LHS);
1556
1557      continue;
1558    }
1559    // Do a built-in assignment of scalar data members.
1560    LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1561    LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1562
1563    if (!hasAggregateLLVMType(Field->getType())) {
1564      RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1565      EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1566    } else if (Field->getType()->isAnyComplexType()) {
1567      ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1568                                               RHS.isVolatileQualified());
1569      StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1570    } else {
1571      EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1572    }
1573  }
1574  FinishFunction();
1575}
1576
1577/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1578/// Before the implicitly-declared copy assignment operator for a class is
1579/// implicitly defined, all implicitly- declared copy assignment operators for
1580/// its direct base classes and its nonstatic data members shall have been
1581/// implicitly defined. [12.8-p12]
1582/// The implicitly-defined copy assignment operator for class X performs
1583/// memberwise assignment of its subob- jects. The direct base classes of X are
1584/// assigned first, in the order of their declaration in
1585/// the base-specifier-list, and then the immediate nonstatic data members of X
1586/// are assigned, in the order in which they were declared in the class
1587/// definition.Each subobject is assigned in the manner appropriate to its type:
1588///   if the subobject is of class type, the copy assignment operator for the
1589///   class is used (as if by explicit qualification; that is, ignoring any
1590///   possible virtual overriding functions in more derived classes);
1591///
1592///   if the subobject is an array, each element is assigned, in the manner
1593///   appropriate to the element type;
1594///
1595///   if the subobject is of scalar type, the built-in assignment operator is
1596///   used.
1597void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1598                                                  llvm::Function *Fn,
1599                                                  const FunctionArgList &Args) {
1600
1601  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1602  assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1603         "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
1604  StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
1605
1606  FunctionArgList::const_iterator i = Args.begin();
1607  const VarDecl *ThisArg = i->first;
1608  llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1609  llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1610  const VarDecl *SrcArg = (i+1)->first;
1611  llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1612  llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1613
1614  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1615       Base != ClassDecl->bases_end(); ++Base) {
1616    // FIXME. copy assignment of virtual base NYI
1617    if (Base->isVirtual())
1618      continue;
1619
1620    CXXRecordDecl *BaseClassDecl
1621      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1622    EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1623                            Base->getType());
1624  }
1625
1626  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1627       FieldEnd = ClassDecl->field_end();
1628       Field != FieldEnd; ++Field) {
1629    QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1630    const ConstantArrayType *Array =
1631      getContext().getAsConstantArrayType(FieldType);
1632    if (Array)
1633      FieldType = getContext().getBaseElementType(FieldType);
1634
1635    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1636      CXXRecordDecl *FieldClassDecl
1637      = cast<CXXRecordDecl>(FieldClassType->getDecl());
1638      LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1639      LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1640      if (Array) {
1641        const llvm::Type *BasePtr = ConvertType(FieldType);
1642        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1643        llvm::Value *DestBaseAddrPtr =
1644          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1645        llvm::Value *SrcBaseAddrPtr =
1646          Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1647        EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1648                                    FieldClassDecl, FieldType);
1649      }
1650      else
1651        EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1652                               0 /*ClassDecl*/, FieldClassDecl, FieldType);
1653      continue;
1654    }
1655    // Do a built-in assignment of scalar data members.
1656    LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1657    LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1658    RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1659    EmitStoreThroughLValue(RVRHS, LHS, FieldType);
1660  }
1661
1662  // return *this;
1663  Builder.CreateStore(LoadOfThis, ReturnValue);
1664
1665  FinishFunction();
1666}
1667
1668static void EmitBaseInitializer(CodeGenFunction &CGF,
1669                                const CXXRecordDecl *ClassDecl,
1670                                CXXBaseOrMemberInitializer *BaseInit,
1671                                CXXCtorType CtorType) {
1672  assert(BaseInit->isBaseInitializer() &&
1673         "Must have base initializer!");
1674
1675  llvm::Value *ThisPtr = CGF.LoadCXXThis();
1676
1677  const Type *BaseType = BaseInit->getBaseClass();
1678  CXXRecordDecl *BaseClassDecl =
1679    cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1680  llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1681                                             BaseClassDecl,
1682                                             /*NullCheckValue=*/false);
1683  CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1684                             CtorType, V,
1685                             BaseInit->const_arg_begin(),
1686                             BaseInit->const_arg_end());
1687}
1688
1689static void EmitMemberInitializer(CodeGenFunction &CGF,
1690                                  const CXXRecordDecl *ClassDecl,
1691                                  CXXBaseOrMemberInitializer *MemberInit) {
1692  assert(MemberInit->isMemberInitializer() &&
1693         "Must have member initializer!");
1694
1695  // non-static data member initializers.
1696  FieldDecl *Field = MemberInit->getMember();
1697  QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
1698
1699  llvm::Value *ThisPtr = CGF.LoadCXXThis();
1700  LValue LHS;
1701  if (FieldType->isReferenceType()) {
1702    // FIXME: This is really ugly; should be refactored somehow
1703    unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1704    llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1705    assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1706    LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1707  } else {
1708    LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
1709  }
1710
1711  // If we are initializing an anonymous union field, drill down to the field.
1712  if (MemberInit->getAnonUnionMember()) {
1713    Field = MemberInit->getAnonUnionMember();
1714    LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1715                                 /*IsUnion=*/true, 0);
1716    FieldType = Field->getType();
1717  }
1718
1719  // If the field is an array, branch based on the element type.
1720  const ConstantArrayType *Array =
1721    CGF.getContext().getAsConstantArrayType(FieldType);
1722  if (Array)
1723    FieldType = CGF.getContext().getBaseElementType(FieldType);
1724
1725  // We lose the constructor for anonymous union members, so handle them
1726  // explicitly.
1727  // FIXME: This is somwhat ugly.
1728  if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1729    if (MemberInit->getNumArgs())
1730      CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1731                      LHS.isVolatileQualified());
1732    else
1733      CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1734    return;
1735  }
1736
1737  if (FieldType->getAs<RecordType>()) {
1738    assert(MemberInit->getConstructor() &&
1739           "EmitCtorPrologue - no constructor to initialize member");
1740    if (Array) {
1741      const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1742      BasePtr = llvm::PointerType::getUnqual(BasePtr);
1743      llvm::Value *BaseAddrPtr =
1744        CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1745      CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
1746                                     Array, BaseAddrPtr,
1747                                     MemberInit->const_arg_begin(),
1748                                     MemberInit->const_arg_end());
1749    }
1750    else
1751      CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1752                                 Ctor_Complete, LHS.getAddress(),
1753                                 MemberInit->const_arg_begin(),
1754                                 MemberInit->const_arg_end());
1755    return;
1756  }
1757
1758  assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1759  Expr *RhsExpr = *MemberInit->arg_begin();
1760  RValue RHS;
1761  if (FieldType->isReferenceType()) {
1762    RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1763                                    /*IsInitializer=*/true);
1764    CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1765  } else if (Array) {
1766    CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1767  } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1768    RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1769    CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1770  } else if (RhsExpr->getType()->isAnyComplexType()) {
1771    CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1772                                LHS.isVolatileQualified());
1773  } else {
1774    // Handle member function pointers; other aggregates shouldn't get this far.
1775    CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1776  }
1777}
1778
1779/// EmitCtorPrologue - This routine generates necessary code to initialize
1780/// base classes and non-static data members belonging to this constructor.
1781/// FIXME: This needs to take a CXXCtorType.
1782void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1783                                       CXXCtorType CtorType) {
1784  const CXXRecordDecl *ClassDecl = CD->getParent();
1785
1786  // FIXME: Add vbase initialization
1787
1788  for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1789       E = CD->init_end();
1790       B != E; ++B) {
1791    CXXBaseOrMemberInitializer *Member = (*B);
1792
1793    assert(LiveTemporaries.empty() &&
1794           "Should not have any live temporaries at initializer start!");
1795
1796    if (Member->isBaseInitializer())
1797      EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1798    else
1799      EmitMemberInitializer(*this, ClassDecl, Member);
1800
1801    // Pop any live temporaries that the initializers might have pushed.
1802    while (!LiveTemporaries.empty())
1803      PopCXXTemporary();
1804  }
1805
1806  if (!ClassDecl->isDynamicClass())
1807    return;
1808
1809  // Initialize the vtable pointer.
1810  // FIXME: This needs to initialize secondary vtable pointers too.
1811  llvm::Value *ThisPtr = LoadCXXThis();
1812
1813  llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1814  uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl);
1815
1816  llvm::Value *VtableAddressPoint =
1817    Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1818
1819  llvm::Value *VtableField =
1820    Builder.CreateBitCast(ThisPtr,
1821                          VtableAddressPoint->getType()->getPointerTo());
1822
1823  Builder.CreateStore(VtableAddressPoint, VtableField);
1824}
1825
1826/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1827/// destructor. This is to call destructors on members and base classes
1828/// in reverse order of their construction.
1829/// FIXME: This needs to take a CXXDtorType.
1830void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1831                                       CXXDtorType DtorType) {
1832  assert(!DD->isTrivial() &&
1833         "Should not emit dtor epilogue for trivial dtor!");
1834
1835  const CXXRecordDecl *ClassDecl = DD->getParent();
1836
1837  // Collect the fields.
1838  llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1839  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1840       E = ClassDecl->field_end(); I != E; ++I) {
1841    const FieldDecl *Field = *I;
1842
1843    QualType FieldType = getContext().getCanonicalType(Field->getType());
1844    FieldType = getContext().getBaseElementType(FieldType);
1845
1846    const RecordType *RT = FieldType->getAs<RecordType>();
1847    if (!RT)
1848      continue;
1849
1850    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1851    if (FieldClassDecl->hasTrivialDestructor())
1852        continue;
1853
1854    FieldDecls.push_back(Field);
1855  }
1856
1857  // Now destroy the fields.
1858  for (size_t i = FieldDecls.size(); i > 0; --i) {
1859    const FieldDecl *Field = FieldDecls[i - 1];
1860
1861    QualType FieldType = Field->getType();
1862    const ConstantArrayType *Array =
1863      getContext().getAsConstantArrayType(FieldType);
1864    if (Array)
1865      FieldType = getContext().getBaseElementType(FieldType);
1866
1867    const RecordType *RT = FieldType->getAs<RecordType>();
1868    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1869
1870    llvm::Value *ThisPtr = LoadCXXThis();
1871
1872    LValue LHS = EmitLValueForField(ThisPtr, Field,
1873                                    /*isUnion=*/false,
1874                                    // FIXME: Qualifiers?
1875                                    /*CVRQualifiers=*/0);
1876    if (Array) {
1877      const llvm::Type *BasePtr = ConvertType(FieldType);
1878      BasePtr = llvm::PointerType::getUnqual(BasePtr);
1879      llvm::Value *BaseAddrPtr =
1880        Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1881      EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1882                                Array, BaseAddrPtr);
1883    } else
1884      EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1885                            Dtor_Complete, LHS.getAddress());
1886  }
1887
1888  // Destroy non-virtual bases.
1889  for (CXXRecordDecl::reverse_base_class_const_iterator I =
1890        ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1891    const CXXBaseSpecifier &Base = *I;
1892
1893    // Ignore virtual bases.
1894    if (Base.isVirtual())
1895      continue;
1896
1897    CXXRecordDecl *BaseClassDecl
1898      = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1899
1900    // Ignore trivial destructors.
1901    if (BaseClassDecl->hasTrivialDestructor())
1902      continue;
1903    const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1904
1905    llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1906                                           ClassDecl, BaseClassDecl,
1907                                           /*NullCheckValue=*/false);
1908    EmitCXXDestructorCall(D, Dtor_Base, V);
1909  }
1910
1911  // If we're emitting a base destructor, we don't want to emit calls to the
1912  // virtual bases.
1913  if (DtorType == Dtor_Base)
1914    return;
1915
1916  // Handle virtual bases.
1917  for (CXXRecordDecl::reverse_base_class_const_iterator I =
1918       ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
1919    const CXXBaseSpecifier &Base = *I;
1920    CXXRecordDecl *BaseClassDecl
1921    = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1922
1923    // Ignore trivial destructors.
1924    if (BaseClassDecl->hasTrivialDestructor())
1925      continue;
1926    const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1927    llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1928                                           ClassDecl, BaseClassDecl,
1929                                           /*NullCheckValue=*/false);
1930    EmitCXXDestructorCall(D, Dtor_Base, V);
1931  }
1932
1933  // If we have a deleting destructor, emit a call to the delete operator.
1934  if (DtorType == Dtor_Deleting) {
1935    assert(DD->getOperatorDelete() &&
1936           "operator delete missing - EmitDtorEpilogue");
1937    EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1938                   getContext().getTagDeclType(ClassDecl));
1939  }
1940}
1941
1942void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1943                                                  CXXDtorType DtorType,
1944                                                  llvm::Function *Fn,
1945                                                  const FunctionArgList &Args) {
1946  assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
1947         "SynthesizeDefaultDestructor - destructor has user declaration");
1948
1949  StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1950                SourceLocation());
1951
1952  EmitDtorEpilogue(Dtor, DtorType);
1953  FinishFunction();
1954}
1955