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