CGCXX.cpp revision fd12649cd54074ca9efa0774a7812e330619d198
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::BuildThunk(GlobalDecl GD, bool Extern,
998                          const ThunkAdjustment &ThisAdjustment) {
999  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1000  llvm::SmallString<256> OutName;
1001  if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
1002    getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
1003                                          OutName);
1004  } else
1005    getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
1006
1007  llvm::GlobalVariable::LinkageTypes linktype;
1008  linktype = llvm::GlobalValue::WeakAnyLinkage;
1009  if (!Extern)
1010    linktype = llvm::GlobalValue::InternalLinkage;
1011  llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1012  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1013  const llvm::FunctionType *FTy =
1014    getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1015                               FPT->isVariadic());
1016
1017  llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
1018                                              &getModule());
1019  CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
1020  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1021  return m;
1022}
1023
1024llvm::Constant *
1025CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
1026                                   const CovariantThunkAdjustment &Adjustment) {
1027  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1028  llvm::SmallString<256> OutName;
1029  getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
1030  llvm::GlobalVariable::LinkageTypes linktype;
1031  linktype = llvm::GlobalValue::WeakAnyLinkage;
1032  if (!Extern)
1033    linktype = llvm::GlobalValue::InternalLinkage;
1034  llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1035  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1036  const llvm::FunctionType *FTy =
1037    getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1038                               FPT->isVariadic());
1039
1040  llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
1041                                              &getModule());
1042  CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
1043  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1044  return m;
1045}
1046
1047llvm::Value *
1048CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
1049                                              const CXXRecordDecl *ClassDecl,
1050                                           const CXXRecordDecl *BaseClassDecl) {
1051  const llvm::Type *Int8PtrTy =
1052    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1053
1054  llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1055                                                 Int8PtrTy->getPointerTo());
1056  VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1057
1058  int64_t VBaseOffsetIndex =
1059    CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1060
1061  llvm::Value *VBaseOffsetPtr =
1062    Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
1063  const llvm::Type *PtrDiffTy =
1064    ConvertType(getContext().getPointerDiffType());
1065
1066  VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1067                                         PtrDiffTy->getPointerTo());
1068
1069  llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1070
1071  return VBaseOffset;
1072}
1073
1074static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
1075                                     llvm::Value *This, const llvm::Type *Ty) {
1076  Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
1077
1078  llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1079  Vtable = CGF.Builder.CreateLoad(Vtable);
1080
1081  llvm::Value *VFuncPtr =
1082    CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1083  return CGF.Builder.CreateLoad(VFuncPtr);
1084}
1085
1086llvm::Value *
1087CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1088                                  const llvm::Type *Ty) {
1089  MD = MD->getCanonicalDecl();
1090  uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
1091
1092  return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1093}
1094
1095llvm::Value *
1096CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1097                                  llvm::Value *&This, const llvm::Type *Ty) {
1098  DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
1099  uint64_t VtableIndex =
1100    CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
1101
1102  return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1103}
1104
1105/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1106/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1107/// copy or via a copy constructor call.
1108//  FIXME. Consolidate this with EmitCXXAggrConstructorCall.
1109void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1110                                            llvm::Value *Src,
1111                                            const ArrayType *Array,
1112                                            const CXXRecordDecl *BaseClassDecl,
1113                                            QualType Ty) {
1114  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1115  assert(CA && "VLA cannot be copied over");
1116  bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1117
1118  // Create a temporary for the loop index and initialize it with 0.
1119  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1120                                           "loop.index");
1121  llvm::Value* zeroConstant =
1122    llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1123  Builder.CreateStore(zeroConstant, IndexPtr);
1124  // Start the loop with a block that tests the condition.
1125  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1126  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1127
1128  EmitBlock(CondBlock);
1129
1130  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1131  // Generate: if (loop-index < number-of-elements fall to the loop body,
1132  // otherwise, go to the block after the for-loop.
1133  uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1134  llvm::Value * NumElementsPtr =
1135    llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1136  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1137  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1138                                              "isless");
1139  // If the condition is true, execute the body.
1140  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1141
1142  EmitBlock(ForBody);
1143  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1144  // Inside the loop body, emit the constructor call on the array element.
1145  Counter = Builder.CreateLoad(IndexPtr);
1146  Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1147  Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1148  if (BitwiseCopy)
1149    EmitAggregateCopy(Dest, Src, Ty);
1150  else if (CXXConstructorDecl *BaseCopyCtor =
1151           BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1152    llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1153                                                      Ctor_Complete);
1154    CallArgList CallArgs;
1155    // Push the this (Dest) ptr.
1156    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1157                                      BaseCopyCtor->getThisType(getContext())));
1158
1159    // Push the Src ptr.
1160    CallArgs.push_back(std::make_pair(RValue::get(Src),
1161                                     BaseCopyCtor->getParamDecl(0)->getType()));
1162    QualType ResultType =
1163      BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
1164    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1165             Callee, CallArgs, BaseCopyCtor);
1166  }
1167  EmitBlock(ContinueBlock);
1168
1169  // Emit the increment of the loop counter.
1170  llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1171  Counter = Builder.CreateLoad(IndexPtr);
1172  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1173  Builder.CreateStore(NextVal, IndexPtr);
1174
1175  // Finally, branch back up to the condition for the next iteration.
1176  EmitBranch(CondBlock);
1177
1178  // Emit the fall-through block.
1179  EmitBlock(AfterFor, true);
1180}
1181
1182/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1183/// array of objects from SrcValue to DestValue. Assignment can be either a
1184/// bitwise assignment or via a copy assignment operator function call.
1185/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1186void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1187                                            llvm::Value *Src,
1188                                            const ArrayType *Array,
1189                                            const CXXRecordDecl *BaseClassDecl,
1190                                            QualType Ty) {
1191  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1192  assert(CA && "VLA cannot be asssigned");
1193  bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1194
1195  // Create a temporary for the loop index and initialize it with 0.
1196  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1197                                           "loop.index");
1198  llvm::Value* zeroConstant =
1199  llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1200  Builder.CreateStore(zeroConstant, IndexPtr);
1201  // Start the loop with a block that tests the condition.
1202  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1203  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1204
1205  EmitBlock(CondBlock);
1206
1207  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1208  // Generate: if (loop-index < number-of-elements fall to the loop body,
1209  // otherwise, go to the block after the for-loop.
1210  uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1211  llvm::Value * NumElementsPtr =
1212  llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1213  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1214  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1215                                              "isless");
1216  // If the condition is true, execute the body.
1217  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1218
1219  EmitBlock(ForBody);
1220  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1221  // Inside the loop body, emit the assignment operator call on array element.
1222  Counter = Builder.CreateLoad(IndexPtr);
1223  Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1224  Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1225  const CXXMethodDecl *MD = 0;
1226  if (BitwiseAssign)
1227    EmitAggregateCopy(Dest, Src, Ty);
1228  else {
1229    bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1230                                                               MD);
1231    assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1232    (void)hasCopyAssign;
1233    const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1234    const llvm::Type *LTy =
1235    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1236                                   FPT->isVariadic());
1237    llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
1238
1239    CallArgList CallArgs;
1240    // Push the this (Dest) ptr.
1241    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1242                                      MD->getThisType(getContext())));
1243
1244    // Push the Src ptr.
1245    CallArgs.push_back(std::make_pair(RValue::get(Src),
1246                                      MD->getParamDecl(0)->getType()));
1247    QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
1248    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1249             Callee, CallArgs, MD);
1250  }
1251  EmitBlock(ContinueBlock);
1252
1253  // Emit the increment of the loop counter.
1254  llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1255  Counter = Builder.CreateLoad(IndexPtr);
1256  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1257  Builder.CreateStore(NextVal, IndexPtr);
1258
1259  // Finally, branch back up to the condition for the next iteration.
1260  EmitBranch(CondBlock);
1261
1262  // Emit the fall-through block.
1263  EmitBlock(AfterFor, true);
1264}
1265
1266/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1267/// object from SrcValue to DestValue. Copying can be either a bitwise copy
1268/// or via a copy constructor call.
1269void CodeGenFunction::EmitClassMemberwiseCopy(
1270                        llvm::Value *Dest, llvm::Value *Src,
1271                        const CXXRecordDecl *ClassDecl,
1272                        const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1273  if (ClassDecl) {
1274    Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1275                                 /*NullCheckValue=*/false);
1276    Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1277                                /*NullCheckValue=*/false);
1278  }
1279  if (BaseClassDecl->hasTrivialCopyConstructor()) {
1280    EmitAggregateCopy(Dest, Src, Ty);
1281    return;
1282  }
1283
1284  if (CXXConstructorDecl *BaseCopyCtor =
1285      BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1286    llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1287                                                      Ctor_Complete);
1288    CallArgList CallArgs;
1289    // Push the this (Dest) ptr.
1290    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1291                                      BaseCopyCtor->getThisType(getContext())));
1292
1293    // Push the Src ptr.
1294    CallArgs.push_back(std::make_pair(RValue::get(Src),
1295                       BaseCopyCtor->getParamDecl(0)->getType()));
1296    QualType ResultType =
1297    BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
1298    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1299             Callee, CallArgs, BaseCopyCtor);
1300  }
1301}
1302
1303/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1304/// object from SrcValue to DestValue. Assignment can be either a bitwise
1305/// assignment of via an assignment operator call.
1306// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
1307void CodeGenFunction::EmitClassCopyAssignment(
1308                                        llvm::Value *Dest, llvm::Value *Src,
1309                                        const CXXRecordDecl *ClassDecl,
1310                                        const CXXRecordDecl *BaseClassDecl,
1311                                        QualType Ty) {
1312  if (ClassDecl) {
1313    Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1314                                 /*NullCheckValue=*/false);
1315    Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1316                                /*NullCheckValue=*/false);
1317  }
1318  if (BaseClassDecl->hasTrivialCopyAssignment()) {
1319    EmitAggregateCopy(Dest, Src, Ty);
1320    return;
1321  }
1322
1323  const CXXMethodDecl *MD = 0;
1324  bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1325                                                                 MD);
1326  assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1327  (void)ConstCopyAssignOp;
1328
1329  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1330  const llvm::Type *LTy =
1331    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1332                                   FPT->isVariadic());
1333  llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
1334
1335  CallArgList CallArgs;
1336  // Push the this (Dest) ptr.
1337  CallArgs.push_back(std::make_pair(RValue::get(Dest),
1338                                    MD->getThisType(getContext())));
1339
1340  // Push the Src ptr.
1341  CallArgs.push_back(std::make_pair(RValue::get(Src),
1342                                    MD->getParamDecl(0)->getType()));
1343  QualType ResultType =
1344    MD->getType()->getAs<FunctionType>()->getResultType();
1345  EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1346           Callee, CallArgs, MD);
1347}
1348
1349/// SynthesizeDefaultConstructor - synthesize a default constructor
1350void
1351CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1352                                              CXXCtorType Type,
1353                                              llvm::Function *Fn,
1354                                              const FunctionArgList &Args) {
1355  assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
1356  StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1357                SourceLocation());
1358  EmitCtorPrologue(Ctor, Type);
1359  FinishFunction();
1360}
1361
1362/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1363/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
1364/// The implicitly-defined copy constructor for class X performs a memberwise
1365/// copy of its subobjects. The order of copying is the same as the order of
1366/// initialization of bases and members in a user-defined constructor
1367/// Each subobject is copied in the manner appropriate to its type:
1368///  if the subobject is of class type, the copy constructor for the class is
1369///  used;
1370///  if the subobject is an array, each element is copied, in the manner
1371///  appropriate to the element type;
1372///  if the subobject is of scalar type, the built-in assignment operator is
1373///  used.
1374/// Virtual base class subobjects shall be copied only once by the
1375/// implicitly-defined copy constructor
1376
1377void
1378CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1379                                              CXXCtorType Type,
1380                                              llvm::Function *Fn,
1381                                              const FunctionArgList &Args) {
1382  const CXXRecordDecl *ClassDecl = Ctor->getParent();
1383  assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
1384      "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1385  assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
1386  StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1387                SourceLocation());
1388
1389  FunctionArgList::const_iterator i = Args.begin();
1390  const VarDecl *ThisArg = i->first;
1391  llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1392  llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1393  const VarDecl *SrcArg = (i+1)->first;
1394  llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1395  llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1396
1397  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1398       Base != ClassDecl->bases_end(); ++Base) {
1399    // FIXME. copy constrution of virtual base NYI
1400    if (Base->isVirtual())
1401      continue;
1402
1403    CXXRecordDecl *BaseClassDecl
1404      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1405    EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1406                            Base->getType());
1407  }
1408
1409  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1410       E = ClassDecl->field_end(); I != E; ++I) {
1411    const FieldDecl *Field = *I;
1412
1413    QualType FieldType = getContext().getCanonicalType(Field->getType());
1414    const ConstantArrayType *Array =
1415      getContext().getAsConstantArrayType(FieldType);
1416    if (Array)
1417      FieldType = getContext().getBaseElementType(FieldType);
1418
1419    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1420      CXXRecordDecl *FieldClassDecl
1421        = cast<CXXRecordDecl>(FieldClassType->getDecl());
1422      LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1423      LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1424      if (Array) {
1425        const llvm::Type *BasePtr = ConvertType(FieldType);
1426        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1427        llvm::Value *DestBaseAddrPtr =
1428          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1429        llvm::Value *SrcBaseAddrPtr =
1430          Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1431        EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1432                                    FieldClassDecl, FieldType);
1433      }
1434      else
1435        EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1436                                0 /*ClassDecl*/, FieldClassDecl, FieldType);
1437      continue;
1438    }
1439
1440    if (Field->getType()->isReferenceType()) {
1441      unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1442
1443      llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1444                                                 "lhs.ref");
1445
1446      llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1447                                                 "rhs.ref");
1448
1449      // Load the value in RHS.
1450      RHS = Builder.CreateLoad(RHS);
1451
1452      // And store it in the LHS
1453      Builder.CreateStore(RHS, LHS);
1454
1455      continue;
1456    }
1457    // Do a built-in assignment of scalar data members.
1458    LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1459    LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1460
1461    if (!hasAggregateLLVMType(Field->getType())) {
1462      RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1463      EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1464    } else if (Field->getType()->isAnyComplexType()) {
1465      ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1466                                               RHS.isVolatileQualified());
1467      StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1468    } else {
1469      EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1470    }
1471  }
1472  FinishFunction();
1473}
1474
1475/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1476/// Before the implicitly-declared copy assignment operator for a class is
1477/// implicitly defined, all implicitly- declared copy assignment operators for
1478/// its direct base classes and its nonstatic data members shall have been
1479/// implicitly defined. [12.8-p12]
1480/// The implicitly-defined copy assignment operator for class X performs
1481/// memberwise assignment of its subob- jects. The direct base classes of X are
1482/// assigned first, in the order of their declaration in
1483/// the base-specifier-list, and then the immediate nonstatic data members of X
1484/// are assigned, in the order in which they were declared in the class
1485/// definition.Each subobject is assigned in the manner appropriate to its type:
1486///   if the subobject is of class type, the copy assignment operator for the
1487///   class is used (as if by explicit qualification; that is, ignoring any
1488///   possible virtual overriding functions in more derived classes);
1489///
1490///   if the subobject is an array, each element is assigned, in the manner
1491///   appropriate to the element type;
1492///
1493///   if the subobject is of scalar type, the built-in assignment operator is
1494///   used.
1495void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1496                                                  llvm::Function *Fn,
1497                                                  const FunctionArgList &Args) {
1498
1499  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1500  assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1501         "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
1502  StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
1503
1504  FunctionArgList::const_iterator i = Args.begin();
1505  const VarDecl *ThisArg = i->first;
1506  llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1507  llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1508  const VarDecl *SrcArg = (i+1)->first;
1509  llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1510  llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1511
1512  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1513       Base != ClassDecl->bases_end(); ++Base) {
1514    // FIXME. copy assignment of virtual base NYI
1515    if (Base->isVirtual())
1516      continue;
1517
1518    CXXRecordDecl *BaseClassDecl
1519      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1520    EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1521                            Base->getType());
1522  }
1523
1524  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1525       FieldEnd = ClassDecl->field_end();
1526       Field != FieldEnd; ++Field) {
1527    QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1528    const ConstantArrayType *Array =
1529      getContext().getAsConstantArrayType(FieldType);
1530    if (Array)
1531      FieldType = getContext().getBaseElementType(FieldType);
1532
1533    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1534      CXXRecordDecl *FieldClassDecl
1535      = cast<CXXRecordDecl>(FieldClassType->getDecl());
1536      LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1537      LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1538      if (Array) {
1539        const llvm::Type *BasePtr = ConvertType(FieldType);
1540        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1541        llvm::Value *DestBaseAddrPtr =
1542          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1543        llvm::Value *SrcBaseAddrPtr =
1544          Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1545        EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1546                                    FieldClassDecl, FieldType);
1547      }
1548      else
1549        EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1550                               0 /*ClassDecl*/, FieldClassDecl, FieldType);
1551      continue;
1552    }
1553    // Do a built-in assignment of scalar data members.
1554    LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1555    LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1556    RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1557    EmitStoreThroughLValue(RVRHS, LHS, FieldType);
1558  }
1559
1560  // return *this;
1561  Builder.CreateStore(LoadOfThis, ReturnValue);
1562
1563  FinishFunction();
1564}
1565
1566static void EmitBaseInitializer(CodeGenFunction &CGF,
1567                                const CXXRecordDecl *ClassDecl,
1568                                CXXBaseOrMemberInitializer *BaseInit,
1569                                CXXCtorType CtorType) {
1570  assert(BaseInit->isBaseInitializer() &&
1571         "Must have base initializer!");
1572
1573  llvm::Value *ThisPtr = CGF.LoadCXXThis();
1574
1575  const Type *BaseType = BaseInit->getBaseClass();
1576  CXXRecordDecl *BaseClassDecl =
1577    cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1578  llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1579                                             BaseClassDecl,
1580                                             /*NullCheckValue=*/false);
1581  CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1582                             CtorType, V,
1583                             BaseInit->const_arg_begin(),
1584                             BaseInit->const_arg_end());
1585}
1586
1587static void EmitMemberInitializer(CodeGenFunction &CGF,
1588                                  const CXXRecordDecl *ClassDecl,
1589                                  CXXBaseOrMemberInitializer *MemberInit) {
1590  assert(MemberInit->isMemberInitializer() &&
1591         "Must have member initializer!");
1592
1593  // non-static data member initializers.
1594  FieldDecl *Field = MemberInit->getMember();
1595  QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
1596
1597  llvm::Value *ThisPtr = CGF.LoadCXXThis();
1598  LValue LHS;
1599  if (FieldType->isReferenceType()) {
1600    // FIXME: This is really ugly; should be refactored somehow
1601    unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1602    llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1603    assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1604    LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1605  } else {
1606    LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
1607  }
1608
1609  // If we are initializing an anonymous union field, drill down to the field.
1610  if (MemberInit->getAnonUnionMember()) {
1611    Field = MemberInit->getAnonUnionMember();
1612    LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1613                                 /*IsUnion=*/true, 0);
1614    FieldType = Field->getType();
1615  }
1616
1617  // If the field is an array, branch based on the element type.
1618  const ConstantArrayType *Array =
1619    CGF.getContext().getAsConstantArrayType(FieldType);
1620  if (Array)
1621    FieldType = CGF.getContext().getBaseElementType(FieldType);
1622
1623  // We lose the constructor for anonymous union members, so handle them
1624  // explicitly.
1625  // FIXME: This is somwhat ugly.
1626  if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1627    if (MemberInit->getNumArgs())
1628      CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1629                      LHS.isVolatileQualified());
1630    else
1631      CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1632    return;
1633  }
1634
1635  if (FieldType->getAs<RecordType>()) {
1636    assert(MemberInit->getConstructor() &&
1637           "EmitCtorPrologue - no constructor to initialize member");
1638    if (Array) {
1639      const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1640      BasePtr = llvm::PointerType::getUnqual(BasePtr);
1641      llvm::Value *BaseAddrPtr =
1642        CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1643      CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
1644                                     Array, BaseAddrPtr,
1645                                     MemberInit->const_arg_begin(),
1646                                     MemberInit->const_arg_end());
1647    }
1648    else
1649      CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1650                                 Ctor_Complete, LHS.getAddress(),
1651                                 MemberInit->const_arg_begin(),
1652                                 MemberInit->const_arg_end());
1653    return;
1654  }
1655
1656  assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1657  Expr *RhsExpr = *MemberInit->arg_begin();
1658  RValue RHS;
1659  if (FieldType->isReferenceType()) {
1660    RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1661                                    /*IsInitializer=*/true);
1662    CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1663  } else if (Array) {
1664    CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1665  } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1666    RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1667    CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1668  } else if (RhsExpr->getType()->isAnyComplexType()) {
1669    CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1670                                LHS.isVolatileQualified());
1671  } else {
1672    // Handle member function pointers; other aggregates shouldn't get this far.
1673    CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1674  }
1675}
1676
1677/// EmitCtorPrologue - This routine generates necessary code to initialize
1678/// base classes and non-static data members belonging to this constructor.
1679/// FIXME: This needs to take a CXXCtorType.
1680void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1681                                       CXXCtorType CtorType) {
1682  const CXXRecordDecl *ClassDecl = CD->getParent();
1683
1684  // FIXME: Add vbase initialization
1685  llvm::Value *LoadOfThis = 0;
1686
1687  for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1688       E = CD->init_end();
1689       B != E; ++B) {
1690    CXXBaseOrMemberInitializer *Member = (*B);
1691
1692    assert(LiveTemporaries.empty() &&
1693           "Should not have any live temporaries at initializer start!");
1694
1695    if (Member->isBaseInitializer())
1696      EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1697    else
1698      EmitMemberInitializer(*this, ClassDecl, Member);
1699
1700    // Pop any live temporaries that the initializers might have pushed.
1701    while (!LiveTemporaries.empty())
1702      PopCXXTemporary();
1703  }
1704
1705  // Initialize the vtable pointer
1706  if (ClassDecl->isDynamicClass()) {
1707    if (!LoadOfThis)
1708      LoadOfThis = LoadCXXThis();
1709    llvm::Value *VtableField;
1710    llvm::Type *Ptr8Ty, *PtrPtr8Ty;
1711    Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
1712    PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1713    VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1714    llvm::Value *vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1715    Builder.CreateStore(vtable, VtableField);
1716  }
1717}
1718
1719/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1720/// destructor. This is to call destructors on members and base classes
1721/// in reverse order of their construction.
1722/// FIXME: This needs to take a CXXDtorType.
1723void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1724                                       CXXDtorType DtorType) {
1725  assert(!DD->isTrivial() &&
1726         "Should not emit dtor epilogue for trivial dtor!");
1727
1728  const CXXRecordDecl *ClassDecl = DD->getParent();
1729
1730  // Collect the fields.
1731  llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1732  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1733       E = ClassDecl->field_end(); I != E; ++I) {
1734    const FieldDecl *Field = *I;
1735
1736    QualType FieldType = getContext().getCanonicalType(Field->getType());
1737    FieldType = getContext().getBaseElementType(FieldType);
1738
1739    const RecordType *RT = FieldType->getAs<RecordType>();
1740    if (!RT)
1741      continue;
1742
1743    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1744    if (FieldClassDecl->hasTrivialDestructor())
1745        continue;
1746
1747    FieldDecls.push_back(Field);
1748  }
1749
1750  // Now destroy the fields.
1751  for (size_t i = FieldDecls.size(); i > 0; --i) {
1752    const FieldDecl *Field = FieldDecls[i - 1];
1753
1754    QualType FieldType = Field->getType();
1755    const ConstantArrayType *Array =
1756      getContext().getAsConstantArrayType(FieldType);
1757    if (Array)
1758      FieldType = getContext().getBaseElementType(FieldType);
1759
1760    const RecordType *RT = FieldType->getAs<RecordType>();
1761    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1762
1763    llvm::Value *ThisPtr = LoadCXXThis();
1764
1765    LValue LHS = EmitLValueForField(ThisPtr, Field,
1766                                    /*isUnion=*/false,
1767                                    // FIXME: Qualifiers?
1768                                    /*CVRQualifiers=*/0);
1769    if (Array) {
1770      const llvm::Type *BasePtr = ConvertType(FieldType);
1771      BasePtr = llvm::PointerType::getUnqual(BasePtr);
1772      llvm::Value *BaseAddrPtr =
1773        Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1774      EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1775                                Array, BaseAddrPtr);
1776    } else
1777      EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1778                            Dtor_Complete, LHS.getAddress());
1779  }
1780
1781  // Destroy non-virtual bases.
1782  for (CXXRecordDecl::reverse_base_class_const_iterator I =
1783        ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1784    const CXXBaseSpecifier &Base = *I;
1785
1786    // Ignore virtual bases.
1787    if (Base.isVirtual())
1788      continue;
1789
1790    CXXRecordDecl *BaseClassDecl
1791      = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1792
1793    // Ignore trivial destructors.
1794    if (BaseClassDecl->hasTrivialDestructor())
1795      continue;
1796    const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1797
1798    llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1799                                           ClassDecl, BaseClassDecl,
1800                                           /*NullCheckValue=*/false);
1801    EmitCXXDestructorCall(D, Dtor_Base, V);
1802  }
1803
1804  // If we're emitting a base destructor, we don't want to emit calls to the
1805  // virtual bases.
1806  if (DtorType == Dtor_Base)
1807    return;
1808
1809  // Handle virtual bases.
1810  for (CXXRecordDecl::reverse_base_class_const_iterator I =
1811       ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
1812    const CXXBaseSpecifier &Base = *I;
1813    CXXRecordDecl *BaseClassDecl
1814    = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1815
1816    // Ignore trivial destructors.
1817    if (BaseClassDecl->hasTrivialDestructor())
1818      continue;
1819    const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1820    llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1821                                           ClassDecl, BaseClassDecl,
1822                                           /*NullCheckValue=*/false);
1823    EmitCXXDestructorCall(D, Dtor_Base, V);
1824  }
1825
1826  // If we have a deleting destructor, emit a call to the delete operator.
1827  if (DtorType == Dtor_Deleting) {
1828    assert(DD->getOperatorDelete() &&
1829           "operator delete missing - EmitDtorEpilogue");
1830    EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1831                   getContext().getTagDeclType(ClassDecl));
1832  }
1833}
1834
1835void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1836                                                  CXXDtorType DtorType,
1837                                                  llvm::Function *Fn,
1838                                                  const FunctionArgList &Args) {
1839  assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
1840         "SynthesizeDefaultDestructor - destructor has user declaration");
1841
1842  StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1843                SourceLocation());
1844
1845  EmitDtorEpilogue(Dtor, DtorType);
1846  FinishFunction();
1847}
1848