1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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 of classes
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/RecordLayout.h"
17 
18 using namespace clang;
19 using namespace CodeGen;
20 
21 static uint64_t
22 ComputeNonVirtualBaseClassOffset(ASTContext &Context, CXXBasePaths &Paths,
23                                  unsigned Start) {
24   uint64_t Offset = 0;
25 
26   const CXXBasePath &Path = Paths.front();
27   for (unsigned i = Start, e = Path.size(); i != e; ++i) {
28     const CXXBasePathElement& Element = Path[i];
29 
30     // Get the layout.
31     const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
32 
33     const CXXBaseSpecifier *BS = Element.Base;
34     assert(!BS->isVirtual() && "Should not see virtual bases here!");
35 
36     const CXXRecordDecl *Base =
37       cast<CXXRecordDecl>(BS->getType()->getAs<RecordType>()->getDecl());
38 
39     // Add the offset.
40     Offset += Layout.getBaseClassOffset(Base) / 8;
41   }
42 
43   return Offset;
44 }
45 
46 llvm::Constant *
47 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *Class,
48                                             const CXXRecordDecl *BaseClass) {
49   if (Class == BaseClass)
50     return 0;
51 
52   CXXBasePaths Paths(/*FindAmbiguities=*/false,
53                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
54   if (!const_cast<CXXRecordDecl *>(Class)->
55         isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClass), Paths)) {
56     assert(false && "Class must be derived from the passed in base class!");
57     return 0;
58   }
59 
60   uint64_t Offset = ComputeNonVirtualBaseClassOffset(getContext(), Paths, 0);
61   if (!Offset)
62     return 0;
63 
64   const llvm::Type *PtrDiffTy =
65     Types.ConvertType(getContext().getPointerDiffType());
66 
67   return llvm::ConstantInt::get(PtrDiffTy, Offset);
68 }
69 
70 // FIXME: This probably belongs in CGVtable, but it relies on
71 // the static function ComputeNonVirtualBaseClassOffset, so we should make that
72 // a CodeGenModule member function as well.
73 ThunkAdjustment
74 CodeGenModule::ComputeThunkAdjustment(const CXXRecordDecl *ClassDecl,
75                                       const CXXRecordDecl *BaseClassDecl) {
76   CXXBasePaths Paths(/*FindAmbiguities=*/false,
77                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
78   if (!const_cast<CXXRecordDecl *>(ClassDecl)->
79         isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
80     assert(false && "Class must be derived from the passed in base class!");
81     return ThunkAdjustment();
82   }
83 
84   unsigned Start = 0;
85   uint64_t VirtualOffset = 0;
86 
87   const CXXBasePath &Path = Paths.front();
88   const CXXRecordDecl *VBase = 0;
89   for (unsigned i = 0, e = Path.size(); i != e; ++i) {
90     const CXXBasePathElement& Element = Path[i];
91     if (Element.Base->isVirtual()) {
92       Start = i+1;
93       QualType VBaseType = Element.Base->getType();
94       VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
95     }
96   }
97   if (VBase)
98     VirtualOffset =
99       getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
100 
101   uint64_t Offset =
102     ComputeNonVirtualBaseClassOffset(getContext(), Paths, Start);
103   return ThunkAdjustment(Offset, VirtualOffset);
104 }
105 
106 llvm::Value *
107 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
108                                        const CXXRecordDecl *Class,
109                                        const CXXRecordDecl *BaseClass,
110                                        bool NullCheckValue) {
111   QualType BTy =
112     getContext().getCanonicalType(
113       getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClass)));
114   const llvm::Type *BasePtrTy = llvm::PointerType::getUnqual(ConvertType(BTy));
115 
116   if (Class == BaseClass) {
117     // Just cast back.
118     return Builder.CreateBitCast(Value, BasePtrTy);
119   }
120 
121   CXXBasePaths Paths(/*FindAmbiguities=*/false,
122                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
123   if (!const_cast<CXXRecordDecl *>(Class)->
124         isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClass), Paths)) {
125     assert(false && "Class must be derived from the passed in base class!");
126     return 0;
127   }
128 
129   unsigned Start = 0;
130   llvm::Value *VirtualOffset = 0;
131 
132   const CXXBasePath &Path = Paths.front();
133   const CXXRecordDecl *VBase = 0;
134   for (unsigned i = 0, e = Path.size(); i != e; ++i) {
135     const CXXBasePathElement& Element = Path[i];
136     if (Element.Base->isVirtual()) {
137       Start = i+1;
138       QualType VBaseType = Element.Base->getType();
139       VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
140     }
141   }
142 
143   uint64_t Offset =
144     ComputeNonVirtualBaseClassOffset(getContext(), Paths, Start);
145 
146   if (!Offset && !VBase) {
147     // Just cast back.
148     return Builder.CreateBitCast(Value, BasePtrTy);
149   }
150 
151   llvm::BasicBlock *CastNull = 0;
152   llvm::BasicBlock *CastNotNull = 0;
153   llvm::BasicBlock *CastEnd = 0;
154 
155   if (NullCheckValue) {
156     CastNull = createBasicBlock("cast.null");
157     CastNotNull = createBasicBlock("cast.notnull");
158     CastEnd = createBasicBlock("cast.end");
159 
160     llvm::Value *IsNull =
161       Builder.CreateICmpEQ(Value,
162                            llvm::Constant::getNullValue(Value->getType()));
163     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
164     EmitBlock(CastNotNull);
165   }
166 
167   if (VBase)
168     VirtualOffset = GetVirtualBaseClassOffset(Value, Class, VBase);
169 
170   const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
171   llvm::Value *NonVirtualOffset = 0;
172   if (Offset)
173     NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, Offset);
174 
175   llvm::Value *BaseOffset;
176   if (VBase) {
177     if (NonVirtualOffset)
178       BaseOffset = Builder.CreateAdd(VirtualOffset, NonVirtualOffset);
179     else
180       BaseOffset = VirtualOffset;
181   } else
182     BaseOffset = NonVirtualOffset;
183 
184   // Apply the base offset.
185   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
186   Value = Builder.CreateBitCast(Value, Int8PtrTy);
187   Value = Builder.CreateGEP(Value, BaseOffset, "add.ptr");
188 
189   // Cast back.
190   Value = Builder.CreateBitCast(Value, BasePtrTy);
191 
192   if (NullCheckValue) {
193     Builder.CreateBr(CastEnd);
194     EmitBlock(CastNull);
195     Builder.CreateBr(CastEnd);
196     EmitBlock(CastEnd);
197 
198     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
199     PHI->reserveOperandSpace(2);
200     PHI->addIncoming(Value, CastNotNull);
201     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
202                      CastNull);
203     Value = PHI;
204   }
205 
206   return Value;
207 }
208 
209 llvm::Value *
210 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
211                                           const CXXRecordDecl *Class,
212                                           const CXXRecordDecl *DerivedClass,
213                                           bool NullCheckValue) {
214   QualType DerivedTy =
215     getContext().getCanonicalType(
216     getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(DerivedClass)));
217   const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
218 
219   if (Class == DerivedClass) {
220     // Just cast back.
221     return Builder.CreateBitCast(Value, DerivedPtrTy);
222   }
223 
224   llvm::Value *NonVirtualOffset =
225     CGM.GetNonVirtualBaseClassOffset(DerivedClass, Class);
226 
227   if (!NonVirtualOffset) {
228     // No offset, we can just cast back.
229     return Builder.CreateBitCast(Value, DerivedPtrTy);
230   }
231 
232   llvm::BasicBlock *CastNull = 0;
233   llvm::BasicBlock *CastNotNull = 0;
234   llvm::BasicBlock *CastEnd = 0;
235 
236   if (NullCheckValue) {
237     CastNull = createBasicBlock("cast.null");
238     CastNotNull = createBasicBlock("cast.notnull");
239     CastEnd = createBasicBlock("cast.end");
240 
241     llvm::Value *IsNull =
242     Builder.CreateICmpEQ(Value,
243                          llvm::Constant::getNullValue(Value->getType()));
244     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
245     EmitBlock(CastNotNull);
246   }
247 
248   // Apply the offset.
249   Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
250   Value = Builder.CreateSub(Value, NonVirtualOffset);
251   Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
252 
253   // Just cast.
254   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
255 
256   if (NullCheckValue) {
257     Builder.CreateBr(CastEnd);
258     EmitBlock(CastNull);
259     Builder.CreateBr(CastEnd);
260     EmitBlock(CastEnd);
261 
262     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
263     PHI->reserveOperandSpace(2);
264     PHI->addIncoming(Value, CastNotNull);
265     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
266                      CastNull);
267     Value = PHI;
268   }
269 
270   return Value;
271 }
272 
273 /// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
274 /// array of objects from SrcValue to DestValue. Copying can be either a bitwise
275 /// copy or via a copy constructor call.
276 //  FIXME. Consolidate this with EmitCXXAggrConstructorCall.
277 void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
278                                             llvm::Value *Src,
279                                             const ArrayType *Array,
280                                             const CXXRecordDecl *BaseClassDecl,
281                                             QualType Ty) {
282   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
283   assert(CA && "VLA cannot be copied over");
284   bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
285 
286   // Create a temporary for the loop index and initialize it with 0.
287   llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
288                                            "loop.index");
289   llvm::Value* zeroConstant =
290     llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
291   Builder.CreateStore(zeroConstant, IndexPtr);
292   // Start the loop with a block that tests the condition.
293   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
294   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
295 
296   EmitBlock(CondBlock);
297 
298   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
299   // Generate: if (loop-index < number-of-elements fall to the loop body,
300   // otherwise, go to the block after the for-loop.
301   uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
302   llvm::Value * NumElementsPtr =
303     llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
304   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
305   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
306                                               "isless");
307   // If the condition is true, execute the body.
308   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
309 
310   EmitBlock(ForBody);
311   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
312   // Inside the loop body, emit the constructor call on the array element.
313   Counter = Builder.CreateLoad(IndexPtr);
314   Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
315   Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
316   if (BitwiseCopy)
317     EmitAggregateCopy(Dest, Src, Ty);
318   else if (CXXConstructorDecl *BaseCopyCtor =
319            BaseClassDecl->getCopyConstructor(getContext(), 0)) {
320     llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
321                                                       Ctor_Complete);
322     CallArgList CallArgs;
323     // Push the this (Dest) ptr.
324     CallArgs.push_back(std::make_pair(RValue::get(Dest),
325                                       BaseCopyCtor->getThisType(getContext())));
326 
327     // Push the Src ptr.
328     CallArgs.push_back(std::make_pair(RValue::get(Src),
329                                      BaseCopyCtor->getParamDecl(0)->getType()));
330     const FunctionProtoType *FPT
331       = BaseCopyCtor->getType()->getAs<FunctionProtoType>();
332     EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
333              Callee, ReturnValueSlot(), CallArgs, BaseCopyCtor);
334   }
335   EmitBlock(ContinueBlock);
336 
337   // Emit the increment of the loop counter.
338   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
339   Counter = Builder.CreateLoad(IndexPtr);
340   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
341   Builder.CreateStore(NextVal, IndexPtr);
342 
343   // Finally, branch back up to the condition for the next iteration.
344   EmitBranch(CondBlock);
345 
346   // Emit the fall-through block.
347   EmitBlock(AfterFor, true);
348 }
349 
350 /// EmitClassAggrCopyAssignment - This routine generates code to assign a class
351 /// array of objects from SrcValue to DestValue. Assignment can be either a
352 /// bitwise assignment or via a copy assignment operator function call.
353 /// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
354 void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
355                                             llvm::Value *Src,
356                                             const ArrayType *Array,
357                                             const CXXRecordDecl *BaseClassDecl,
358                                             QualType Ty) {
359   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
360   assert(CA && "VLA cannot be asssigned");
361   bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
362 
363   // Create a temporary for the loop index and initialize it with 0.
364   llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
365                                            "loop.index");
366   llvm::Value* zeroConstant =
367   llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
368   Builder.CreateStore(zeroConstant, IndexPtr);
369   // Start the loop with a block that tests the condition.
370   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
371   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
372 
373   EmitBlock(CondBlock);
374 
375   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
376   // Generate: if (loop-index < number-of-elements fall to the loop body,
377   // otherwise, go to the block after the for-loop.
378   uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
379   llvm::Value * NumElementsPtr =
380   llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
381   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
382   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
383                                               "isless");
384   // If the condition is true, execute the body.
385   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
386 
387   EmitBlock(ForBody);
388   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
389   // Inside the loop body, emit the assignment operator call on array element.
390   Counter = Builder.CreateLoad(IndexPtr);
391   Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
392   Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
393   const CXXMethodDecl *MD = 0;
394   if (BitwiseAssign)
395     EmitAggregateCopy(Dest, Src, Ty);
396   else {
397     BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
398     assert(MD && "EmitClassAggrCopyAssignment - No user assign");
399     const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
400     const llvm::Type *LTy =
401     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
402                                    FPT->isVariadic());
403     llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
404 
405     CallArgList CallArgs;
406     // Push the this (Dest) ptr.
407     CallArgs.push_back(std::make_pair(RValue::get(Dest),
408                                       MD->getThisType(getContext())));
409 
410     // Push the Src ptr.
411     QualType SrcTy = MD->getParamDecl(0)->getType();
412     RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
413                                                  RValue::getAggregate(Src);
414     CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
415     EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
416              Callee, ReturnValueSlot(), CallArgs, MD);
417   }
418   EmitBlock(ContinueBlock);
419 
420   // Emit the increment of the loop counter.
421   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
422   Counter = Builder.CreateLoad(IndexPtr);
423   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
424   Builder.CreateStore(NextVal, IndexPtr);
425 
426   // Finally, branch back up to the condition for the next iteration.
427   EmitBranch(CondBlock);
428 
429   // Emit the fall-through block.
430   EmitBlock(AfterFor, true);
431 }
432 
433 /// GetVTTParameter - Return the VTT parameter that should be passed to a
434 /// base constructor/destructor with virtual bases.
435 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD) {
436   if (!CGVtableInfo::needsVTTParameter(GD)) {
437     // This constructor/destructor does not need a VTT parameter.
438     return 0;
439   }
440 
441   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
442   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
443 
444   llvm::Value *VTT;
445 
446   uint64_t SubVTTIndex =
447     CGF.CGM.getVtableInfo().getSubVTTIndex(RD, Base);
448   assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
449 
450   if (CGVtableInfo::needsVTTParameter(CGF.CurGD)) {
451     // A VTT parameter was passed to the constructor, use it.
452     VTT = CGF.LoadCXXVTT();
453     VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
454   } else {
455     // We're the complete constructor, so get the VTT by name.
456     VTT = CGF.CGM.getVtableInfo().getVTT(RD);
457     VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
458   }
459 
460   return VTT;
461 }
462 
463 
464 /// EmitClassMemberwiseCopy - This routine generates code to copy a class
465 /// object from SrcValue to DestValue. Copying can be either a bitwise copy
466 /// or via a copy constructor call.
467 void CodeGenFunction::EmitClassMemberwiseCopy(
468                         llvm::Value *Dest, llvm::Value *Src,
469                         const CXXRecordDecl *ClassDecl,
470                         const CXXRecordDecl *BaseClassDecl, QualType Ty) {
471   CXXCtorType CtorType = Ctor_Complete;
472 
473   if (ClassDecl) {
474     Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
475                                  /*NullCheckValue=*/false);
476     Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
477                                 /*NullCheckValue=*/false);
478 
479     // We want to call the base constructor.
480     CtorType = Ctor_Base;
481   }
482   if (BaseClassDecl->hasTrivialCopyConstructor()) {
483     EmitAggregateCopy(Dest, Src, Ty);
484     return;
485   }
486 
487   if (CXXConstructorDecl *BaseCopyCtor =
488       BaseClassDecl->getCopyConstructor(getContext(), 0)) {
489     llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, CtorType);
490     CallArgList CallArgs;
491     // Push the this (Dest) ptr.
492     CallArgs.push_back(std::make_pair(RValue::get(Dest),
493                                       BaseCopyCtor->getThisType(getContext())));
494 
495     // Push the VTT parameter, if necessary.
496     if (llvm::Value *VTT =
497           GetVTTParameter(*this, GlobalDecl(BaseCopyCtor, CtorType))) {
498       QualType T = getContext().getPointerType(getContext().VoidPtrTy);
499       CallArgs.push_back(std::make_pair(RValue::get(VTT), T));
500     }
501 
502     // Push the Src ptr.
503     CallArgs.push_back(std::make_pair(RValue::get(Src),
504                        BaseCopyCtor->getParamDecl(0)->getType()));
505     const FunctionProtoType *FPT =
506       BaseCopyCtor->getType()->getAs<FunctionProtoType>();
507     EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
508              Callee, ReturnValueSlot(), CallArgs, BaseCopyCtor);
509   }
510 }
511 
512 /// EmitClassCopyAssignment - This routine generates code to copy assign a class
513 /// object from SrcValue to DestValue. Assignment can be either a bitwise
514 /// assignment of via an assignment operator call.
515 // FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
516 void CodeGenFunction::EmitClassCopyAssignment(
517                                         llvm::Value *Dest, llvm::Value *Src,
518                                         const CXXRecordDecl *ClassDecl,
519                                         const CXXRecordDecl *BaseClassDecl,
520                                         QualType Ty) {
521   if (ClassDecl) {
522     Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
523                                  /*NullCheckValue=*/false);
524     Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
525                                 /*NullCheckValue=*/false);
526   }
527   if (BaseClassDecl->hasTrivialCopyAssignment()) {
528     EmitAggregateCopy(Dest, Src, Ty);
529     return;
530   }
531 
532   const CXXMethodDecl *MD = 0;
533   BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
534   assert(MD && "EmitClassCopyAssignment - missing copy assign");
535 
536   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
537   const llvm::Type *LTy =
538     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
539                                    FPT->isVariadic());
540   llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
541 
542   CallArgList CallArgs;
543   // Push the this (Dest) ptr.
544   CallArgs.push_back(std::make_pair(RValue::get(Dest),
545                                     MD->getThisType(getContext())));
546 
547   // Push the Src ptr.
548   QualType SrcTy = MD->getParamDecl(0)->getType();
549   RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
550                                                RValue::getAggregate(Src);
551   CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
552   EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
553            Callee, ReturnValueSlot(), CallArgs, MD);
554 }
555 
556 /// SynthesizeDefaultConstructor - synthesize a default constructor
557 void
558 CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
559                                               CXXCtorType Type,
560                                               llvm::Function *Fn,
561                                               const FunctionArgList &Args) {
562   assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
563   StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
564                 SourceLocation());
565   EmitCtorPrologue(Ctor, Type);
566   FinishFunction();
567 }
568 
569 /// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
570 /// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
571 /// The implicitly-defined copy constructor for class X performs a memberwise
572 /// copy of its subobjects. The order of copying is the same as the order of
573 /// initialization of bases and members in a user-defined constructor
574 /// Each subobject is copied in the manner appropriate to its type:
575 ///  if the subobject is of class type, the copy constructor for the class is
576 ///  used;
577 ///  if the subobject is an array, each element is copied, in the manner
578 ///  appropriate to the element type;
579 ///  if the subobject is of scalar type, the built-in assignment operator is
580 ///  used.
581 /// Virtual base class subobjects shall be copied only once by the
582 /// implicitly-defined copy constructor
583 
584 void
585 CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
586                                               CXXCtorType Type,
587                                               llvm::Function *Fn,
588                                               const FunctionArgList &Args) {
589   const CXXRecordDecl *ClassDecl = Ctor->getParent();
590   assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
591       "SynthesizeCXXCopyConstructor - copy constructor has definition already");
592   assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
593   StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
594                 SourceLocation());
595 
596   FunctionArgList::const_iterator i = Args.begin();
597   const VarDecl *ThisArg = i->first;
598   llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
599   llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
600   const VarDecl *SrcArg = (i+1)->first;
601   llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
602   llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
603 
604   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
605        Base != ClassDecl->bases_end(); ++Base) {
606     // FIXME. copy constrution of virtual base NYI
607     if (Base->isVirtual())
608       continue;
609 
610     CXXRecordDecl *BaseClassDecl
611       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
612     EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
613                             Base->getType());
614   }
615 
616   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
617        E = ClassDecl->field_end(); I != E; ++I) {
618     const FieldDecl *Field = *I;
619 
620     QualType FieldType = getContext().getCanonicalType(Field->getType());
621     const ConstantArrayType *Array =
622       getContext().getAsConstantArrayType(FieldType);
623     if (Array)
624       FieldType = getContext().getBaseElementType(FieldType);
625 
626     if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
627       CXXRecordDecl *FieldClassDecl
628         = cast<CXXRecordDecl>(FieldClassType->getDecl());
629       LValue LHS = EmitLValueForField(LoadOfThis, Field, 0);
630       LValue RHS = EmitLValueForField(LoadOfSrc, Field, 0);
631       if (Array) {
632         const llvm::Type *BasePtr = ConvertType(FieldType);
633         BasePtr = llvm::PointerType::getUnqual(BasePtr);
634         llvm::Value *DestBaseAddrPtr =
635           Builder.CreateBitCast(LHS.getAddress(), BasePtr);
636         llvm::Value *SrcBaseAddrPtr =
637           Builder.CreateBitCast(RHS.getAddress(), BasePtr);
638         EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
639                                     FieldClassDecl, FieldType);
640       }
641       else
642         EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
643                                 0 /*ClassDecl*/, FieldClassDecl, FieldType);
644       continue;
645     }
646 
647     // Do a built-in assignment of scalar data members.
648     LValue LHS = EmitLValueForFieldInitialization(LoadOfThis, Field, 0);
649     LValue RHS = EmitLValueForFieldInitialization(LoadOfSrc, Field, 0);
650 
651     if (!hasAggregateLLVMType(Field->getType())) {
652       RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
653       EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
654     } else if (Field->getType()->isAnyComplexType()) {
655       ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
656                                                RHS.isVolatileQualified());
657       StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
658     } else {
659       EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
660     }
661   }
662 
663   InitializeVtablePtrs(ClassDecl);
664   FinishFunction();
665 }
666 
667 /// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
668 /// Before the implicitly-declared copy assignment operator for a class is
669 /// implicitly defined, all implicitly- declared copy assignment operators for
670 /// its direct base classes and its nonstatic data members shall have been
671 /// implicitly defined. [12.8-p12]
672 /// The implicitly-defined copy assignment operator for class X performs
673 /// memberwise assignment of its subob- jects. The direct base classes of X are
674 /// assigned first, in the order of their declaration in
675 /// the base-specifier-list, and then the immediate nonstatic data members of X
676 /// are assigned, in the order in which they were declared in the class
677 /// definition.Each subobject is assigned in the manner appropriate to its type:
678 ///   if the subobject is of class type, the copy assignment operator for the
679 ///   class is used (as if by explicit qualification; that is, ignoring any
680 ///   possible virtual overriding functions in more derived classes);
681 ///
682 ///   if the subobject is an array, each element is assigned, in the manner
683 ///   appropriate to the element type;
684 ///
685 ///   if the subobject is of scalar type, the built-in assignment operator is
686 ///   used.
687 void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
688                                                   llvm::Function *Fn,
689                                                   const FunctionArgList &Args) {
690 
691   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
692   assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
693          "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
694   StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
695 
696   FunctionArgList::const_iterator i = Args.begin();
697   const VarDecl *ThisArg = i->first;
698   llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
699   llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
700   const VarDecl *SrcArg = (i+1)->first;
701   llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
702   llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
703 
704   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
705        Base != ClassDecl->bases_end(); ++Base) {
706     // FIXME. copy assignment of virtual base NYI
707     if (Base->isVirtual())
708       continue;
709 
710     CXXRecordDecl *BaseClassDecl
711       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
712     EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
713                             Base->getType());
714   }
715 
716   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
717        FieldEnd = ClassDecl->field_end();
718        Field != FieldEnd; ++Field) {
719     QualType FieldType = getContext().getCanonicalType((*Field)->getType());
720     const ConstantArrayType *Array =
721       getContext().getAsConstantArrayType(FieldType);
722     if (Array)
723       FieldType = getContext().getBaseElementType(FieldType);
724 
725     if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
726       CXXRecordDecl *FieldClassDecl
727       = cast<CXXRecordDecl>(FieldClassType->getDecl());
728       LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
729       LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
730       if (Array) {
731         const llvm::Type *BasePtr = ConvertType(FieldType);
732         BasePtr = llvm::PointerType::getUnqual(BasePtr);
733         llvm::Value *DestBaseAddrPtr =
734           Builder.CreateBitCast(LHS.getAddress(), BasePtr);
735         llvm::Value *SrcBaseAddrPtr =
736           Builder.CreateBitCast(RHS.getAddress(), BasePtr);
737         EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
738                                     FieldClassDecl, FieldType);
739       }
740       else
741         EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
742                                0 /*ClassDecl*/, FieldClassDecl, FieldType);
743       continue;
744     }
745     // Do a built-in assignment of scalar data members.
746     LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
747     LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
748     if (!hasAggregateLLVMType(Field->getType())) {
749       RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
750       EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
751     } else if (Field->getType()->isAnyComplexType()) {
752       ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
753                                                RHS.isVolatileQualified());
754       StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
755     } else {
756       EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
757     }
758   }
759 
760   // return *this;
761   Builder.CreateStore(LoadOfThis, ReturnValue);
762 
763   FinishFunction();
764 }
765 
766 static void EmitBaseInitializer(CodeGenFunction &CGF,
767                                 const CXXRecordDecl *ClassDecl,
768                                 CXXBaseOrMemberInitializer *BaseInit,
769                                 CXXCtorType CtorType) {
770   assert(BaseInit->isBaseInitializer() &&
771          "Must have base initializer!");
772 
773   llvm::Value *ThisPtr = CGF.LoadCXXThis();
774 
775   const Type *BaseType = BaseInit->getBaseClass();
776   CXXRecordDecl *BaseClassDecl =
777     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
778 
779   // FIXME: This method of determining whether a base is virtual is ridiculous;
780   // it should be part of BaseInit.
781   bool isBaseVirtual = false;
782   for (CXXRecordDecl::base_class_const_iterator I = ClassDecl->vbases_begin(),
783        E = ClassDecl->vbases_end(); I != E; ++I)
784     if (I->getType()->getAs<RecordType>()->getDecl() == BaseClassDecl) {
785       isBaseVirtual = true;
786       break;
787     }
788 
789   // The base constructor doesn't construct virtual bases.
790   if (CtorType == Ctor_Base && isBaseVirtual)
791     return;
792 
793   // Compute the offset to the base; we do this directly instead of using
794   // GetAddressOfBaseClass because the class doesn't have a vtable pointer
795   // at this point.
796   // FIXME: This could be refactored back into GetAddressOfBaseClass if it took
797   // an extra parameter for whether the derived class is the complete object
798   // class.
799   const ASTRecordLayout &Layout =
800       CGF.getContext().getASTRecordLayout(ClassDecl);
801   uint64_t Offset;
802   if (isBaseVirtual)
803     Offset = Layout.getVBaseClassOffset(BaseClassDecl);
804   else
805     Offset = Layout.getBaseClassOffset(BaseClassDecl);
806   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
807   const llvm::Type *BaseClassType = CGF.ConvertType(QualType(BaseType, 0));
808   llvm::Value *V = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
809   V = CGF.Builder.CreateConstInBoundsGEP1_64(V, Offset/8);
810   V = CGF.Builder.CreateBitCast(V, BaseClassType->getPointerTo());
811   CGF.EmitAggExpr(BaseInit->getInit(), V, false, false, true);
812 
813   if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor()) {
814     // FIXME: Is this OK for C++0x delegating constructors?
815     CodeGenFunction::EHCleanupBlock Cleanup(CGF);
816 
817     llvm::Value *ThisPtr = CGF.LoadCXXThis();
818     llvm::Value *V = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
819     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
820     V = CGF.Builder.CreateBitCast(V, BaseClassType->getPointerTo());
821 
822     CXXDestructorDecl *DD = BaseClassDecl->getDestructor(CGF.getContext());
823     CGF.EmitCXXDestructorCall(DD, Dtor_Base, V);
824   }
825 }
826 
827 static void EmitMemberInitializer(CodeGenFunction &CGF,
828                                   const CXXRecordDecl *ClassDecl,
829                                   CXXBaseOrMemberInitializer *MemberInit) {
830   assert(MemberInit->isMemberInitializer() &&
831          "Must have member initializer!");
832 
833   // non-static data member initializers.
834   FieldDecl *Field = MemberInit->getMember();
835   QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
836 
837   llvm::Value *ThisPtr = CGF.LoadCXXThis();
838   LValue LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
839 
840   // If we are initializing an anonymous union field, drill down to the field.
841   if (MemberInit->getAnonUnionMember()) {
842     Field = MemberInit->getAnonUnionMember();
843     LHS = CGF.EmitLValueForField(LHS.getAddress(), Field, 0);
844     FieldType = Field->getType();
845   }
846 
847   // FIXME: If there's no initializer and the CXXBaseOrMemberInitializer
848   // was implicitly generated, we shouldn't be zeroing memory.
849   RValue RHS;
850   if (FieldType->isReferenceType()) {
851     RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(),
852                                          /*IsInitializer=*/true);
853     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
854   } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
855     CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
856   } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
857     RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit(), true));
858     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
859   } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
860     CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
861                                 LHS.isVolatileQualified());
862   } else {
863     CGF.EmitAggExpr(MemberInit->getInit(), LHS.getAddress(),
864                     LHS.isVolatileQualified(), false, true);
865 
866     if (!CGF.Exceptions)
867       return;
868 
869     const RecordType *RT = FieldType->getAs<RecordType>();
870     if (!RT)
871       return;
872 
873     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
874     if (!RD->hasTrivialDestructor()) {
875       // FIXME: Is this OK for C++0x delegating constructors?
876       CodeGenFunction::EHCleanupBlock Cleanup(CGF);
877 
878       llvm::Value *ThisPtr = CGF.LoadCXXThis();
879       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
880 
881       CXXDestructorDecl *DD = RD->getDestructor(CGF.getContext());
882       CGF.EmitCXXDestructorCall(DD, Dtor_Complete, LHS.getAddress());
883     }
884   }
885 }
886 
887 /// EmitCtorPrologue - This routine generates necessary code to initialize
888 /// base classes and non-static data members belonging to this constructor.
889 /// FIXME: This needs to take a CXXCtorType.
890 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
891                                        CXXCtorType CtorType) {
892   const CXXRecordDecl *ClassDecl = CD->getParent();
893 
894   llvm::SmallVector<CXXBaseOrMemberInitializer *, 8> MemberInitializers;
895 
896   // FIXME: Add vbase initialization
897 
898   for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
899        E = CD->init_end();
900        B != E; ++B) {
901     CXXBaseOrMemberInitializer *Member = (*B);
902 
903     assert(LiveTemporaries.empty() &&
904            "Should not have any live temporaries at initializer start!");
905 
906     if (Member->isBaseInitializer())
907       EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
908     else
909       MemberInitializers.push_back(Member);
910   }
911 
912   InitializeVtablePtrs(ClassDecl);
913 
914   for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) {
915     assert(LiveTemporaries.empty() &&
916            "Should not have any live temporaries at initializer start!");
917 
918     EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I]);
919   }
920 }
921 
922 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
923 /// destructor. This is to call destructors on members and base classes
924 /// in reverse order of their construction.
925 /// FIXME: This needs to take a CXXDtorType.
926 void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
927                                        CXXDtorType DtorType) {
928   assert(!DD->isTrivial() &&
929          "Should not emit dtor epilogue for trivial dtor!");
930 
931   const CXXRecordDecl *ClassDecl = DD->getParent();
932 
933   // Collect the fields.
934   llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
935   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
936        E = ClassDecl->field_end(); I != E; ++I) {
937     const FieldDecl *Field = *I;
938 
939     QualType FieldType = getContext().getCanonicalType(Field->getType());
940     FieldType = getContext().getBaseElementType(FieldType);
941 
942     const RecordType *RT = FieldType->getAs<RecordType>();
943     if (!RT)
944       continue;
945 
946     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
947     if (FieldClassDecl->hasTrivialDestructor())
948         continue;
949 
950     FieldDecls.push_back(Field);
951   }
952 
953   // Now destroy the fields.
954   for (size_t i = FieldDecls.size(); i > 0; --i) {
955     const FieldDecl *Field = FieldDecls[i - 1];
956 
957     QualType FieldType = Field->getType();
958     const ConstantArrayType *Array =
959       getContext().getAsConstantArrayType(FieldType);
960     if (Array)
961       FieldType = getContext().getBaseElementType(FieldType);
962 
963     const RecordType *RT = FieldType->getAs<RecordType>();
964     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
965 
966     llvm::Value *ThisPtr = LoadCXXThis();
967 
968     LValue LHS = EmitLValueForField(ThisPtr, Field,
969                                     // FIXME: Qualifiers?
970                                     /*CVRQualifiers=*/0);
971     if (Array) {
972       const llvm::Type *BasePtr = ConvertType(FieldType);
973       BasePtr = llvm::PointerType::getUnqual(BasePtr);
974       llvm::Value *BaseAddrPtr =
975         Builder.CreateBitCast(LHS.getAddress(), BasePtr);
976       EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
977                                 Array, BaseAddrPtr);
978     } else
979       EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
980                             Dtor_Complete, LHS.getAddress());
981   }
982 
983   // Destroy non-virtual bases.
984   for (CXXRecordDecl::reverse_base_class_const_iterator I =
985         ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
986     const CXXBaseSpecifier &Base = *I;
987 
988     // Ignore virtual bases.
989     if (Base.isVirtual())
990       continue;
991 
992     CXXRecordDecl *BaseClassDecl
993       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
994 
995     // Ignore trivial destructors.
996     if (BaseClassDecl->hasTrivialDestructor())
997       continue;
998     const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
999 
1000     llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1001                                            ClassDecl, BaseClassDecl,
1002                                            /*NullCheckValue=*/false);
1003     EmitCXXDestructorCall(D, Dtor_Base, V);
1004   }
1005 
1006   // If we're emitting a base destructor, we don't want to emit calls to the
1007   // virtual bases.
1008   if (DtorType == Dtor_Base)
1009     return;
1010 
1011   // Handle virtual bases.
1012   for (CXXRecordDecl::reverse_base_class_const_iterator I =
1013        ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
1014     const CXXBaseSpecifier &Base = *I;
1015     CXXRecordDecl *BaseClassDecl
1016     = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1017 
1018     // Ignore trivial destructors.
1019     if (BaseClassDecl->hasTrivialDestructor())
1020       continue;
1021     const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1022     llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1023                                            ClassDecl, BaseClassDecl,
1024                                            /*NullCheckValue=*/false);
1025     EmitCXXDestructorCall(D, Dtor_Base, V);
1026   }
1027 
1028   // If we have a deleting destructor, emit a call to the delete operator.
1029   if (DtorType == Dtor_Deleting) {
1030     assert(DD->getOperatorDelete() &&
1031            "operator delete missing - EmitDtorEpilogue");
1032     EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1033                    getContext().getTagDeclType(ClassDecl));
1034   }
1035 }
1036 
1037 void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1038                                                   CXXDtorType DtorType,
1039                                                   llvm::Function *Fn,
1040                                                   const FunctionArgList &Args) {
1041   assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
1042          "SynthesizeDefaultDestructor - destructor has user declaration");
1043 
1044   StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1045                 SourceLocation());
1046   InitializeVtablePtrs(Dtor->getParent());
1047   EmitDtorEpilogue(Dtor, DtorType);
1048   FinishFunction();
1049 }
1050 
1051 /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1052 /// for-loop to call the default constructor on individual members of the
1053 /// array.
1054 /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1055 /// array type and 'ArrayPtr' points to the beginning fo the array.
1056 /// It is assumed that all relevant checks have been made by the caller.
1057 void
1058 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1059                                           const ConstantArrayType *ArrayTy,
1060                                           llvm::Value *ArrayPtr,
1061                                           CallExpr::const_arg_iterator ArgBeg,
1062                                           CallExpr::const_arg_iterator ArgEnd) {
1063 
1064   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1065   llvm::Value * NumElements =
1066     llvm::ConstantInt::get(SizeTy,
1067                            getContext().getConstantArrayElementCount(ArrayTy));
1068 
1069   EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
1070 }
1071 
1072 void
1073 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1074                                           llvm::Value *NumElements,
1075                                           llvm::Value *ArrayPtr,
1076                                           CallExpr::const_arg_iterator ArgBeg,
1077                                           CallExpr::const_arg_iterator ArgEnd) {
1078   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1079 
1080   // Create a temporary for the loop index and initialize it with 0.
1081   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1082   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1083   Builder.CreateStore(Zero, IndexPtr);
1084 
1085   // Start the loop with a block that tests the condition.
1086   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1087   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1088 
1089   EmitBlock(CondBlock);
1090 
1091   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1092 
1093   // Generate: if (loop-index < number-of-elements fall to the loop body,
1094   // otherwise, go to the block after the for-loop.
1095   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1096   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1097   // If the condition is true, execute the body.
1098   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1099 
1100   EmitBlock(ForBody);
1101 
1102   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1103   // Inside the loop body, emit the constructor call on the array element.
1104   Counter = Builder.CreateLoad(IndexPtr);
1105   llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1106                                                    "arrayidx");
1107 
1108   // C++ [class.temporary]p4:
1109   // There are two contexts in which temporaries are destroyed at a different
1110   // point than the end of the full-expression. The first context is when a
1111   // default constructor is called to initialize an element of an array.
1112   // If the constructor has one or more default arguments, the destruction of
1113   // every temporary created in a default argument expression is sequenced
1114   // before the construction of the next array element, if any.
1115 
1116   // Keep track of the current number of live temporaries.
1117   unsigned OldNumLiveTemporaries = LiveTemporaries.size();
1118 
1119   EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
1120 
1121   // Pop temporaries.
1122   while (LiveTemporaries.size() > OldNumLiveTemporaries)
1123     PopCXXTemporary();
1124 
1125   EmitBlock(ContinueBlock);
1126 
1127   // Emit the increment of the loop counter.
1128   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1129   Counter = Builder.CreateLoad(IndexPtr);
1130   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1131   Builder.CreateStore(NextVal, IndexPtr);
1132 
1133   // Finally, branch back up to the condition for the next iteration.
1134   EmitBranch(CondBlock);
1135 
1136   // Emit the fall-through block.
1137   EmitBlock(AfterFor, true);
1138 }
1139 
1140 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1141 /// elements in reverse order of construction.
1142 void
1143 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1144                                            const ArrayType *Array,
1145                                            llvm::Value *This) {
1146   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1147   assert(CA && "Do we support VLA for destruction ?");
1148   uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1149 
1150   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1151   llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1152   EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1153 }
1154 
1155 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1156 /// elements in reverse order of construction.
1157 void
1158 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1159                                            llvm::Value *UpperCount,
1160                                            llvm::Value *This) {
1161   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1162   llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1163 
1164   // Create a temporary for the loop index and initialize it with count of
1165   // array elements.
1166   llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1167 
1168   // Store the number of elements in the index pointer.
1169   Builder.CreateStore(UpperCount, IndexPtr);
1170 
1171   // Start the loop with a block that tests the condition.
1172   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1173   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1174 
1175   EmitBlock(CondBlock);
1176 
1177   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1178 
1179   // Generate: if (loop-index != 0 fall to the loop body,
1180   // otherwise, go to the block after the for-loop.
1181   llvm::Value* zeroConstant =
1182     llvm::Constant::getNullValue(SizeLTy);
1183   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1184   llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1185                                             "isne");
1186   // If the condition is true, execute the body.
1187   Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1188 
1189   EmitBlock(ForBody);
1190 
1191   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1192   // Inside the loop body, emit the constructor call on the array element.
1193   Counter = Builder.CreateLoad(IndexPtr);
1194   Counter = Builder.CreateSub(Counter, One);
1195   llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1196   EmitCXXDestructorCall(D, Dtor_Complete, Address);
1197 
1198   EmitBlock(ContinueBlock);
1199 
1200   // Emit the decrement of the loop counter.
1201   Counter = Builder.CreateLoad(IndexPtr);
1202   Counter = Builder.CreateSub(Counter, One, "dec");
1203   Builder.CreateStore(Counter, IndexPtr);
1204 
1205   // Finally, branch back up to the condition for the next iteration.
1206   EmitBranch(CondBlock);
1207 
1208   // Emit the fall-through block.
1209   EmitBlock(AfterFor, true);
1210 }
1211 
1212 /// GenerateCXXAggrDestructorHelper - Generates a helper function which when
1213 /// invoked, calls the default destructor on array elements in reverse order of
1214 /// construction.
1215 llvm::Constant *
1216 CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1217                                                  const ArrayType *Array,
1218                                                  llvm::Value *This) {
1219   FunctionArgList Args;
1220   ImplicitParamDecl *Dst =
1221     ImplicitParamDecl::Create(getContext(), 0,
1222                               SourceLocation(), 0,
1223                               getContext().getPointerType(getContext().VoidTy));
1224   Args.push_back(std::make_pair(Dst, Dst->getType()));
1225 
1226   llvm::SmallString<16> Name;
1227   llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
1228   QualType R = getContext().VoidTy;
1229   const CGFunctionInfo &FI
1230     = CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
1231   const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
1232   llvm::Function *Fn =
1233     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
1234                            Name.str(),
1235                            &CGM.getModule());
1236   IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
1237   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1238                                           getContext().getTranslationUnitDecl(),
1239                                           SourceLocation(), II, R, 0,
1240                                           FunctionDecl::Static,
1241                                           false, true);
1242   StartFunction(FD, R, Fn, Args, SourceLocation());
1243   QualType BaseElementTy = getContext().getBaseElementType(Array);
1244   const llvm::Type *BasePtr = ConvertType(BaseElementTy);
1245   BasePtr = llvm::PointerType::getUnqual(BasePtr);
1246   llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
1247   EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
1248   FinishFunction();
1249   llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
1250                                               0);
1251   llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1252   return m;
1253 }
1254 
1255 
1256 void
1257 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1258                                         CXXCtorType Type,
1259                                         llvm::Value *This,
1260                                         CallExpr::const_arg_iterator ArgBeg,
1261                                         CallExpr::const_arg_iterator ArgEnd) {
1262   if (D->isTrivial()) {
1263     if (ArgBeg == ArgEnd) {
1264       // Trivial default constructor, no codegen required.
1265       assert(D->isDefaultConstructor() &&
1266              "trivial 0-arg ctor not a default ctor");
1267       return;
1268     }
1269 
1270     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1271     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1272 
1273     const Expr *E = (*ArgBeg);
1274     QualType Ty = E->getType();
1275     llvm::Value *Src = EmitLValue(E).getAddress();
1276     EmitAggregateCopy(This, Src, Ty);
1277     return;
1278   }
1279 
1280   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type));
1281   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1282 
1283   EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
1284 }
1285 
1286 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1287                                             CXXDtorType Type,
1288                                             llvm::Value *This) {
1289   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type));
1290   llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1291 
1292   EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
1293 }
1294 
1295 llvm::Value *
1296 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1297                                            const CXXRecordDecl *ClassDecl,
1298                                            const CXXRecordDecl *BaseClassDecl) {
1299   const llvm::Type *Int8PtrTy =
1300     llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1301 
1302   llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1303                                                  Int8PtrTy->getPointerTo());
1304   VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1305 
1306   int64_t VBaseOffsetIndex =
1307     CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1308 
1309   llvm::Value *VBaseOffsetPtr =
1310     Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
1311   const llvm::Type *PtrDiffTy =
1312     ConvertType(getContext().getPointerDiffType());
1313 
1314   VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1315                                          PtrDiffTy->getPointerTo());
1316 
1317   llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1318 
1319   return VBaseOffset;
1320 }
1321 
1322 void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
1323   if (!ClassDecl->isDynamicClass())
1324     return;
1325 
1326   llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1327   CGVtableInfo::AddrSubMap_t& AddressPoints =
1328       *(*CGM.getVtableInfo().AddressPoints[ClassDecl])[ClassDecl];
1329   llvm::Value *ThisPtr = LoadCXXThis();
1330   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassDecl);
1331 
1332   // Store address points for virtual bases
1333   for (CXXRecordDecl::base_class_const_iterator I =
1334        ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); I != E; ++I) {
1335     const CXXBaseSpecifier &Base = *I;
1336     CXXRecordDecl *BaseClassDecl
1337       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1338     uint64_t Offset = Layout.getVBaseClassOffset(BaseClassDecl);
1339     InitializeVtablePtrsRecursive(BaseClassDecl, Vtable, AddressPoints,
1340                                   ThisPtr, Offset);
1341   }
1342 
1343   // Store address points for non-virtual bases and current class
1344   InitializeVtablePtrsRecursive(ClassDecl, Vtable, AddressPoints, ThisPtr, 0);
1345 }
1346 
1347 void CodeGenFunction::InitializeVtablePtrsRecursive(
1348         const CXXRecordDecl *ClassDecl,
1349         llvm::Constant *Vtable,
1350         CGVtableInfo::AddrSubMap_t& AddressPoints,
1351         llvm::Value *ThisPtr,
1352         uint64_t Offset) {
1353   if (!ClassDecl->isDynamicClass())
1354     return;
1355 
1356   // Store address points for non-virtual bases
1357   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassDecl);
1358   for (CXXRecordDecl::base_class_const_iterator I =
1359        ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1360     const CXXBaseSpecifier &Base = *I;
1361     if (Base.isVirtual())
1362       continue;
1363     CXXRecordDecl *BaseClassDecl
1364       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1365     uint64_t NewOffset = Offset + Layout.getBaseClassOffset(BaseClassDecl);
1366     InitializeVtablePtrsRecursive(BaseClassDecl, Vtable, AddressPoints,
1367                                   ThisPtr, NewOffset);
1368   }
1369 
1370   // Compute the address point
1371   assert(AddressPoints.count(std::make_pair(ClassDecl, Offset)) &&
1372          "Missing address point for class");
1373   uint64_t AddressPoint = AddressPoints[std::make_pair(ClassDecl, Offset)];
1374   llvm::Value *VtableAddressPoint =
1375       Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1376 
1377   // Compute the address to store the address point
1378   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
1379   llvm::Value *VtableField = Builder.CreateBitCast(ThisPtr, Int8PtrTy);
1380   VtableField = Builder.CreateConstInBoundsGEP1_64(VtableField, Offset/8);
1381   const llvm::Type *AddressPointPtrTy =
1382       VtableAddressPoint->getType()->getPointerTo();
1383   VtableField = Builder.CreateBitCast(VtableField, AddressPointPtrTy);
1384 
1385   // Store address point
1386   Builder.CreateStore(VtableAddressPoint, VtableField);
1387 }
1388 
1389 llvm::Value *CodeGenFunction::LoadCXXVTT() {
1390   assert((isa<CXXConstructorDecl>(CurFuncDecl) ||
1391           isa<CXXDestructorDecl>(CurFuncDecl)) &&
1392          "Must be in a C++ ctor or dtor to load the vtt parameter");
1393 
1394   return Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
1395 }
1396