]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGClass.cpp
Merge from HEAD@222977.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGClass.cpp
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   assert(MemberInit->getInit() && "Must have initializer!");
524   
525   // non-static data member initializers.
526   FieldDecl *Field = MemberInit->getAnyMember();
527   QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
528
529   llvm::Value *ThisPtr = CGF.LoadCXXThis();
530   LValue LHS;
531   
532   // If we are initializing an anonymous union field, drill down to the field.
533   if (MemberInit->isIndirectMemberInitializer()) {
534     LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
535                                            MemberInit->getIndirectMember(), 0);
536     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
537   } else {
538     LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
539   }
540
541   // FIXME: If there's no initializer and the CXXCtorInitializer
542   // was implicitly generated, we shouldn't be zeroing memory.
543   RValue RHS;
544   if (FieldType->isReferenceType()) {
545     RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
546     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
547   } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
548     CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
549   } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
550     RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
551     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
552   } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
553     CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
554                                 LHS.isVolatileQualified());
555   } else {
556     llvm::Value *ArrayIndexVar = 0;
557     const ConstantArrayType *Array
558       = CGF.getContext().getAsConstantArrayType(FieldType);
559     if (Array && Constructor->isImplicit() && 
560         Constructor->isCopyConstructor()) {
561       const llvm::Type *SizeTy
562         = CGF.ConvertType(CGF.getContext().getSizeType());
563       
564       // The LHS is a pointer to the first object we'll be constructing, as
565       // a flat array.
566       QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
567       const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
568       BasePtr = llvm::PointerType::getUnqual(BasePtr);
569       llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(), 
570                                                            BasePtr);
571       LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
572       
573       // Create an array index that will be used to walk over all of the
574       // objects we're constructing.
575       ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
576       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
577       CGF.Builder.CreateStore(Zero, ArrayIndexVar);
578       
579       // If we are copying an array of scalars or classes with trivial copy 
580       // constructors, perform a single aggregate copy.
581       const RecordType *Record = BaseElementTy->getAs<RecordType>();
582       if (!Record || 
583           cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
584         // Find the source pointer. We knows it's the last argument because
585         // we know we're in a copy constructor.
586         unsigned SrcArgIndex = Args.size() - 1;
587         llvm::Value *SrcPtr
588           = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
589         LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
590         
591         // Copy the aggregate.
592         CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
593                               LHS.isVolatileQualified());
594         return;
595       }
596       
597       // Emit the block variables for the array indices, if any.
598       for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
599         CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
600     }
601     
602     EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
603     
604     if (!CGF.CGM.getLangOptions().Exceptions)
605       return;
606
607     // FIXME: If we have an array of classes w/ non-trivial destructors, 
608     // we need to destroy in reverse order of construction along the exception
609     // path.
610     const RecordType *RT = FieldType->getAs<RecordType>();
611     if (!RT)
612       return;
613     
614     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
615     if (!RD->hasTrivialDestructor())
616       CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
617                                               RD->getDestructor());
618   }
619 }
620
621 /// Checks whether the given constructor is a valid subject for the
622 /// complete-to-base constructor delegation optimization, i.e.
623 /// emitting the complete constructor as a simple call to the base
624 /// constructor.
625 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
626
627   // Currently we disable the optimization for classes with virtual
628   // bases because (1) the addresses of parameter variables need to be
629   // consistent across all initializers but (2) the delegate function
630   // call necessarily creates a second copy of the parameter variable.
631   //
632   // The limiting example (purely theoretical AFAIK):
633   //   struct A { A(int &c) { c++; } };
634   //   struct B : virtual A {
635   //     B(int count) : A(count) { printf("%d\n", count); }
636   //   };
637   // ...although even this example could in principle be emitted as a
638   // delegation since the address of the parameter doesn't escape.
639   if (Ctor->getParent()->getNumVBases()) {
640     // TODO: white-list trivial vbase initializers.  This case wouldn't
641     // be subject to the restrictions below.
642
643     // TODO: white-list cases where:
644     //  - there are no non-reference parameters to the constructor
645     //  - the initializers don't access any non-reference parameters
646     //  - the initializers don't take the address of non-reference
647     //    parameters
648     //  - etc.
649     // If we ever add any of the above cases, remember that:
650     //  - function-try-blocks will always blacklist this optimization
651     //  - we need to perform the constructor prologue and cleanup in
652     //    EmitConstructorBody.
653
654     return false;
655   }
656
657   // We also disable the optimization for variadic functions because
658   // it's impossible to "re-pass" varargs.
659   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
660     return false;
661
662   // FIXME: Decide if we can do a delegation of a delegating constructor.
663   if (Ctor->isDelegatingConstructor())
664     return false;
665
666   return true;
667 }
668
669 /// EmitConstructorBody - Emits the body of the current constructor.
670 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
671   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
672   CXXCtorType CtorType = CurGD.getCtorType();
673
674   // Before we go any further, try the complete->base constructor
675   // delegation optimization.
676   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
677     if (CGDebugInfo *DI = getDebugInfo()) 
678       DI->EmitStopPoint(Builder);
679     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
680     return;
681   }
682
683   Stmt *Body = Ctor->getBody();
684
685   // Enter the function-try-block before the constructor prologue if
686   // applicable.
687   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
688   if (IsTryBody)
689     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
690
691   EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
692
693   // Emit the constructor prologue, i.e. the base and member
694   // initializers.
695   EmitCtorPrologue(Ctor, CtorType, Args);
696
697   // Emit the body of the statement.
698   if (IsTryBody)
699     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
700   else if (Body)
701     EmitStmt(Body);
702
703   // Emit any cleanup blocks associated with the member or base
704   // initializers, which includes (along the exceptional path) the
705   // destructors for those members and bases that were fully
706   // constructed.
707   PopCleanupBlocks(CleanupDepth);
708
709   if (IsTryBody)
710     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
711 }
712
713 /// EmitCtorPrologue - This routine generates necessary code to initialize
714 /// base classes and non-static data members belonging to this constructor.
715 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
716                                        CXXCtorType CtorType,
717                                        FunctionArgList &Args) {
718   if (CD->isDelegatingConstructor())
719     return EmitDelegatingCXXConstructorCall(CD, Args);
720
721   const CXXRecordDecl *ClassDecl = CD->getParent();
722
723   llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
724   
725   for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
726        E = CD->init_end();
727        B != E; ++B) {
728     CXXCtorInitializer *Member = (*B);
729     
730     if (Member->isBaseInitializer()) {
731       EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
732     } else {
733       assert(Member->isAnyMemberInitializer() &&
734             "Delegating initializer on non-delegating constructor");
735       MemberInitializers.push_back(Member);
736     }
737   }
738
739   InitializeVTablePointers(ClassDecl);
740
741   for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
742     EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
743 }
744
745 static bool
746 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
747
748 static bool
749 HasTrivialDestructorBody(ASTContext &Context, 
750                          const CXXRecordDecl *BaseClassDecl,
751                          const CXXRecordDecl *MostDerivedClassDecl)
752 {
753   // If the destructor is trivial we don't have to check anything else.
754   if (BaseClassDecl->hasTrivialDestructor())
755     return true;
756
757   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
758     return false;
759
760   // Check fields.
761   for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
762        E = BaseClassDecl->field_end(); I != E; ++I) {
763     const FieldDecl *Field = *I;
764     
765     if (!FieldHasTrivialDestructorBody(Context, Field))
766       return false;
767   }
768
769   // Check non-virtual bases.
770   for (CXXRecordDecl::base_class_const_iterator I = 
771        BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
772        I != E; ++I) {
773     if (I->isVirtual())
774       continue;
775
776     const CXXRecordDecl *NonVirtualBase =
777       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
778     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
779                                   MostDerivedClassDecl))
780       return false;
781   }
782
783   if (BaseClassDecl == MostDerivedClassDecl) {
784     // Check virtual bases.
785     for (CXXRecordDecl::base_class_const_iterator I = 
786          BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
787          I != E; ++I) {
788       const CXXRecordDecl *VirtualBase =
789         cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
790       if (!HasTrivialDestructorBody(Context, VirtualBase,
791                                     MostDerivedClassDecl))
792         return false;      
793     }
794   }
795
796   return true;
797 }
798
799 static bool
800 FieldHasTrivialDestructorBody(ASTContext &Context,
801                               const FieldDecl *Field)
802 {
803   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
804
805   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
806   if (!RT)
807     return true;
808   
809   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
810   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
811 }
812
813 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
814 /// any vtable pointers before calling this destructor.
815 static bool CanSkipVTablePointerInitialization(ASTContext &Context,
816                                                const CXXDestructorDecl *Dtor) {
817   if (!Dtor->hasTrivialBody())
818     return false;
819
820   // Check the fields.
821   const CXXRecordDecl *ClassDecl = Dtor->getParent();
822   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
823        E = ClassDecl->field_end(); I != E; ++I) {
824     const FieldDecl *Field = *I;
825
826     if (!FieldHasTrivialDestructorBody(Context, Field))
827       return false;
828   }
829
830   return true;
831 }
832
833 /// EmitDestructorBody - Emits the body of the current destructor.
834 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
835   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
836   CXXDtorType DtorType = CurGD.getDtorType();
837
838   // The call to operator delete in a deleting destructor happens
839   // outside of the function-try-block, which means it's always
840   // possible to delegate the destructor body to the complete
841   // destructor.  Do so.
842   if (DtorType == Dtor_Deleting) {
843     EnterDtorCleanups(Dtor, Dtor_Deleting);
844     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
845                           LoadCXXThis());
846     PopCleanupBlock();
847     return;
848   }
849
850   Stmt *Body = Dtor->getBody();
851
852   // If the body is a function-try-block, enter the try before
853   // anything else.
854   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
855   if (isTryBody)
856     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
857
858   // Enter the epilogue cleanups.
859   RunCleanupsScope DtorEpilogue(*this);
860   
861   // If this is the complete variant, just invoke the base variant;
862   // the epilogue will destruct the virtual bases.  But we can't do
863   // this optimization if the body is a function-try-block, because
864   // we'd introduce *two* handler blocks.
865   switch (DtorType) {
866   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
867
868   case Dtor_Complete:
869     // Enter the cleanup scopes for virtual bases.
870     EnterDtorCleanups(Dtor, Dtor_Complete);
871
872     if (!isTryBody) {
873       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
874                             LoadCXXThis());
875       break;
876     }
877     // Fallthrough: act like we're in the base variant.
878       
879   case Dtor_Base:
880     // Enter the cleanup scopes for fields and non-virtual bases.
881     EnterDtorCleanups(Dtor, Dtor_Base);
882
883     // Initialize the vtable pointers before entering the body.
884     if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
885         InitializeVTablePointers(Dtor->getParent());
886
887     if (isTryBody)
888       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
889     else if (Body)
890       EmitStmt(Body);
891     else {
892       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
893       // nothing to do besides what's in the epilogue
894     }
895     // -fapple-kext must inline any call to this dtor into
896     // the caller's body.
897     if (getContext().getLangOptions().AppleKext)
898       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
899     break;
900   }
901
902   // Jump out through the epilogue cleanups.
903   DtorEpilogue.ForceCleanup();
904
905   // Exit the try if applicable.
906   if (isTryBody)
907     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
908 }
909
910 namespace {
911   /// Call the operator delete associated with the current destructor.
912   struct CallDtorDelete : EHScopeStack::Cleanup {
913     CallDtorDelete() {}
914
915     void Emit(CodeGenFunction &CGF, bool IsForEH) {
916       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
917       const CXXRecordDecl *ClassDecl = Dtor->getParent();
918       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
919                          CGF.getContext().getTagDeclType(ClassDecl));
920     }
921   };
922
923   struct CallArrayFieldDtor : EHScopeStack::Cleanup {
924     const FieldDecl *Field;
925     CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
926
927     void Emit(CodeGenFunction &CGF, bool IsForEH) {
928       QualType FieldType = Field->getType();
929       const ConstantArrayType *Array =
930         CGF.getContext().getAsConstantArrayType(FieldType);
931       
932       QualType BaseType =
933         CGF.getContext().getBaseElementType(Array->getElementType());
934       const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
935
936       llvm::Value *ThisPtr = CGF.LoadCXXThis();
937       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 
938                                           // FIXME: Qualifiers?
939                                           /*CVRQualifiers=*/0);
940
941       const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
942       llvm::Value *BaseAddrPtr =
943         CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
944       CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
945                                     Array, BaseAddrPtr);
946     }
947   };
948
949   struct CallFieldDtor : EHScopeStack::Cleanup {
950     const FieldDecl *Field;
951     CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
952
953     void Emit(CodeGenFunction &CGF, bool IsForEH) {
954       const CXXRecordDecl *FieldClassDecl =
955         Field->getType()->getAsCXXRecordDecl();
956
957       llvm::Value *ThisPtr = CGF.LoadCXXThis();
958       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 
959                                           // FIXME: Qualifiers?
960                                           /*CVRQualifiers=*/0);
961
962       CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
963                                 Dtor_Complete, /*ForVirtualBase=*/false,
964                                 LHS.getAddress());
965     }
966   };
967 }
968
969 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
970 /// destructor. This is to call destructors on members and base classes
971 /// in reverse order of their construction.
972 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
973                                         CXXDtorType DtorType) {
974   assert(!DD->isTrivial() &&
975          "Should not emit dtor epilogue for trivial dtor!");
976
977   // The deleting-destructor phase just needs to call the appropriate
978   // operator delete that Sema picked up.
979   if (DtorType == Dtor_Deleting) {
980     assert(DD->getOperatorDelete() && 
981            "operator delete missing - EmitDtorEpilogue");
982     EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
983     return;
984   }
985
986   const CXXRecordDecl *ClassDecl = DD->getParent();
987
988   // The complete-destructor phase just destructs all the virtual bases.
989   if (DtorType == Dtor_Complete) {
990
991     // We push them in the forward order so that they'll be popped in
992     // the reverse order.
993     for (CXXRecordDecl::base_class_const_iterator I = 
994            ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
995               I != E; ++I) {
996       const CXXBaseSpecifier &Base = *I;
997       CXXRecordDecl *BaseClassDecl
998         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
999     
1000       // Ignore trivial destructors.
1001       if (BaseClassDecl->hasTrivialDestructor())
1002         continue;
1003
1004       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1005                                         BaseClassDecl,
1006                                         /*BaseIsVirtual*/ true);
1007     }
1008
1009     return;
1010   }
1011
1012   assert(DtorType == Dtor_Base);
1013   
1014   // Destroy non-virtual bases.
1015   for (CXXRecordDecl::base_class_const_iterator I = 
1016         ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1017     const CXXBaseSpecifier &Base = *I;
1018     
1019     // Ignore virtual bases.
1020     if (Base.isVirtual())
1021       continue;
1022     
1023     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1024     
1025     // Ignore trivial destructors.
1026     if (BaseClassDecl->hasTrivialDestructor())
1027       continue;
1028
1029     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1030                                       BaseClassDecl,
1031                                       /*BaseIsVirtual*/ false);
1032   }
1033
1034   // Destroy direct fields.
1035   llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1036   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1037        E = ClassDecl->field_end(); I != E; ++I) {
1038     const FieldDecl *Field = *I;
1039     
1040     QualType FieldType = getContext().getCanonicalType(Field->getType());
1041     const ConstantArrayType *Array = 
1042       getContext().getAsConstantArrayType(FieldType);
1043     if (Array)
1044       FieldType = getContext().getBaseElementType(Array->getElementType());
1045     
1046     const RecordType *RT = FieldType->getAs<RecordType>();
1047     if (!RT)
1048       continue;
1049     
1050     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1051     if (FieldClassDecl->hasTrivialDestructor())
1052         continue;
1053
1054     if (Array)
1055       EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
1056     else
1057       EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
1058   }
1059 }
1060
1061 /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1062 /// for-loop to call the default constructor on individual members of the
1063 /// array. 
1064 /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1065 /// array type and 'ArrayPtr' points to the beginning fo the array.
1066 /// It is assumed that all relevant checks have been made by the caller.
1067 ///
1068 /// \param ZeroInitialization True if each element should be zero-initialized
1069 /// before it is constructed.
1070 void
1071 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1072                                             const ConstantArrayType *ArrayTy,
1073                                             llvm::Value *ArrayPtr,
1074                                             CallExpr::const_arg_iterator ArgBeg,
1075                                             CallExpr::const_arg_iterator ArgEnd,
1076                                             bool ZeroInitialization) {
1077
1078   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1079   llvm::Value * NumElements =
1080     llvm::ConstantInt::get(SizeTy, 
1081                            getContext().getConstantArrayElementCount(ArrayTy));
1082
1083   EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
1084                              ZeroInitialization);
1085 }
1086
1087 void
1088 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1089                                           llvm::Value *NumElements,
1090                                           llvm::Value *ArrayPtr,
1091                                           CallExpr::const_arg_iterator ArgBeg,
1092                                           CallExpr::const_arg_iterator ArgEnd,
1093                                             bool ZeroInitialization) {
1094   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1095
1096   // Create a temporary for the loop index and initialize it with 0.
1097   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1098   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1099   Builder.CreateStore(Zero, IndexPtr);
1100
1101   // Start the loop with a block that tests the condition.
1102   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1103   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1104
1105   EmitBlock(CondBlock);
1106
1107   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1108
1109   // Generate: if (loop-index < number-of-elements fall to the loop body,
1110   // otherwise, go to the block after the for-loop.
1111   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1112   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1113   // If the condition is true, execute the body.
1114   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1115
1116   EmitBlock(ForBody);
1117
1118   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1119   // Inside the loop body, emit the constructor call on the array element.
1120   Counter = Builder.CreateLoad(IndexPtr);
1121   llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter, 
1122                                                    "arrayidx");
1123
1124   // Zero initialize the storage, if requested.
1125   if (ZeroInitialization)
1126     EmitNullInitialization(Address, 
1127                            getContext().getTypeDeclType(D->getParent()));
1128   
1129   // C++ [class.temporary]p4: 
1130   // There are two contexts in which temporaries are destroyed at a different
1131   // point than the end of the full-expression. The first context is when a
1132   // default constructor is called to initialize an element of an array. 
1133   // If the constructor has one or more default arguments, the destruction of 
1134   // every temporary created in a default argument expression is sequenced 
1135   // before the construction of the next array element, if any.
1136   
1137   // Keep track of the current number of live temporaries.
1138   {
1139     RunCleanupsScope Scope(*this);
1140
1141     EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
1142                            ArgBeg, ArgEnd);
1143   }
1144
1145   EmitBlock(ContinueBlock);
1146
1147   // Emit the increment of the loop counter.
1148   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1149   Counter = Builder.CreateLoad(IndexPtr);
1150   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1151   Builder.CreateStore(NextVal, IndexPtr);
1152
1153   // Finally, branch back up to the condition for the next iteration.
1154   EmitBranch(CondBlock);
1155
1156   // Emit the fall-through block.
1157   EmitBlock(AfterFor, true);
1158 }
1159
1160 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1161 /// elements in reverse order of construction.
1162 void
1163 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1164                                            const ArrayType *Array,
1165                                            llvm::Value *This) {
1166   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1167   assert(CA && "Do we support VLA for destruction ?");
1168   uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1169   
1170   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1171   llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1172   EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1173 }
1174
1175 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1176 /// elements in reverse order of construction.
1177 void
1178 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1179                                            llvm::Value *UpperCount,
1180                                            llvm::Value *This) {
1181   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1182   llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1183   
1184   // Create a temporary for the loop index and initialize it with count of
1185   // array elements.
1186   llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1187
1188   // Store the number of elements in the index pointer.
1189   Builder.CreateStore(UpperCount, IndexPtr);
1190
1191   // Start the loop with a block that tests the condition.
1192   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1193   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1194
1195   EmitBlock(CondBlock);
1196
1197   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1198
1199   // Generate: if (loop-index != 0 fall to the loop body,
1200   // otherwise, go to the block after the for-loop.
1201   llvm::Value* zeroConstant =
1202     llvm::Constant::getNullValue(SizeLTy);
1203   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1204   llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1205                                             "isne");
1206   // If the condition is true, execute the body.
1207   Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1208
1209   EmitBlock(ForBody);
1210
1211   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1212   // Inside the loop body, emit the constructor call on the array element.
1213   Counter = Builder.CreateLoad(IndexPtr);
1214   Counter = Builder.CreateSub(Counter, One);
1215   llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1216   EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
1217
1218   EmitBlock(ContinueBlock);
1219
1220   // Emit the decrement of the loop counter.
1221   Counter = Builder.CreateLoad(IndexPtr);
1222   Counter = Builder.CreateSub(Counter, One, "dec");
1223   Builder.CreateStore(Counter, IndexPtr);
1224
1225   // Finally, branch back up to the condition for the next iteration.
1226   EmitBranch(CondBlock);
1227
1228   // Emit the fall-through block.
1229   EmitBlock(AfterFor, true);
1230 }
1231
1232 void
1233 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1234                                         CXXCtorType Type, bool ForVirtualBase,
1235                                         llvm::Value *This,
1236                                         CallExpr::const_arg_iterator ArgBeg,
1237                                         CallExpr::const_arg_iterator ArgEnd) {
1238
1239   CGDebugInfo *DI = getDebugInfo();
1240   if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1241     // If debug info for this class has been emitted then this is the right time
1242     // to do so.
1243     const CXXRecordDecl *Parent = D->getParent();
1244     DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1245                               Parent->getLocation());
1246   }
1247
1248   if (D->isTrivial()) {
1249     if (ArgBeg == ArgEnd) {
1250       // Trivial default constructor, no codegen required.
1251       assert(D->isDefaultConstructor() &&
1252              "trivial 0-arg ctor not a default ctor");
1253       return;
1254     }
1255
1256     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1257     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1258
1259     const Expr *E = (*ArgBeg);
1260     QualType Ty = E->getType();
1261     llvm::Value *Src = EmitLValue(E).getAddress();
1262     EmitAggregateCopy(This, Src, Ty);
1263     return;
1264   }
1265
1266   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
1267   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1268
1269   EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
1270 }
1271
1272 void
1273 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1274                                         llvm::Value *This, llvm::Value *Src,
1275                                         CallExpr::const_arg_iterator ArgBeg,
1276                                         CallExpr::const_arg_iterator ArgEnd) {
1277   if (D->isTrivial()) {
1278     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1279     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1280     EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1281     return;
1282   }
1283   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, 
1284                                                     clang::Ctor_Complete);
1285   assert(D->isInstance() &&
1286          "Trying to emit a member call expr on a static method!");
1287   
1288   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1289   
1290   CallArgList Args;
1291   
1292   // Push the this ptr.
1293   Args.add(RValue::get(This), D->getThisType(getContext()));
1294   
1295   
1296   // Push the src ptr.
1297   QualType QT = *(FPT->arg_type_begin());
1298   const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1299   Src = Builder.CreateBitCast(Src, t);
1300   Args.add(RValue::get(Src), QT);
1301   
1302   // Skip over first argument (Src).
1303   ++ArgBeg;
1304   CallExpr::const_arg_iterator Arg = ArgBeg;
1305   for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1306        E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1307     assert(Arg != ArgEnd && "Running over edge of argument list!");
1308     EmitCallArg(Args, *Arg, *I);
1309   }
1310   // Either we've emitted all the call args, or we have a call to a
1311   // variadic function.
1312   assert((Arg == ArgEnd || FPT->isVariadic()) &&
1313          "Extra arguments in non-variadic function!");
1314   // If we still have any arguments, emit them using the type of the argument.
1315   for (; Arg != ArgEnd; ++Arg) {
1316     QualType ArgType = Arg->getType();
1317     EmitCallArg(Args, *Arg, ArgType);
1318   }
1319   
1320   QualType ResultType = FPT->getResultType();
1321   EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1322                                           FPT->getExtInfo()),
1323                   Callee, ReturnValueSlot(), Args, D);
1324 }
1325
1326 void
1327 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1328                                                 CXXCtorType CtorType,
1329                                                 const FunctionArgList &Args) {
1330   CallArgList DelegateArgs;
1331
1332   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1333   assert(I != E && "no parameters to constructor");
1334
1335   // this
1336   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1337   ++I;
1338
1339   // vtt
1340   if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1341                                          /*ForVirtualBase=*/false)) {
1342     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1343     DelegateArgs.add(RValue::get(VTT), VoidPP);
1344
1345     if (CodeGenVTables::needsVTTParameter(CurGD)) {
1346       assert(I != E && "cannot skip vtt parameter, already done with args");
1347       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1348       ++I;
1349     }
1350   }
1351
1352   // Explicit arguments.
1353   for (; I != E; ++I) {
1354     const VarDecl *param = *I;
1355     EmitDelegateCallArg(DelegateArgs, param);
1356   }
1357
1358   EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1359            CGM.GetAddrOfCXXConstructor(Ctor, CtorType), 
1360            ReturnValueSlot(), DelegateArgs, Ctor);
1361 }
1362
1363 namespace {
1364   struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1365     const CXXDestructorDecl *Dtor;
1366     llvm::Value *Addr;
1367     CXXDtorType Type;
1368
1369     CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1370                            CXXDtorType Type)
1371       : Dtor(D), Addr(Addr), Type(Type) {}
1372
1373     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1374       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1375                                 Addr);
1376     }
1377   };
1378 }
1379
1380 void
1381 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1382                                                   const FunctionArgList &Args) {
1383   assert(Ctor->isDelegatingConstructor());
1384
1385   llvm::Value *ThisPtr = LoadCXXThis();
1386
1387   AggValueSlot AggSlot = AggValueSlot::forAddr(ThisPtr, false, /*Lifetime*/ true);
1388
1389   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1390
1391   const CXXRecordDecl *ClassDecl = Ctor->getParent();
1392   if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1393     CXXDtorType Type =
1394       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1395
1396     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1397                                                 ClassDecl->getDestructor(),
1398                                                 ThisPtr, Type);
1399   }
1400 }
1401
1402 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1403                                             CXXDtorType Type,
1404                                             bool ForVirtualBase,
1405                                             llvm::Value *This) {
1406   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type), 
1407                                      ForVirtualBase);
1408   llvm::Value *Callee = 0;
1409   if (getContext().getLangOptions().AppleKext)
1410     Callee = BuildAppleKextVirtualDestructorCall(DD, Type, 
1411                                                  DD->getParent());
1412     
1413   if (!Callee)
1414     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1415   
1416   EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
1417 }
1418
1419 namespace {
1420   struct CallLocalDtor : EHScopeStack::Cleanup {
1421     const CXXDestructorDecl *Dtor;
1422     llvm::Value *Addr;
1423
1424     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1425       : Dtor(D), Addr(Addr) {}
1426
1427     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1428       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1429                                 /*ForVirtualBase=*/false, Addr);
1430     }
1431   };
1432 }
1433
1434 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1435                                             llvm::Value *Addr) {
1436   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1437 }
1438
1439 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1440   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1441   if (!ClassDecl) return;
1442   if (ClassDecl->hasTrivialDestructor()) return;
1443
1444   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1445   assert(D && D->isUsed() && "destructor not marked as used!");
1446   PushDestructorCleanup(D, Addr);
1447 }
1448
1449 llvm::Value *
1450 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1451                                            const CXXRecordDecl *ClassDecl,
1452                                            const CXXRecordDecl *BaseClassDecl) {
1453   llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
1454   CharUnits VBaseOffsetOffset = 
1455     CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
1456   
1457   llvm::Value *VBaseOffsetPtr = 
1458     Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 
1459                                "vbase.offset.ptr");
1460   const llvm::Type *PtrDiffTy = 
1461     ConvertType(getContext().getPointerDiffType());
1462   
1463   VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 
1464                                          PtrDiffTy->getPointerTo());
1465                                          
1466   llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1467   
1468   return VBaseOffset;
1469 }
1470
1471 void
1472 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base, 
1473                                          const CXXRecordDecl *NearestVBase,
1474                                          CharUnits OffsetFromNearestVBase,
1475                                          llvm::Constant *VTable,
1476                                          const CXXRecordDecl *VTableClass) {
1477   const CXXRecordDecl *RD = Base.getBase();
1478
1479   // Compute the address point.
1480   llvm::Value *VTableAddressPoint;
1481
1482   // Check if we need to use a vtable from the VTT.
1483   if (CodeGenVTables::needsVTTParameter(CurGD) &&
1484       (RD->getNumVBases() || NearestVBase)) {
1485     // Get the secondary vpointer index.
1486     uint64_t VirtualPointerIndex = 
1487      CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1488     
1489     /// Load the VTT.
1490     llvm::Value *VTT = LoadCXXVTT();
1491     if (VirtualPointerIndex)
1492       VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1493
1494     // And load the address point from the VTT.
1495     VTableAddressPoint = Builder.CreateLoad(VTT);
1496   } else {
1497     uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
1498     VTableAddressPoint =
1499       Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1500   }
1501
1502   // Compute where to store the address point.
1503   llvm::Value *VirtualOffset = 0;
1504   CharUnits NonVirtualOffset = CharUnits::Zero();
1505   
1506   if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1507     // We need to use the virtual base offset offset because the virtual base
1508     // might have a different offset in the most derived class.
1509     VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass, 
1510                                               NearestVBase);
1511     NonVirtualOffset = OffsetFromNearestVBase;
1512   } else {
1513     // We can just use the base offset in the complete class.
1514     NonVirtualOffset = Base.getBaseOffset();
1515   }
1516   
1517   // Apply the offsets.
1518   llvm::Value *VTableField = LoadCXXThis();
1519   
1520   if (!NonVirtualOffset.isZero() || VirtualOffset)
1521     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField, 
1522                                                   NonVirtualOffset,
1523                                                   VirtualOffset);
1524
1525   // Finally, store the address point.
1526   const llvm::Type *AddressPointPtrTy =
1527     VTableAddressPoint->getType()->getPointerTo();
1528   VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1529   Builder.CreateStore(VTableAddressPoint, VTableField);
1530 }
1531
1532 void
1533 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base, 
1534                                           const CXXRecordDecl *NearestVBase,
1535                                           CharUnits OffsetFromNearestVBase,
1536                                           bool BaseIsNonVirtualPrimaryBase,
1537                                           llvm::Constant *VTable,
1538                                           const CXXRecordDecl *VTableClass,
1539                                           VisitedVirtualBasesSetTy& VBases) {
1540   // If this base is a non-virtual primary base the address point has already
1541   // been set.
1542   if (!BaseIsNonVirtualPrimaryBase) {
1543     // Initialize the vtable pointer for this base.
1544     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1545                             VTable, VTableClass);
1546   }
1547   
1548   const CXXRecordDecl *RD = Base.getBase();
1549
1550   // Traverse bases.
1551   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 
1552        E = RD->bases_end(); I != E; ++I) {
1553     CXXRecordDecl *BaseDecl
1554       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1555
1556     // Ignore classes without a vtable.
1557     if (!BaseDecl->isDynamicClass())
1558       continue;
1559
1560     CharUnits BaseOffset;
1561     CharUnits BaseOffsetFromNearestVBase;
1562     bool BaseDeclIsNonVirtualPrimaryBase;
1563
1564     if (I->isVirtual()) {
1565       // Check if we've visited this virtual base before.
1566       if (!VBases.insert(BaseDecl))
1567         continue;
1568
1569       const ASTRecordLayout &Layout = 
1570         getContext().getASTRecordLayout(VTableClass);
1571
1572       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1573       BaseOffsetFromNearestVBase = CharUnits::Zero();
1574       BaseDeclIsNonVirtualPrimaryBase = false;
1575     } else {
1576       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1577
1578       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
1579       BaseOffsetFromNearestVBase = 
1580         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
1581       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
1582     }
1583     
1584     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset), 
1585                              I->isVirtual() ? BaseDecl : NearestVBase,
1586                              BaseOffsetFromNearestVBase,
1587                              BaseDeclIsNonVirtualPrimaryBase, 
1588                              VTable, VTableClass, VBases);
1589   }
1590 }
1591
1592 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1593   // Ignore classes without a vtable.
1594   if (!RD->isDynamicClass())
1595     return;
1596
1597   // Get the VTable.
1598   llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
1599
1600   // Initialize the vtable pointers for this class and all of its bases.
1601   VisitedVirtualBasesSetTy VBases;
1602   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()), 
1603                            /*NearestVBase=*/0, 
1604                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
1605                            /*BaseIsNonVirtualPrimaryBase=*/false, 
1606                            VTable, RD, VBases);
1607 }
1608
1609 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1610                                            const llvm::Type *Ty) {
1611   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1612   return Builder.CreateLoad(VTablePtrSrc, "vtable");
1613 }
1614
1615 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1616   const Expr *E = Base;
1617   
1618   while (true) {
1619     E = E->IgnoreParens();
1620     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1621       if (CE->getCastKind() == CK_DerivedToBase || 
1622           CE->getCastKind() == CK_UncheckedDerivedToBase ||
1623           CE->getCastKind() == CK_NoOp) {
1624         E = CE->getSubExpr();
1625         continue;
1626       }
1627     }
1628
1629     break;
1630   }
1631
1632   QualType DerivedType = E->getType();
1633   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1634     DerivedType = PTy->getPointeeType();
1635
1636   return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1637 }
1638
1639 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1640 // quite what we want.
1641 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1642   while (true) {
1643     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1644       E = PE->getSubExpr();
1645       continue;
1646     }
1647
1648     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1649       if (CE->getCastKind() == CK_NoOp) {
1650         E = CE->getSubExpr();
1651         continue;
1652       }
1653     }
1654     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1655       if (UO->getOpcode() == UO_Extension) {
1656         E = UO->getSubExpr();
1657         continue;
1658       }
1659     }
1660     return E;
1661   }
1662 }
1663
1664 /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1665 /// function call on the given expr can be devirtualized.
1666 /// expr can be devirtualized.
1667 static bool canDevirtualizeMemberFunctionCall(const Expr *Base, 
1668                                               const CXXMethodDecl *MD) {
1669   // If the most derived class is marked final, we know that no subclass can
1670   // override this member function and so we can devirtualize it. For example:
1671   //
1672   // struct A { virtual void f(); }
1673   // struct B final : A { };
1674   //
1675   // void f(B *b) {
1676   //   b->f();
1677   // }
1678   //
1679   const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1680   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1681     return true;
1682
1683   // If the member function is marked 'final', we know that it can't be
1684   // overridden and can therefore devirtualize it.
1685   if (MD->hasAttr<FinalAttr>())
1686     return true;
1687
1688   // Similarly, if the class itself is marked 'final' it can't be overridden
1689   // and we can therefore devirtualize the member function call.
1690   if (MD->getParent()->hasAttr<FinalAttr>())
1691     return true;
1692
1693   Base = skipNoOpCastsAndParens(Base);
1694   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1695     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1696       // This is a record decl. We know the type and can devirtualize it.
1697       return VD->getType()->isRecordType();
1698     }
1699     
1700     return false;
1701   }
1702   
1703   // We can always devirtualize calls on temporary object expressions.
1704   if (isa<CXXConstructExpr>(Base))
1705     return true;
1706   
1707   // And calls on bound temporaries.
1708   if (isa<CXXBindTemporaryExpr>(Base))
1709     return true;
1710   
1711   // Check if this is a call expr that returns a record type.
1712   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1713     return CE->getCallReturnType()->isRecordType();
1714
1715   // We can't devirtualize the call.
1716   return false;
1717 }
1718
1719 static bool UseVirtualCall(ASTContext &Context,
1720                            const CXXOperatorCallExpr *CE,
1721                            const CXXMethodDecl *MD) {
1722   if (!MD->isVirtual())
1723     return false;
1724   
1725   // When building with -fapple-kext, all calls must go through the vtable since
1726   // the kernel linker can do runtime patching of vtables.
1727   if (Context.getLangOptions().AppleKext)
1728     return true;
1729
1730   return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1731 }
1732
1733 llvm::Value *
1734 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1735                                              const CXXMethodDecl *MD,
1736                                              llvm::Value *This) {
1737   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1738   const llvm::Type *Ty =
1739     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1740                                    FPT->isVariadic());
1741
1742   if (UseVirtualCall(getContext(), E, MD))
1743     return BuildVirtualCall(MD, This, Ty);
1744
1745   return CGM.GetAddrOfFunction(MD, Ty);
1746 }