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 "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/EvaluatedExprVisitor.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 
22 using namespace clang;
23 using namespace CodeGen;
24 
25 static CharUnits
26 ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27                                  const CXXRecordDecl *DerivedClass,
28                                  CastExpr::path_const_iterator Start,
29                                  CastExpr::path_const_iterator End) {
30   CharUnits Offset = CharUnits::Zero();
31 
32   const CXXRecordDecl *RD = DerivedClass;
33 
34   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
35     const CXXBaseSpecifier *Base = *I;
36     assert(!Base->isVirtual() && "Should not see virtual bases here!");
37 
38     // Get the layout.
39     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40 
41     const CXXRecordDecl *BaseDecl =
42       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43 
44     // Add the offset.
45     Offset += Layout.getBaseClassOffset(BaseDecl);
46 
47     RD = BaseDecl;
48   }
49 
50   return Offset;
51 }
52 
53 llvm::Constant *
54 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
55                                    CastExpr::path_const_iterator PathBegin,
56                                    CastExpr::path_const_iterator PathEnd) {
57   assert(PathBegin != PathEnd && "Base path should not be empty!");
58 
59   CharUnits Offset =
60     ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61                                      PathBegin, PathEnd);
62   if (Offset.isZero())
63     return 0;
64 
65   const llvm::Type *PtrDiffTy =
66   Types.ConvertType(getContext().getPointerDiffType());
67 
68   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
69 }
70 
71 /// Gets the address of a direct base class within a complete object.
72 /// This should only be used for (1) non-virtual bases or (2) virtual bases
73 /// when the type is known to be complete (e.g. in complete destructors).
74 ///
75 /// The object pointed to by 'This' is assumed to be non-null.
76 llvm::Value *
77 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78                                                    const CXXRecordDecl *Derived,
79                                                    const CXXRecordDecl *Base,
80                                                    bool BaseIsVirtual) {
81   // 'this' must be a pointer (in some address space) to Derived.
82   assert(This->getType()->isPointerTy() &&
83          cast<llvm::PointerType>(This->getType())->getElementType()
84            == ConvertType(Derived));
85 
86   // Compute the offset of the virtual base.
87   CharUnits Offset;
88   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
89   if (BaseIsVirtual)
90     Offset = Layout.getVBaseClassOffset(Base);
91   else
92     Offset = Layout.getBaseClassOffset(Base);
93 
94   // Shift and cast down to the base type.
95   // TODO: for complete types, this should be possible with a GEP.
96   llvm::Value *V = This;
97   if (Offset.isPositive()) {
98     const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
99     V = Builder.CreateBitCast(V, Int8PtrTy);
100     V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
101   }
102   V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103 
104   return V;
105 }
106 
107 static llvm::Value *
108 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
109                                 CharUnits NonVirtual, llvm::Value *Virtual) {
110   const llvm::Type *PtrDiffTy =
111     CGF.ConvertType(CGF.getContext().getPointerDiffType());
112 
113   llvm::Value *NonVirtualOffset = 0;
114   if (!NonVirtual.isZero())
115     NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116                                               NonVirtual.getQuantity());
117 
118   llvm::Value *BaseOffset;
119   if (Virtual) {
120     if (NonVirtualOffset)
121       BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122     else
123       BaseOffset = Virtual;
124   } else
125     BaseOffset = NonVirtualOffset;
126 
127   // Apply the base offset.
128   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
129   ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
130   ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
131 
132   return ThisPtr;
133 }
134 
135 llvm::Value *
136 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
137                                        const CXXRecordDecl *Derived,
138                                        CastExpr::path_const_iterator PathBegin,
139                                        CastExpr::path_const_iterator PathEnd,
140                                        bool NullCheckValue) {
141   assert(PathBegin != PathEnd && "Base path should not be empty!");
142 
143   CastExpr::path_const_iterator Start = PathBegin;
144   const CXXRecordDecl *VBase = 0;
145 
146   // Get the virtual base.
147   if ((*Start)->isVirtual()) {
148     VBase =
149       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150     ++Start;
151   }
152 
153   CharUnits NonVirtualOffset =
154     ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
155                                      Start, PathEnd);
156 
157   // Get the base pointer type.
158   const llvm::Type *BasePtrTy =
159     ConvertType((PathEnd[-1])->getType())->getPointerTo();
160 
161   if (NonVirtualOffset.isZero() && !VBase) {
162     // Just cast back.
163     return Builder.CreateBitCast(Value, BasePtrTy);
164   }
165 
166   llvm::BasicBlock *CastNull = 0;
167   llvm::BasicBlock *CastNotNull = 0;
168   llvm::BasicBlock *CastEnd = 0;
169 
170   if (NullCheckValue) {
171     CastNull = createBasicBlock("cast.null");
172     CastNotNull = createBasicBlock("cast.notnull");
173     CastEnd = createBasicBlock("cast.end");
174 
175     llvm::Value *IsNull = Builder.CreateIsNull(Value);
176     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177     EmitBlock(CastNotNull);
178   }
179 
180   llvm::Value *VirtualOffset = 0;
181 
182   if (VBase) {
183     if (Derived->hasAttr<FinalAttr>()) {
184       VirtualOffset = 0;
185 
186       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
187 
188       CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
189       NonVirtualOffset += VBaseOffset;
190     } else
191       VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
192   }
193 
194   // Apply the offsets.
195   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
196                                           NonVirtualOffset,
197                                           VirtualOffset);
198 
199   // Cast back.
200   Value = Builder.CreateBitCast(Value, BasePtrTy);
201 
202   if (NullCheckValue) {
203     Builder.CreateBr(CastEnd);
204     EmitBlock(CastNull);
205     Builder.CreateBr(CastEnd);
206     EmitBlock(CastEnd);
207 
208     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
209     PHI->addIncoming(Value, CastNotNull);
210     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
211                      CastNull);
212     Value = PHI;
213   }
214 
215   return Value;
216 }
217 
218 llvm::Value *
219 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
220                                           const CXXRecordDecl *Derived,
221                                         CastExpr::path_const_iterator PathBegin,
222                                           CastExpr::path_const_iterator PathEnd,
223                                           bool NullCheckValue) {
224   assert(PathBegin != PathEnd && "Base path should not be empty!");
225 
226   QualType DerivedTy =
227     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
228   const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
229 
230   llvm::Value *NonVirtualOffset =
231     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
232 
233   if (!NonVirtualOffset) {
234     // No offset, we can just cast back.
235     return Builder.CreateBitCast(Value, DerivedPtrTy);
236   }
237 
238   llvm::BasicBlock *CastNull = 0;
239   llvm::BasicBlock *CastNotNull = 0;
240   llvm::BasicBlock *CastEnd = 0;
241 
242   if (NullCheckValue) {
243     CastNull = createBasicBlock("cast.null");
244     CastNotNull = createBasicBlock("cast.notnull");
245     CastEnd = createBasicBlock("cast.end");
246 
247     llvm::Value *IsNull = Builder.CreateIsNull(Value);
248     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
249     EmitBlock(CastNotNull);
250   }
251 
252   // Apply the offset.
253   Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
254   Value = Builder.CreateSub(Value, NonVirtualOffset);
255   Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
256 
257   // Just cast.
258   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
259 
260   if (NullCheckValue) {
261     Builder.CreateBr(CastEnd);
262     EmitBlock(CastNull);
263     Builder.CreateBr(CastEnd);
264     EmitBlock(CastEnd);
265 
266     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
267     PHI->addIncoming(Value, CastNotNull);
268     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
269                      CastNull);
270     Value = PHI;
271   }
272 
273   return Value;
274 }
275 
276 /// GetVTTParameter - Return the VTT parameter that should be passed to a
277 /// base constructor/destructor with virtual bases.
278 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
279                                     bool ForVirtualBase) {
280   if (!CodeGenVTables::needsVTTParameter(GD)) {
281     // This constructor/destructor does not need a VTT parameter.
282     return 0;
283   }
284 
285   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
286   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
287 
288   llvm::Value *VTT;
289 
290   uint64_t SubVTTIndex;
291 
292   // If the record matches the base, this is the complete ctor/dtor
293   // variant calling the base variant in a class with virtual bases.
294   if (RD == Base) {
295     assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
296            "doing no-op VTT offset in base dtor/ctor?");
297     assert(!ForVirtualBase && "Can't have same class as virtual base!");
298     SubVTTIndex = 0;
299   } else {
300     const ASTRecordLayout &Layout =
301       CGF.getContext().getASTRecordLayout(RD);
302     CharUnits BaseOffset = ForVirtualBase ?
303       Layout.getVBaseClassOffset(Base) :
304       Layout.getBaseClassOffset(Base);
305 
306     SubVTTIndex =
307       CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
308     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
309   }
310 
311   if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
312     // A VTT parameter was passed to the constructor, use it.
313     VTT = CGF.LoadCXXVTT();
314     VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
315   } else {
316     // We're the complete constructor, so get the VTT by name.
317     VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
318     VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
319   }
320 
321   return VTT;
322 }
323 
324 namespace {
325   /// Call the destructor for a direct base class.
326   struct CallBaseDtor : EHScopeStack::Cleanup {
327     const CXXRecordDecl *BaseClass;
328     bool BaseIsVirtual;
329     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
330       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
331 
332     void Emit(CodeGenFunction &CGF, bool IsForEH) {
333       const CXXRecordDecl *DerivedClass =
334         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
335 
336       const CXXDestructorDecl *D = BaseClass->getDestructor();
337       llvm::Value *Addr =
338         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
339                                                   DerivedClass, BaseClass,
340                                                   BaseIsVirtual);
341       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
342     }
343   };
344 
345   /// A visitor which checks whether an initializer uses 'this' in a
346   /// way which requires the vtable to be properly set.
347   struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
348     typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
349 
350     bool UsesThis;
351 
352     DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
353 
354     // Black-list all explicit and implicit references to 'this'.
355     //
356     // Do we need to worry about external references to 'this' derived
357     // from arbitrary code?  If so, then anything which runs arbitrary
358     // external code might potentially access the vtable.
359     void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
360   };
361 }
362 
363 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
364   DynamicThisUseChecker Checker(C);
365   Checker.Visit(const_cast<Expr*>(Init));
366   return Checker.UsesThis;
367 }
368 
369 static void EmitBaseInitializer(CodeGenFunction &CGF,
370                                 const CXXRecordDecl *ClassDecl,
371                                 CXXCtorInitializer *BaseInit,
372                                 CXXCtorType CtorType) {
373   assert(BaseInit->isBaseInitializer() &&
374          "Must have base initializer!");
375 
376   llvm::Value *ThisPtr = CGF.LoadCXXThis();
377 
378   const Type *BaseType = BaseInit->getBaseClass();
379   CXXRecordDecl *BaseClassDecl =
380     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
381 
382   bool isBaseVirtual = BaseInit->isBaseVirtual();
383 
384   // The base constructor doesn't construct virtual bases.
385   if (CtorType == Ctor_Base && isBaseVirtual)
386     return;
387 
388   // If the initializer for the base (other than the constructor
389   // itself) accesses 'this' in any way, we need to initialize the
390   // vtables.
391   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
392     CGF.InitializeVTablePointers(ClassDecl);
393 
394   // We can pretend to be a complete class because it only matters for
395   // virtual bases, and we only do virtual bases for complete ctors.
396   llvm::Value *V =
397     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
398                                               BaseClassDecl,
399                                               isBaseVirtual);
400 
401   AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
402 
403   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
404 
405   if (CGF.CGM.getLangOptions().Exceptions &&
406       !BaseClassDecl->hasTrivialDestructor())
407     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
408                                           isBaseVirtual);
409 }
410 
411 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
412                                      LValue LHS,
413                                      llvm::Value *ArrayIndexVar,
414                                      CXXCtorInitializer *MemberInit,
415                                      QualType T,
416                                      unsigned Index) {
417   if (Index == MemberInit->getNumArrayIndices()) {
418     CodeGenFunction::RunCleanupsScope Cleanups(CGF);
419 
420     llvm::Value *Dest = LHS.getAddress();
421     if (ArrayIndexVar) {
422       // If we have an array index variable, load it and use it as an offset.
423       // Then, increment the value.
424       llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
425       Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
426       llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
427       Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
428       CGF.Builder.CreateStore(Next, ArrayIndexVar);
429     }
430 
431     AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
432                                               /*Lifetime*/ true);
433 
434     CGF.EmitAggExpr(MemberInit->getInit(), Slot);
435 
436     return;
437   }
438 
439   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
440   assert(Array && "Array initialization without the array type?");
441   llvm::Value *IndexVar
442     = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
443   assert(IndexVar && "Array index variable not loaded");
444 
445   // Initialize this index variable to zero.
446   llvm::Value* Zero
447     = llvm::Constant::getNullValue(
448                               CGF.ConvertType(CGF.getContext().getSizeType()));
449   CGF.Builder.CreateStore(Zero, IndexVar);
450 
451   // Start the loop with a block that tests the condition.
452   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
453   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
454 
455   CGF.EmitBlock(CondBlock);
456 
457   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
458   // Generate: if (loop-index < number-of-elements) fall to the loop body,
459   // otherwise, go to the block after the for-loop.
460   uint64_t NumElements = Array->getSize().getZExtValue();
461   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
462   llvm::Value *NumElementsPtr =
463     llvm::ConstantInt::get(Counter->getType(), NumElements);
464   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
465                                                   "isless");
466 
467   // If the condition is true, execute the body.
468   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
469 
470   CGF.EmitBlock(ForBody);
471   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
472 
473   {
474     CodeGenFunction::RunCleanupsScope Cleanups(CGF);
475 
476     // Inside the loop body recurse to emit the inner loop or, eventually, the
477     // constructor call.
478     EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
479                              Array->getElementType(), Index + 1);
480   }
481 
482   CGF.EmitBlock(ContinueBlock);
483 
484   // Emit the increment of the loop counter.
485   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
486   Counter = CGF.Builder.CreateLoad(IndexVar);
487   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
488   CGF.Builder.CreateStore(NextVal, IndexVar);
489 
490   // Finally, branch back up to the condition for the next iteration.
491   CGF.EmitBranch(CondBlock);
492 
493   // Emit the fall-through block.
494   CGF.EmitBlock(AfterFor, true);
495 }
496 
497 namespace {
498   struct CallMemberDtor : EHScopeStack::Cleanup {
499     FieldDecl *Field;
500     CXXDestructorDecl *Dtor;
501 
502     CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
503       : Field(Field), Dtor(Dtor) {}
504 
505     void Emit(CodeGenFunction &CGF, bool IsForEH) {
506       // FIXME: Is this OK for C++0x delegating constructors?
507       llvm::Value *ThisPtr = CGF.LoadCXXThis();
508       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
509 
510       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
511                                 LHS.getAddress());
512     }
513   };
514 }
515 
516 static void EmitMemberInitializer(CodeGenFunction &CGF,
517                                   const CXXRecordDecl *ClassDecl,
518                                   CXXCtorInitializer *MemberInit,
519                                   const CXXConstructorDecl *Constructor,
520                                   FunctionArgList &Args) {
521   assert(MemberInit->isAnyMemberInitializer() &&
522          "Must have member initializer!");
523 
524   // non-static data member initializers.
525   FieldDecl *Field = MemberInit->getAnyMember();
526   QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
527 
528   llvm::Value *ThisPtr = CGF.LoadCXXThis();
529   LValue LHS;
530 
531   // If we are initializing an anonymous union field, drill down to the field.
532   if (MemberInit->isIndirectMemberInitializer()) {
533     LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
534                                            MemberInit->getIndirectMember(), 0);
535     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
536   } else {
537     LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
538   }
539 
540   // FIXME: If there's no initializer and the CXXCtorInitializer
541   // was implicitly generated, we shouldn't be zeroing memory.
542   RValue RHS;
543   if (FieldType->isReferenceType()) {
544     RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
545     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
546   } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
547     CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
548   } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
549     RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
550     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
551   } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
552     CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
553                                 LHS.isVolatileQualified());
554   } else {
555     llvm::Value *ArrayIndexVar = 0;
556     const ConstantArrayType *Array
557       = CGF.getContext().getAsConstantArrayType(FieldType);
558     if (Array && Constructor->isImplicit() &&
559         Constructor->isCopyConstructor()) {
560       const llvm::Type *SizeTy
561         = CGF.ConvertType(CGF.getContext().getSizeType());
562 
563       // The LHS is a pointer to the first object we'll be constructing, as
564       // a flat array.
565       QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
566       const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
567       BasePtr = llvm::PointerType::getUnqual(BasePtr);
568       llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
569                                                            BasePtr);
570       LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
571 
572       // Create an array index that will be used to walk over all of the
573       // objects we're constructing.
574       ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
575       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
576       CGF.Builder.CreateStore(Zero, ArrayIndexVar);
577 
578       // If we are copying an array of scalars or classes with trivial copy
579       // constructors, perform a single aggregate copy.
580       const RecordType *Record = BaseElementTy->getAs<RecordType>();
581       if (!Record ||
582           cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
583         // Find the source pointer. We knows it's the last argument because
584         // we know we're in a copy constructor.
585         unsigned SrcArgIndex = Args.size() - 1;
586         llvm::Value *SrcPtr
587           = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
588         LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
589 
590         // Copy the aggregate.
591         CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
592                               LHS.isVolatileQualified());
593         return;
594       }
595 
596       // Emit the block variables for the array indices, if any.
597       for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
598         CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
599     }
600 
601     EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
602 
603     if (!CGF.CGM.getLangOptions().Exceptions)
604       return;
605 
606     // FIXME: If we have an array of classes w/ non-trivial destructors,
607     // we need to destroy in reverse order of construction along the exception
608     // path.
609     const RecordType *RT = FieldType->getAs<RecordType>();
610     if (!RT)
611       return;
612 
613     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
614     if (!RD->hasTrivialDestructor())
615       CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
616                                               RD->getDestructor());
617   }
618 }
619 
620 /// Checks whether the given constructor is a valid subject for the
621 /// complete-to-base constructor delegation optimization, i.e.
622 /// emitting the complete constructor as a simple call to the base
623 /// constructor.
624 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
625 
626   // Currently we disable the optimization for classes with virtual
627   // bases because (1) the addresses of parameter variables need to be
628   // consistent across all initializers but (2) the delegate function
629   // call necessarily creates a second copy of the parameter variable.
630   //
631   // The limiting example (purely theoretical AFAIK):
632   //   struct A { A(int &c) { c++; } };
633   //   struct B : virtual A {
634   //     B(int count) : A(count) { printf("%d\n", count); }
635   //   };
636   // ...although even this example could in principle be emitted as a
637   // delegation since the address of the parameter doesn't escape.
638   if (Ctor->getParent()->getNumVBases()) {
639     // TODO: white-list trivial vbase initializers.  This case wouldn't
640     // be subject to the restrictions below.
641 
642     // TODO: white-list cases where:
643     //  - there are no non-reference parameters to the constructor
644     //  - the initializers don't access any non-reference parameters
645     //  - the initializers don't take the address of non-reference
646     //    parameters
647     //  - etc.
648     // If we ever add any of the above cases, remember that:
649     //  - function-try-blocks will always blacklist this optimization
650     //  - we need to perform the constructor prologue and cleanup in
651     //    EmitConstructorBody.
652 
653     return false;
654   }
655 
656   // We also disable the optimization for variadic functions because
657   // it's impossible to "re-pass" varargs.
658   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
659     return false;
660 
661   // FIXME: Decide if we can do a delegation of a delegating constructor.
662   if (Ctor->isDelegatingConstructor())
663     return false;
664 
665   return true;
666 }
667 
668 /// EmitConstructorBody - Emits the body of the current constructor.
669 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
670   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
671   CXXCtorType CtorType = CurGD.getCtorType();
672 
673   // Before we go any further, try the complete->base constructor
674   // delegation optimization.
675   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
676     if (CGDebugInfo *DI = getDebugInfo())
677       DI->EmitStopPoint(Builder);
678     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
679     return;
680   }
681 
682   Stmt *Body = Ctor->getBody();
683 
684   // Enter the function-try-block before the constructor prologue if
685   // applicable.
686   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
687   if (IsTryBody)
688     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
689 
690   EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
691 
692   // Emit the constructor prologue, i.e. the base and member
693   // initializers.
694   EmitCtorPrologue(Ctor, CtorType, Args);
695 
696   // Emit the body of the statement.
697   if (IsTryBody)
698     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
699   else if (Body)
700     EmitStmt(Body);
701 
702   // Emit any cleanup blocks associated with the member or base
703   // initializers, which includes (along the exceptional path) the
704   // destructors for those members and bases that were fully
705   // constructed.
706   PopCleanupBlocks(CleanupDepth);
707 
708   if (IsTryBody)
709     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
710 }
711 
712 /// EmitCtorPrologue - This routine generates necessary code to initialize
713 /// base classes and non-static data members belonging to this constructor.
714 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
715                                        CXXCtorType CtorType,
716                                        FunctionArgList &Args) {
717   if (CD->isDelegatingConstructor())
718     return EmitDelegatingCXXConstructorCall(CD, Args);
719 
720   const CXXRecordDecl *ClassDecl = CD->getParent();
721 
722   llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
723 
724   for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
725        E = CD->init_end();
726        B != E; ++B) {
727     CXXCtorInitializer *Member = (*B);
728 
729     if (Member->isBaseInitializer())
730       EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
731     else if (Member->isAnyMemberInitializer())
732       MemberInitializers.push_back(Member);
733     else
734       llvm_unreachable("Delegating initializer on non-delegating constructor");
735   }
736 
737   InitializeVTablePointers(ClassDecl);
738 
739   for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
740     EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
741 }
742 
743 /// EmitDestructorBody - Emits the body of the current destructor.
744 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
745   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
746   CXXDtorType DtorType = CurGD.getDtorType();
747 
748   // The call to operator delete in a deleting destructor happens
749   // outside of the function-try-block, which means it's always
750   // possible to delegate the destructor body to the complete
751   // destructor.  Do so.
752   if (DtorType == Dtor_Deleting) {
753     EnterDtorCleanups(Dtor, Dtor_Deleting);
754     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
755                           LoadCXXThis());
756     PopCleanupBlock();
757     return;
758   }
759 
760   Stmt *Body = Dtor->getBody();
761 
762   // If the body is a function-try-block, enter the try before
763   // anything else.
764   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
765   if (isTryBody)
766     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
767 
768   // Enter the epilogue cleanups.
769   RunCleanupsScope DtorEpilogue(*this);
770 
771   // If this is the complete variant, just invoke the base variant;
772   // the epilogue will destruct the virtual bases.  But we can't do
773   // this optimization if the body is a function-try-block, because
774   // we'd introduce *two* handler blocks.
775   switch (DtorType) {
776   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
777 
778   case Dtor_Complete:
779     // Enter the cleanup scopes for virtual bases.
780     EnterDtorCleanups(Dtor, Dtor_Complete);
781 
782     if (!isTryBody) {
783       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
784                             LoadCXXThis());
785       break;
786     }
787     // Fallthrough: act like we're in the base variant.
788 
789   case Dtor_Base:
790     // Enter the cleanup scopes for fields and non-virtual bases.
791     EnterDtorCleanups(Dtor, Dtor_Base);
792 
793     // Initialize the vtable pointers before entering the body.
794     InitializeVTablePointers(Dtor->getParent());
795 
796     if (isTryBody)
797       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
798     else if (Body)
799       EmitStmt(Body);
800     else {
801       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
802       // nothing to do besides what's in the epilogue
803     }
804     // -fapple-kext must inline any call to this dtor into
805     // the caller's body.
806     if (getContext().getLangOptions().AppleKext)
807       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
808     break;
809   }
810 
811   // Jump out through the epilogue cleanups.
812   DtorEpilogue.ForceCleanup();
813 
814   // Exit the try if applicable.
815   if (isTryBody)
816     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
817 }
818 
819 namespace {
820   /// Call the operator delete associated with the current destructor.
821   struct CallDtorDelete : EHScopeStack::Cleanup {
822     CallDtorDelete() {}
823 
824     void Emit(CodeGenFunction &CGF, bool IsForEH) {
825       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
826       const CXXRecordDecl *ClassDecl = Dtor->getParent();
827       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
828                          CGF.getContext().getTagDeclType(ClassDecl));
829     }
830   };
831 
832   struct CallArrayFieldDtor : EHScopeStack::Cleanup {
833     const FieldDecl *Field;
834     CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
835 
836     void Emit(CodeGenFunction &CGF, bool IsForEH) {
837       QualType FieldType = Field->getType();
838       const ConstantArrayType *Array =
839         CGF.getContext().getAsConstantArrayType(FieldType);
840 
841       QualType BaseType =
842         CGF.getContext().getBaseElementType(Array->getElementType());
843       const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
844 
845       llvm::Value *ThisPtr = CGF.LoadCXXThis();
846       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
847                                           // FIXME: Qualifiers?
848                                           /*CVRQualifiers=*/0);
849 
850       const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
851       llvm::Value *BaseAddrPtr =
852         CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
853       CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
854                                     Array, BaseAddrPtr);
855     }
856   };
857 
858   struct CallFieldDtor : EHScopeStack::Cleanup {
859     const FieldDecl *Field;
860     CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
861 
862     void Emit(CodeGenFunction &CGF, bool IsForEH) {
863       const CXXRecordDecl *FieldClassDecl =
864         Field->getType()->getAsCXXRecordDecl();
865 
866       llvm::Value *ThisPtr = CGF.LoadCXXThis();
867       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
868                                           // FIXME: Qualifiers?
869                                           /*CVRQualifiers=*/0);
870 
871       CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
872                                 Dtor_Complete, /*ForVirtualBase=*/false,
873                                 LHS.getAddress());
874     }
875   };
876 }
877 
878 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
879 /// destructor. This is to call destructors on members and base classes
880 /// in reverse order of their construction.
881 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
882                                         CXXDtorType DtorType) {
883   assert(!DD->isTrivial() &&
884          "Should not emit dtor epilogue for trivial dtor!");
885 
886   // The deleting-destructor phase just needs to call the appropriate
887   // operator delete that Sema picked up.
888   if (DtorType == Dtor_Deleting) {
889     assert(DD->getOperatorDelete() &&
890            "operator delete missing - EmitDtorEpilogue");
891     EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
892     return;
893   }
894 
895   const CXXRecordDecl *ClassDecl = DD->getParent();
896 
897   // The complete-destructor phase just destructs all the virtual bases.
898   if (DtorType == Dtor_Complete) {
899 
900     // We push them in the forward order so that they'll be popped in
901     // the reverse order.
902     for (CXXRecordDecl::base_class_const_iterator I =
903            ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
904               I != E; ++I) {
905       const CXXBaseSpecifier &Base = *I;
906       CXXRecordDecl *BaseClassDecl
907         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
908 
909       // Ignore trivial destructors.
910       if (BaseClassDecl->hasTrivialDestructor())
911         continue;
912 
913       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
914                                         BaseClassDecl,
915                                         /*BaseIsVirtual*/ true);
916     }
917 
918     return;
919   }
920 
921   assert(DtorType == Dtor_Base);
922 
923   // Destroy non-virtual bases.
924   for (CXXRecordDecl::base_class_const_iterator I =
925         ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
926     const CXXBaseSpecifier &Base = *I;
927 
928     // Ignore virtual bases.
929     if (Base.isVirtual())
930       continue;
931 
932     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
933 
934     // Ignore trivial destructors.
935     if (BaseClassDecl->hasTrivialDestructor())
936       continue;
937 
938     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
939                                       BaseClassDecl,
940                                       /*BaseIsVirtual*/ false);
941   }
942 
943   // Destroy direct fields.
944   llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
945   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
946        E = ClassDecl->field_end(); I != E; ++I) {
947     const FieldDecl *Field = *I;
948 
949     QualType FieldType = getContext().getCanonicalType(Field->getType());
950     const ConstantArrayType *Array =
951       getContext().getAsConstantArrayType(FieldType);
952     if (Array)
953       FieldType = getContext().getBaseElementType(Array->getElementType());
954 
955     const RecordType *RT = FieldType->getAs<RecordType>();
956     if (!RT)
957       continue;
958 
959     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
960     if (FieldClassDecl->hasTrivialDestructor())
961         continue;
962 
963     if (Array)
964       EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
965     else
966       EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
967   }
968 }
969 
970 /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
971 /// for-loop to call the default constructor on individual members of the
972 /// array.
973 /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
974 /// array type and 'ArrayPtr' points to the beginning fo the array.
975 /// It is assumed that all relevant checks have been made by the caller.
976 ///
977 /// \param ZeroInitialization True if each element should be zero-initialized
978 /// before it is constructed.
979 void
980 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
981                                             const ConstantArrayType *ArrayTy,
982                                             llvm::Value *ArrayPtr,
983                                             CallExpr::const_arg_iterator ArgBeg,
984                                             CallExpr::const_arg_iterator ArgEnd,
985                                             bool ZeroInitialization) {
986 
987   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
988   llvm::Value * NumElements =
989     llvm::ConstantInt::get(SizeTy,
990                            getContext().getConstantArrayElementCount(ArrayTy));
991 
992   EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
993                              ZeroInitialization);
994 }
995 
996 void
997 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
998                                           llvm::Value *NumElements,
999                                           llvm::Value *ArrayPtr,
1000                                           CallExpr::const_arg_iterator ArgBeg,
1001                                           CallExpr::const_arg_iterator ArgEnd,
1002                                             bool ZeroInitialization) {
1003   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1004 
1005   // Create a temporary for the loop index and initialize it with 0.
1006   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1007   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1008   Builder.CreateStore(Zero, IndexPtr);
1009 
1010   // Start the loop with a block that tests the condition.
1011   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1012   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1013 
1014   EmitBlock(CondBlock);
1015 
1016   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1017 
1018   // Generate: if (loop-index < number-of-elements fall to the loop body,
1019   // otherwise, go to the block after the for-loop.
1020   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1021   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1022   // If the condition is true, execute the body.
1023   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1024 
1025   EmitBlock(ForBody);
1026 
1027   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1028   // Inside the loop body, emit the constructor call on the array element.
1029   Counter = Builder.CreateLoad(IndexPtr);
1030   llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1031                                                    "arrayidx");
1032 
1033   // Zero initialize the storage, if requested.
1034   if (ZeroInitialization)
1035     EmitNullInitialization(Address,
1036                            getContext().getTypeDeclType(D->getParent()));
1037 
1038   // C++ [class.temporary]p4:
1039   // There are two contexts in which temporaries are destroyed at a different
1040   // point than the end of the full-expression. The first context is when a
1041   // default constructor is called to initialize an element of an array.
1042   // If the constructor has one or more default arguments, the destruction of
1043   // every temporary created in a default argument expression is sequenced
1044   // before the construction of the next array element, if any.
1045 
1046   // Keep track of the current number of live temporaries.
1047   {
1048     RunCleanupsScope Scope(*this);
1049 
1050     EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
1051                            ArgBeg, ArgEnd);
1052   }
1053 
1054   EmitBlock(ContinueBlock);
1055 
1056   // Emit the increment of the loop counter.
1057   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1058   Counter = Builder.CreateLoad(IndexPtr);
1059   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1060   Builder.CreateStore(NextVal, IndexPtr);
1061 
1062   // Finally, branch back up to the condition for the next iteration.
1063   EmitBranch(CondBlock);
1064 
1065   // Emit the fall-through block.
1066   EmitBlock(AfterFor, true);
1067 }
1068 
1069 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1070 /// elements in reverse order of construction.
1071 void
1072 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1073                                            const ArrayType *Array,
1074                                            llvm::Value *This) {
1075   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1076   assert(CA && "Do we support VLA for destruction ?");
1077   uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1078 
1079   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1080   llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1081   EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1082 }
1083 
1084 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1085 /// elements in reverse order of construction.
1086 void
1087 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1088                                            llvm::Value *UpperCount,
1089                                            llvm::Value *This) {
1090   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1091   llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1092 
1093   // Create a temporary for the loop index and initialize it with count of
1094   // array elements.
1095   llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1096 
1097   // Store the number of elements in the index pointer.
1098   Builder.CreateStore(UpperCount, IndexPtr);
1099 
1100   // Start the loop with a block that tests the condition.
1101   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1102   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1103 
1104   EmitBlock(CondBlock);
1105 
1106   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1107 
1108   // Generate: if (loop-index != 0 fall to the loop body,
1109   // otherwise, go to the block after the for-loop.
1110   llvm::Value* zeroConstant =
1111     llvm::Constant::getNullValue(SizeLTy);
1112   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1113   llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1114                                             "isne");
1115   // If the condition is true, execute the body.
1116   Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1117 
1118   EmitBlock(ForBody);
1119 
1120   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1121   // Inside the loop body, emit the constructor call on the array element.
1122   Counter = Builder.CreateLoad(IndexPtr);
1123   Counter = Builder.CreateSub(Counter, One);
1124   llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1125   EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
1126 
1127   EmitBlock(ContinueBlock);
1128 
1129   // Emit the decrement of the loop counter.
1130   Counter = Builder.CreateLoad(IndexPtr);
1131   Counter = Builder.CreateSub(Counter, One, "dec");
1132   Builder.CreateStore(Counter, IndexPtr);
1133 
1134   // Finally, branch back up to the condition for the next iteration.
1135   EmitBranch(CondBlock);
1136 
1137   // Emit the fall-through block.
1138   EmitBlock(AfterFor, true);
1139 }
1140 
1141 void
1142 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1143                                         CXXCtorType Type, bool ForVirtualBase,
1144                                         llvm::Value *This,
1145                                         CallExpr::const_arg_iterator ArgBeg,
1146                                         CallExpr::const_arg_iterator ArgEnd) {
1147 
1148   CGDebugInfo *DI = getDebugInfo();
1149   if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1150     // If debug info for this class has been emitted then this is the right time
1151     // to do so.
1152     const CXXRecordDecl *Parent = D->getParent();
1153     DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1154                               Parent->getLocation());
1155   }
1156 
1157   if (D->isTrivial()) {
1158     if (ArgBeg == ArgEnd) {
1159       // Trivial default constructor, no codegen required.
1160       assert(D->isDefaultConstructor() &&
1161              "trivial 0-arg ctor not a default ctor");
1162       return;
1163     }
1164 
1165     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1166     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1167 
1168     const Expr *E = (*ArgBeg);
1169     QualType Ty = E->getType();
1170     llvm::Value *Src = EmitLValue(E).getAddress();
1171     EmitAggregateCopy(This, Src, Ty);
1172     return;
1173   }
1174 
1175   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
1176   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1177 
1178   EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
1179 }
1180 
1181 void
1182 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1183                                         llvm::Value *This, llvm::Value *Src,
1184                                         CallExpr::const_arg_iterator ArgBeg,
1185                                         CallExpr::const_arg_iterator ArgEnd) {
1186   if (D->isTrivial()) {
1187     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1188     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1189     EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1190     return;
1191   }
1192   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1193                                                     clang::Ctor_Complete);
1194   assert(D->isInstance() &&
1195          "Trying to emit a member call expr on a static method!");
1196 
1197   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1198 
1199   CallArgList Args;
1200 
1201   // Push the this ptr.
1202   Args.add(RValue::get(This), D->getThisType(getContext()));
1203 
1204 
1205   // Push the src ptr.
1206   QualType QT = *(FPT->arg_type_begin());
1207   const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1208   Src = Builder.CreateBitCast(Src, t);
1209   Args.add(RValue::get(Src), QT);
1210 
1211   // Skip over first argument (Src).
1212   ++ArgBeg;
1213   CallExpr::const_arg_iterator Arg = ArgBeg;
1214   for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1215        E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1216     assert(Arg != ArgEnd && "Running over edge of argument list!");
1217     EmitCallArg(Args, *Arg, *I);
1218   }
1219   // Either we've emitted all the call args, or we have a call to a
1220   // variadic function.
1221   assert((Arg == ArgEnd || FPT->isVariadic()) &&
1222          "Extra arguments in non-variadic function!");
1223   // If we still have any arguments, emit them using the type of the argument.
1224   for (; Arg != ArgEnd; ++Arg) {
1225     QualType ArgType = Arg->getType();
1226     EmitCallArg(Args, *Arg, ArgType);
1227   }
1228 
1229   QualType ResultType = FPT->getResultType();
1230   EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1231                                           FPT->getExtInfo()),
1232                   Callee, ReturnValueSlot(), Args, D);
1233 }
1234 
1235 void
1236 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1237                                                 CXXCtorType CtorType,
1238                                                 const FunctionArgList &Args) {
1239   CallArgList DelegateArgs;
1240 
1241   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1242   assert(I != E && "no parameters to constructor");
1243 
1244   // this
1245   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1246   ++I;
1247 
1248   // vtt
1249   if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1250                                          /*ForVirtualBase=*/false)) {
1251     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1252     DelegateArgs.add(RValue::get(VTT), VoidPP);
1253 
1254     if (CodeGenVTables::needsVTTParameter(CurGD)) {
1255       assert(I != E && "cannot skip vtt parameter, already done with args");
1256       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1257       ++I;
1258     }
1259   }
1260 
1261   // Explicit arguments.
1262   for (; I != E; ++I) {
1263     const VarDecl *param = *I;
1264     EmitDelegateCallArg(DelegateArgs, param);
1265   }
1266 
1267   EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1268            CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1269            ReturnValueSlot(), DelegateArgs, Ctor);
1270 }
1271 
1272 void
1273 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1274                                                   const FunctionArgList &Args) {
1275   assert(Ctor->isDelegatingConstructor());
1276 
1277   llvm::Value *ThisPtr = LoadCXXThis();
1278 
1279   AggValueSlot AggSlot = AggValueSlot::forAddr(ThisPtr, false, /*Lifetime*/ true);
1280 
1281   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1282 }
1283 
1284 
1285 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1286                                             CXXDtorType Type,
1287                                             bool ForVirtualBase,
1288                                             llvm::Value *This) {
1289   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1290                                      ForVirtualBase);
1291   llvm::Value *Callee = 0;
1292   if (getContext().getLangOptions().AppleKext)
1293     Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1294                                                  DD->getParent());
1295 
1296   if (!Callee)
1297     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1298 
1299   EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
1300 }
1301 
1302 namespace {
1303   struct CallLocalDtor : EHScopeStack::Cleanup {
1304     const CXXDestructorDecl *Dtor;
1305     llvm::Value *Addr;
1306 
1307     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1308       : Dtor(D), Addr(Addr) {}
1309 
1310     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1311       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1312                                 /*ForVirtualBase=*/false, Addr);
1313     }
1314   };
1315 }
1316 
1317 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1318                                             llvm::Value *Addr) {
1319   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1320 }
1321 
1322 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1323   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1324   if (!ClassDecl) return;
1325   if (ClassDecl->hasTrivialDestructor()) return;
1326 
1327   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1328   assert(D && D->isUsed() && "destructor not marked as used!");
1329   PushDestructorCleanup(D, Addr);
1330 }
1331 
1332 llvm::Value *
1333 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1334                                            const CXXRecordDecl *ClassDecl,
1335                                            const CXXRecordDecl *BaseClassDecl) {
1336   llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
1337   CharUnits VBaseOffsetOffset =
1338     CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
1339 
1340   llvm::Value *VBaseOffsetPtr =
1341     Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1342                                "vbase.offset.ptr");
1343   const llvm::Type *PtrDiffTy =
1344     ConvertType(getContext().getPointerDiffType());
1345 
1346   VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1347                                          PtrDiffTy->getPointerTo());
1348 
1349   llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1350 
1351   return VBaseOffset;
1352 }
1353 
1354 void
1355 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1356                                          const CXXRecordDecl *NearestVBase,
1357                                          CharUnits OffsetFromNearestVBase,
1358                                          llvm::Constant *VTable,
1359                                          const CXXRecordDecl *VTableClass) {
1360   const CXXRecordDecl *RD = Base.getBase();
1361 
1362   // Compute the address point.
1363   llvm::Value *VTableAddressPoint;
1364 
1365   // Check if we need to use a vtable from the VTT.
1366   if (CodeGenVTables::needsVTTParameter(CurGD) &&
1367       (RD->getNumVBases() || NearestVBase)) {
1368     // Get the secondary vpointer index.
1369     uint64_t VirtualPointerIndex =
1370      CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1371 
1372     /// Load the VTT.
1373     llvm::Value *VTT = LoadCXXVTT();
1374     if (VirtualPointerIndex)
1375       VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1376 
1377     // And load the address point from the VTT.
1378     VTableAddressPoint = Builder.CreateLoad(VTT);
1379   } else {
1380     uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
1381     VTableAddressPoint =
1382       Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1383   }
1384 
1385   // Compute where to store the address point.
1386   llvm::Value *VirtualOffset = 0;
1387   CharUnits NonVirtualOffset = CharUnits::Zero();
1388 
1389   if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1390     // We need to use the virtual base offset offset because the virtual base
1391     // might have a different offset in the most derived class.
1392     VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1393                                               NearestVBase);
1394     NonVirtualOffset = OffsetFromNearestVBase;
1395   } else {
1396     // We can just use the base offset in the complete class.
1397     NonVirtualOffset = Base.getBaseOffset();
1398   }
1399 
1400   // Apply the offsets.
1401   llvm::Value *VTableField = LoadCXXThis();
1402 
1403   if (!NonVirtualOffset.isZero() || VirtualOffset)
1404     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1405                                                   NonVirtualOffset,
1406                                                   VirtualOffset);
1407 
1408   // Finally, store the address point.
1409   const llvm::Type *AddressPointPtrTy =
1410     VTableAddressPoint->getType()->getPointerTo();
1411   VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1412   Builder.CreateStore(VTableAddressPoint, VTableField);
1413 }
1414 
1415 void
1416 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
1417                                           const CXXRecordDecl *NearestVBase,
1418                                           CharUnits OffsetFromNearestVBase,
1419                                           bool BaseIsNonVirtualPrimaryBase,
1420                                           llvm::Constant *VTable,
1421                                           const CXXRecordDecl *VTableClass,
1422                                           VisitedVirtualBasesSetTy& VBases) {
1423   // If this base is a non-virtual primary base the address point has already
1424   // been set.
1425   if (!BaseIsNonVirtualPrimaryBase) {
1426     // Initialize the vtable pointer for this base.
1427     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1428                             VTable, VTableClass);
1429   }
1430 
1431   const CXXRecordDecl *RD = Base.getBase();
1432 
1433   // Traverse bases.
1434   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1435        E = RD->bases_end(); I != E; ++I) {
1436     CXXRecordDecl *BaseDecl
1437       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1438 
1439     // Ignore classes without a vtable.
1440     if (!BaseDecl->isDynamicClass())
1441       continue;
1442 
1443     CharUnits BaseOffset;
1444     CharUnits BaseOffsetFromNearestVBase;
1445     bool BaseDeclIsNonVirtualPrimaryBase;
1446 
1447     if (I->isVirtual()) {
1448       // Check if we've visited this virtual base before.
1449       if (!VBases.insert(BaseDecl))
1450         continue;
1451 
1452       const ASTRecordLayout &Layout =
1453         getContext().getASTRecordLayout(VTableClass);
1454 
1455       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1456       BaseOffsetFromNearestVBase = CharUnits::Zero();
1457       BaseDeclIsNonVirtualPrimaryBase = false;
1458     } else {
1459       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1460 
1461       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
1462       BaseOffsetFromNearestVBase =
1463         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
1464       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
1465     }
1466 
1467     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
1468                              I->isVirtual() ? BaseDecl : NearestVBase,
1469                              BaseOffsetFromNearestVBase,
1470                              BaseDeclIsNonVirtualPrimaryBase,
1471                              VTable, VTableClass, VBases);
1472   }
1473 }
1474 
1475 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1476   // Ignore classes without a vtable.
1477   if (!RD->isDynamicClass())
1478     return;
1479 
1480   // Get the VTable.
1481   llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
1482 
1483   // Initialize the vtable pointers for this class and all of its bases.
1484   VisitedVirtualBasesSetTy VBases;
1485   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1486                            /*NearestVBase=*/0,
1487                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
1488                            /*BaseIsNonVirtualPrimaryBase=*/false,
1489                            VTable, RD, VBases);
1490 }
1491 
1492 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1493                                            const llvm::Type *Ty) {
1494   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1495   return Builder.CreateLoad(VTablePtrSrc, "vtable");
1496 }
1497