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