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 "CGBlocks.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/EvaluatedExprVisitor.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/Frontend/CodeGenOptions.h"
22 
23 using namespace clang;
24 using namespace CodeGen;
25 
26 static CharUnits
27 ComputeNonVirtualBaseClassOffset(ASTContext &Context,
28                                  const CXXRecordDecl *DerivedClass,
29                                  CastExpr::path_const_iterator Start,
30                                  CastExpr::path_const_iterator End) {
31   CharUnits Offset = CharUnits::Zero();
32 
33   const CXXRecordDecl *RD = DerivedClass;
34 
35   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
36     const CXXBaseSpecifier *Base = *I;
37     assert(!Base->isVirtual() && "Should not see virtual bases here!");
38 
39     // Get the layout.
40     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
41 
42     const CXXRecordDecl *BaseDecl =
43       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
44 
45     // Add the offset.
46     Offset += Layout.getBaseClassOffset(BaseDecl);
47 
48     RD = BaseDecl;
49   }
50 
51   return Offset;
52 }
53 
54 llvm::Constant *
55 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
56                                    CastExpr::path_const_iterator PathBegin,
57                                    CastExpr::path_const_iterator PathEnd) {
58   assert(PathBegin != PathEnd && "Base path should not be empty!");
59 
60   CharUnits Offset =
61     ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
62                                      PathBegin, PathEnd);
63   if (Offset.isZero())
64     return 0;
65 
66   llvm::Type *PtrDiffTy =
67   Types.ConvertType(getContext().getPointerDiffType());
68 
69   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
70 }
71 
72 /// Gets the address of a direct base class within a complete object.
73 /// This should only be used for (1) non-virtual bases or (2) virtual bases
74 /// when the type is known to be complete (e.g. in complete destructors).
75 ///
76 /// The object pointed to by 'This' is assumed to be non-null.
77 llvm::Value *
78 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
79                                                    const CXXRecordDecl *Derived,
80                                                    const CXXRecordDecl *Base,
81                                                    bool BaseIsVirtual) {
82   // 'this' must be a pointer (in some address space) to Derived.
83   assert(This->getType()->isPointerTy() &&
84          cast<llvm::PointerType>(This->getType())->getElementType()
85            == ConvertType(Derived));
86 
87   // Compute the offset of the virtual base.
88   CharUnits Offset;
89   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
90   if (BaseIsVirtual)
91     Offset = Layout.getVBaseClassOffset(Base);
92   else
93     Offset = Layout.getBaseClassOffset(Base);
94 
95   // Shift and cast down to the base type.
96   // TODO: for complete types, this should be possible with a GEP.
97   llvm::Value *V = This;
98   if (Offset.isPositive()) {
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   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   ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy);
129   ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
130 
131   return ThisPtr;
132 }
133 
134 llvm::Value *
135 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
136                                        const CXXRecordDecl *Derived,
137                                        CastExpr::path_const_iterator PathBegin,
138                                        CastExpr::path_const_iterator PathEnd,
139                                        bool NullCheckValue) {
140   assert(PathBegin != PathEnd && "Base path should not be empty!");
141 
142   CastExpr::path_const_iterator Start = PathBegin;
143   const CXXRecordDecl *VBase = 0;
144 
145   // Get the virtual base.
146   if ((*Start)->isVirtual()) {
147     VBase =
148       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
149     ++Start;
150   }
151 
152   CharUnits NonVirtualOffset =
153     ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
154                                      Start, PathEnd);
155 
156   // Get the base pointer type.
157   llvm::Type *BasePtrTy =
158     ConvertType((PathEnd[-1])->getType())->getPointerTo();
159 
160   if (NonVirtualOffset.isZero() && !VBase) {
161     // Just cast back.
162     return Builder.CreateBitCast(Value, BasePtrTy);
163   }
164 
165   llvm::BasicBlock *CastNull = 0;
166   llvm::BasicBlock *CastNotNull = 0;
167   llvm::BasicBlock *CastEnd = 0;
168 
169   if (NullCheckValue) {
170     CastNull = createBasicBlock("cast.null");
171     CastNotNull = createBasicBlock("cast.notnull");
172     CastEnd = createBasicBlock("cast.end");
173 
174     llvm::Value *IsNull = Builder.CreateIsNull(Value);
175     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
176     EmitBlock(CastNotNull);
177   }
178 
179   llvm::Value *VirtualOffset = 0;
180 
181   if (VBase) {
182     if (Derived->hasAttr<FinalAttr>()) {
183       VirtualOffset = 0;
184 
185       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
186 
187       CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
188       NonVirtualOffset += VBaseOffset;
189     } else
190       VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
191   }
192 
193   // Apply the offsets.
194   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
195                                           NonVirtualOffset,
196                                           VirtualOffset);
197 
198   // Cast back.
199   Value = Builder.CreateBitCast(Value, BasePtrTy);
200 
201   if (NullCheckValue) {
202     Builder.CreateBr(CastEnd);
203     EmitBlock(CastNull);
204     Builder.CreateBr(CastEnd);
205     EmitBlock(CastEnd);
206 
207     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
208     PHI->addIncoming(Value, CastNotNull);
209     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
210                      CastNull);
211     Value = PHI;
212   }
213 
214   return Value;
215 }
216 
217 llvm::Value *
218 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
219                                           const CXXRecordDecl *Derived,
220                                         CastExpr::path_const_iterator PathBegin,
221                                           CastExpr::path_const_iterator PathEnd,
222                                           bool NullCheckValue) {
223   assert(PathBegin != PathEnd && "Base path should not be empty!");
224 
225   QualType DerivedTy =
226     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
227   llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
228 
229   llvm::Value *NonVirtualOffset =
230     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
231 
232   if (!NonVirtualOffset) {
233     // No offset, we can just cast back.
234     return Builder.CreateBitCast(Value, DerivedPtrTy);
235   }
236 
237   llvm::BasicBlock *CastNull = 0;
238   llvm::BasicBlock *CastNotNull = 0;
239   llvm::BasicBlock *CastEnd = 0;
240 
241   if (NullCheckValue) {
242     CastNull = createBasicBlock("cast.null");
243     CastNotNull = createBasicBlock("cast.notnull");
244     CastEnd = createBasicBlock("cast.end");
245 
246     llvm::Value *IsNull = Builder.CreateIsNull(Value);
247     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
248     EmitBlock(CastNotNull);
249   }
250 
251   // Apply the offset.
252   Value = Builder.CreateBitCast(Value, Int8PtrTy);
253   Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
254                             "sub.ptr");
255 
256   // Just cast.
257   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
258 
259   if (NullCheckValue) {
260     Builder.CreateBr(CastEnd);
261     EmitBlock(CastNull);
262     Builder.CreateBr(CastEnd);
263     EmitBlock(CastEnd);
264 
265     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
266     PHI->addIncoming(Value, CastNotNull);
267     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
268                      CastNull);
269     Value = PHI;
270   }
271 
272   return Value;
273 }
274 
275 /// GetVTTParameter - Return the VTT parameter that should be passed to a
276 /// base constructor/destructor with virtual bases.
277 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
278                                     bool ForVirtualBase) {
279   if (!CodeGenVTables::needsVTTParameter(GD)) {
280     // This constructor/destructor does not need a VTT parameter.
281     return 0;
282   }
283 
284   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
285   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
286 
287   llvm::Value *VTT;
288 
289   uint64_t SubVTTIndex;
290 
291   // If the record matches the base, this is the complete ctor/dtor
292   // variant calling the base variant in a class with virtual bases.
293   if (RD == Base) {
294     assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
295            "doing no-op VTT offset in base dtor/ctor?");
296     assert(!ForVirtualBase && "Can't have same class as virtual base!");
297     SubVTTIndex = 0;
298   } else {
299     const ASTRecordLayout &Layout =
300       CGF.getContext().getASTRecordLayout(RD);
301     CharUnits BaseOffset = ForVirtualBase ?
302       Layout.getVBaseClassOffset(Base) :
303       Layout.getBaseClassOffset(Base);
304 
305     SubVTTIndex =
306       CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
307     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
308   }
309 
310   if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
311     // A VTT parameter was passed to the constructor, use it.
312     VTT = CGF.LoadCXXVTT();
313     VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
314   } else {
315     // We're the complete constructor, so get the VTT by name.
316     VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
317     VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
318   }
319 
320   return VTT;
321 }
322 
323 namespace {
324   /// Call the destructor for a direct base class.
325   struct CallBaseDtor : EHScopeStack::Cleanup {
326     const CXXRecordDecl *BaseClass;
327     bool BaseIsVirtual;
328     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
329       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
330 
331     void Emit(CodeGenFunction &CGF, Flags flags) {
332       const CXXRecordDecl *DerivedClass =
333         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
334 
335       const CXXDestructorDecl *D = BaseClass->getDestructor();
336       llvm::Value *Addr =
337         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
338                                                   DerivedClass, BaseClass,
339                                                   BaseIsVirtual);
340       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
341     }
342   };
343 
344   /// A visitor which checks whether an initializer uses 'this' in a
345   /// way which requires the vtable to be properly set.
346   struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
347     typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
348 
349     bool UsesThis;
350 
351     DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
352 
353     // Black-list all explicit and implicit references to 'this'.
354     //
355     // Do we need to worry about external references to 'this' derived
356     // from arbitrary code?  If so, then anything which runs arbitrary
357     // external code might potentially access the vtable.
358     void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
359   };
360 }
361 
362 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
363   DynamicThisUseChecker Checker(C);
364   Checker.Visit(const_cast<Expr*>(Init));
365   return Checker.UsesThis;
366 }
367 
368 static void EmitBaseInitializer(CodeGenFunction &CGF,
369                                 const CXXRecordDecl *ClassDecl,
370                                 CXXCtorInitializer *BaseInit,
371                                 CXXCtorType CtorType) {
372   assert(BaseInit->isBaseInitializer() &&
373          "Must have base initializer!");
374 
375   llvm::Value *ThisPtr = CGF.LoadCXXThis();
376 
377   const Type *BaseType = BaseInit->getBaseClass();
378   CXXRecordDecl *BaseClassDecl =
379     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
380 
381   bool isBaseVirtual = BaseInit->isBaseVirtual();
382 
383   // The base constructor doesn't construct virtual bases.
384   if (CtorType == Ctor_Base && isBaseVirtual)
385     return;
386 
387   // If the initializer for the base (other than the constructor
388   // itself) accesses 'this' in any way, we need to initialize the
389   // vtables.
390   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
391     CGF.InitializeVTablePointers(ClassDecl);
392 
393   // We can pretend to be a complete class because it only matters for
394   // virtual bases, and we only do virtual bases for complete ctors.
395   llvm::Value *V =
396     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
397                                               BaseClassDecl,
398                                               isBaseVirtual);
399   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
400   AggValueSlot AggSlot =
401     AggValueSlot::forAddr(V, Alignment, Qualifiers(),
402                           AggValueSlot::IsDestructed,
403                           AggValueSlot::DoesNotNeedGCBarriers,
404                           AggValueSlot::IsNotAliased);
405 
406   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
407 
408   if (CGF.CGM.getLangOpts().Exceptions &&
409       !BaseClassDecl->hasTrivialDestructor())
410     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
411                                           isBaseVirtual);
412 }
413 
414 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
415                                      LValue LHS,
416                                      Expr *Init,
417                                      llvm::Value *ArrayIndexVar,
418                                      QualType T,
419                                      ArrayRef<VarDecl *> ArrayIndexes,
420                                      unsigned Index) {
421   if (Index == ArrayIndexes.size()) {
422     LValue LV = LHS;
423     { // Scope for Cleanups.
424       CodeGenFunction::RunCleanupsScope Cleanups(CGF);
425 
426       if (ArrayIndexVar) {
427         // If we have an array index variable, load it and use it as an offset.
428         // Then, increment the value.
429         llvm::Value *Dest = LHS.getAddress();
430         llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
431         Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
432         llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
433         Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
434         CGF.Builder.CreateStore(Next, ArrayIndexVar);
435 
436         // Update the LValue.
437         LV.setAddress(Dest);
438         CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
439         LV.setAlignment(std::min(Align, LV.getAlignment()));
440       }
441 
442       if (!CGF.hasAggregateLLVMType(T)) {
443         CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
444       } else if (T->isAnyComplexType()) {
445         CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
446                                     LV.isVolatileQualified());
447       } else {
448         AggValueSlot Slot =
449           AggValueSlot::forLValue(LV,
450                                   AggValueSlot::IsDestructed,
451                                   AggValueSlot::DoesNotNeedGCBarriers,
452                                   AggValueSlot::IsNotAliased);
453 
454         CGF.EmitAggExpr(Init, Slot);
455       }
456     }
457 
458     // Now, outside of the initializer cleanup scope, destroy the backing array
459     // for a std::initializer_list member.
460     CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
461 
462     return;
463   }
464 
465   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
466   assert(Array && "Array initialization without the array type?");
467   llvm::Value *IndexVar
468     = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
469   assert(IndexVar && "Array index variable not loaded");
470 
471   // Initialize this index variable to zero.
472   llvm::Value* Zero
473     = llvm::Constant::getNullValue(
474                               CGF.ConvertType(CGF.getContext().getSizeType()));
475   CGF.Builder.CreateStore(Zero, IndexVar);
476 
477   // Start the loop with a block that tests the condition.
478   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
479   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
480 
481   CGF.EmitBlock(CondBlock);
482 
483   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
484   // Generate: if (loop-index < number-of-elements) fall to the loop body,
485   // otherwise, go to the block after the for-loop.
486   uint64_t NumElements = Array->getSize().getZExtValue();
487   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
488   llvm::Value *NumElementsPtr =
489     llvm::ConstantInt::get(Counter->getType(), NumElements);
490   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
491                                                   "isless");
492 
493   // If the condition is true, execute the body.
494   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
495 
496   CGF.EmitBlock(ForBody);
497   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
498 
499   {
500     CodeGenFunction::RunCleanupsScope Cleanups(CGF);
501 
502     // Inside the loop body recurse to emit the inner loop or, eventually, the
503     // constructor call.
504     EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
505                              Array->getElementType(), ArrayIndexes, Index + 1);
506   }
507 
508   CGF.EmitBlock(ContinueBlock);
509 
510   // Emit the increment of the loop counter.
511   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
512   Counter = CGF.Builder.CreateLoad(IndexVar);
513   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
514   CGF.Builder.CreateStore(NextVal, IndexVar);
515 
516   // Finally, branch back up to the condition for the next iteration.
517   CGF.EmitBranch(CondBlock);
518 
519   // Emit the fall-through block.
520   CGF.EmitBlock(AfterFor, true);
521 }
522 
523 namespace {
524   struct CallMemberDtor : EHScopeStack::Cleanup {
525     llvm::Value *V;
526     CXXDestructorDecl *Dtor;
527 
528     CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
529       : V(V), Dtor(Dtor) {}
530 
531     void Emit(CodeGenFunction &CGF, Flags flags) {
532       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
533                                 V);
534     }
535   };
536 }
537 
538 static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
539                                             bool Moving) {
540   return Moving ? Record->hasTrivialMoveConstructor() :
541                   Record->hasTrivialCopyConstructor();
542 }
543 
544 static void EmitMemberInitializer(CodeGenFunction &CGF,
545                                   const CXXRecordDecl *ClassDecl,
546                                   CXXCtorInitializer *MemberInit,
547                                   const CXXConstructorDecl *Constructor,
548                                   FunctionArgList &Args) {
549   assert(MemberInit->isAnyMemberInitializer() &&
550          "Must have member initializer!");
551   assert(MemberInit->getInit() && "Must have initializer!");
552 
553   // non-static data member initializers.
554   FieldDecl *Field = MemberInit->getAnyMember();
555   QualType FieldType = Field->getType();
556 
557   llvm::Value *ThisPtr = CGF.LoadCXXThis();
558   LValue LHS;
559 
560   // If we are initializing an anonymous union field, drill down to the field.
561   if (MemberInit->isIndirectMemberInitializer()) {
562     LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
563                                            MemberInit->getIndirectMember(), 0);
564     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
565   } else {
566     LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
567   }
568 
569   // Special case: if we are in a copy or move constructor, and we are copying
570   // an array of PODs or classes with trivial copy constructors, ignore the
571   // AST and perform the copy we know is equivalent.
572   // FIXME: This is hacky at best... if we had a bit more explicit information
573   // in the AST, we could generalize it more easily.
574   const ConstantArrayType *Array
575     = CGF.getContext().getAsConstantArrayType(FieldType);
576   if (Array && Constructor->isImplicitlyDefined() &&
577       Constructor->isCopyOrMoveConstructor()) {
578     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
579     const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
580     if (BaseElementTy.isPODType(CGF.getContext()) ||
581         (Record && hasTrivialCopyOrMoveConstructor(Record,
582                        Constructor->isMoveConstructor()))) {
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 
597   ArrayRef<VarDecl *> ArrayIndexes;
598   if (MemberInit->getNumArrayIndices())
599     ArrayIndexes = MemberInit->getArrayIndexes();
600   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
601 }
602 
603 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
604                                               LValue LHS, Expr *Init,
605                                              ArrayRef<VarDecl *> ArrayIndexes) {
606   QualType FieldType = Field->getType();
607   if (!hasAggregateLLVMType(FieldType)) {
608     if (LHS.isSimple()) {
609       EmitExprAsInit(Init, Field, LHS, false);
610     } else {
611       RValue RHS = RValue::get(EmitScalarExpr(Init));
612       EmitStoreThroughLValue(RHS, LHS);
613     }
614   } else if (FieldType->isAnyComplexType()) {
615     EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
616   } else {
617     llvm::Value *ArrayIndexVar = 0;
618     if (ArrayIndexes.size()) {
619       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
620 
621       // The LHS is a pointer to the first object we'll be constructing, as
622       // a flat array.
623       QualType BaseElementTy = getContext().getBaseElementType(FieldType);
624       llvm::Type *BasePtr = ConvertType(BaseElementTy);
625       BasePtr = llvm::PointerType::getUnqual(BasePtr);
626       llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
627                                                        BasePtr);
628       LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
629 
630       // Create an array index that will be used to walk over all of the
631       // objects we're constructing.
632       ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
633       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
634       Builder.CreateStore(Zero, ArrayIndexVar);
635 
636 
637       // Emit the block variables for the array indices, if any.
638       for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
639         EmitAutoVarDecl(*ArrayIndexes[I]);
640     }
641 
642     EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
643                              ArrayIndexes, 0);
644 
645     if (!CGM.getLangOpts().Exceptions)
646       return;
647 
648     // FIXME: If we have an array of classes w/ non-trivial destructors,
649     // we need to destroy in reverse order of construction along the exception
650     // path.
651     const RecordType *RT = FieldType->getAs<RecordType>();
652     if (!RT)
653       return;
654 
655     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
656     if (!RD->hasTrivialDestructor())
657       EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
658                                           RD->getDestructor());
659   }
660 }
661 
662 /// Checks whether the given constructor is a valid subject for the
663 /// complete-to-base constructor delegation optimization, i.e.
664 /// emitting the complete constructor as a simple call to the base
665 /// constructor.
666 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
667 
668   // Currently we disable the optimization for classes with virtual
669   // bases because (1) the addresses of parameter variables need to be
670   // consistent across all initializers but (2) the delegate function
671   // call necessarily creates a second copy of the parameter variable.
672   //
673   // The limiting example (purely theoretical AFAIK):
674   //   struct A { A(int &c) { c++; } };
675   //   struct B : virtual A {
676   //     B(int count) : A(count) { printf("%d\n", count); }
677   //   };
678   // ...although even this example could in principle be emitted as a
679   // delegation since the address of the parameter doesn't escape.
680   if (Ctor->getParent()->getNumVBases()) {
681     // TODO: white-list trivial vbase initializers.  This case wouldn't
682     // be subject to the restrictions below.
683 
684     // TODO: white-list cases where:
685     //  - there are no non-reference parameters to the constructor
686     //  - the initializers don't access any non-reference parameters
687     //  - the initializers don't take the address of non-reference
688     //    parameters
689     //  - etc.
690     // If we ever add any of the above cases, remember that:
691     //  - function-try-blocks will always blacklist this optimization
692     //  - we need to perform the constructor prologue and cleanup in
693     //    EmitConstructorBody.
694 
695     return false;
696   }
697 
698   // We also disable the optimization for variadic functions because
699   // it's impossible to "re-pass" varargs.
700   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
701     return false;
702 
703   // FIXME: Decide if we can do a delegation of a delegating constructor.
704   if (Ctor->isDelegatingConstructor())
705     return false;
706 
707   return true;
708 }
709 
710 /// EmitConstructorBody - Emits the body of the current constructor.
711 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
712   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
713   CXXCtorType CtorType = CurGD.getCtorType();
714 
715   // Before we go any further, try the complete->base constructor
716   // delegation optimization.
717   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
718     if (CGDebugInfo *DI = getDebugInfo())
719       DI->EmitLocation(Builder, Ctor->getLocEnd());
720     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
721     return;
722   }
723 
724   Stmt *Body = Ctor->getBody();
725 
726   // Enter the function-try-block before the constructor prologue if
727   // applicable.
728   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
729   if (IsTryBody)
730     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
731 
732   EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
733 
734   // TODO: in restricted cases, we can emit the vbase initializers of
735   // a complete ctor and then delegate to the base ctor.
736 
737   // Emit the constructor prologue, i.e. the base and member
738   // initializers.
739   EmitCtorPrologue(Ctor, CtorType, Args);
740 
741   // Emit the body of the statement.
742   if (IsTryBody)
743     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
744   else if (Body)
745     EmitStmt(Body);
746 
747   // Emit any cleanup blocks associated with the member or base
748   // initializers, which includes (along the exceptional path) the
749   // destructors for those members and bases that were fully
750   // constructed.
751   PopCleanupBlocks(CleanupDepth);
752 
753   if (IsTryBody)
754     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
755 }
756 
757 /// EmitCtorPrologue - This routine generates necessary code to initialize
758 /// base classes and non-static data members belonging to this constructor.
759 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
760                                        CXXCtorType CtorType,
761                                        FunctionArgList &Args) {
762   if (CD->isDelegatingConstructor())
763     return EmitDelegatingCXXConstructorCall(CD, Args);
764 
765   const CXXRecordDecl *ClassDecl = CD->getParent();
766 
767   SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
768 
769   for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
770        E = CD->init_end();
771        B != E; ++B) {
772     CXXCtorInitializer *Member = (*B);
773 
774     if (Member->isBaseInitializer()) {
775       EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
776     } else {
777       assert(Member->isAnyMemberInitializer() &&
778             "Delegating initializer on non-delegating constructor");
779       MemberInitializers.push_back(Member);
780     }
781   }
782 
783   InitializeVTablePointers(ClassDecl);
784 
785   for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
786     EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
787 }
788 
789 static bool
790 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
791 
792 static bool
793 HasTrivialDestructorBody(ASTContext &Context,
794                          const CXXRecordDecl *BaseClassDecl,
795                          const CXXRecordDecl *MostDerivedClassDecl)
796 {
797   // If the destructor is trivial we don't have to check anything else.
798   if (BaseClassDecl->hasTrivialDestructor())
799     return true;
800 
801   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
802     return false;
803 
804   // Check fields.
805   for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
806        E = BaseClassDecl->field_end(); I != E; ++I) {
807     const FieldDecl *Field = *I;
808 
809     if (!FieldHasTrivialDestructorBody(Context, Field))
810       return false;
811   }
812 
813   // Check non-virtual bases.
814   for (CXXRecordDecl::base_class_const_iterator I =
815        BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
816        I != E; ++I) {
817     if (I->isVirtual())
818       continue;
819 
820     const CXXRecordDecl *NonVirtualBase =
821       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
822     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
823                                   MostDerivedClassDecl))
824       return false;
825   }
826 
827   if (BaseClassDecl == MostDerivedClassDecl) {
828     // Check virtual bases.
829     for (CXXRecordDecl::base_class_const_iterator I =
830          BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
831          I != E; ++I) {
832       const CXXRecordDecl *VirtualBase =
833         cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
834       if (!HasTrivialDestructorBody(Context, VirtualBase,
835                                     MostDerivedClassDecl))
836         return false;
837     }
838   }
839 
840   return true;
841 }
842 
843 static bool
844 FieldHasTrivialDestructorBody(ASTContext &Context,
845                               const FieldDecl *Field)
846 {
847   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
848 
849   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
850   if (!RT)
851     return true;
852 
853   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
854   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
855 }
856 
857 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
858 /// any vtable pointers before calling this destructor.
859 static bool CanSkipVTablePointerInitialization(ASTContext &Context,
860                                                const CXXDestructorDecl *Dtor) {
861   if (!Dtor->hasTrivialBody())
862     return false;
863 
864   // Check the fields.
865   const CXXRecordDecl *ClassDecl = Dtor->getParent();
866   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
867        E = ClassDecl->field_end(); I != E; ++I) {
868     const FieldDecl *Field = *I;
869 
870     if (!FieldHasTrivialDestructorBody(Context, Field))
871       return false;
872   }
873 
874   return true;
875 }
876 
877 /// EmitDestructorBody - Emits the body of the current destructor.
878 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
879   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
880   CXXDtorType DtorType = CurGD.getDtorType();
881 
882   // The call to operator delete in a deleting destructor happens
883   // outside of the function-try-block, which means it's always
884   // possible to delegate the destructor body to the complete
885   // destructor.  Do so.
886   if (DtorType == Dtor_Deleting) {
887     EnterDtorCleanups(Dtor, Dtor_Deleting);
888     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
889                           LoadCXXThis());
890     PopCleanupBlock();
891     return;
892   }
893 
894   Stmt *Body = Dtor->getBody();
895 
896   // If the body is a function-try-block, enter the try before
897   // anything else.
898   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
899   if (isTryBody)
900     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
901 
902   // Enter the epilogue cleanups.
903   RunCleanupsScope DtorEpilogue(*this);
904 
905   // If this is the complete variant, just invoke the base variant;
906   // the epilogue will destruct the virtual bases.  But we can't do
907   // this optimization if the body is a function-try-block, because
908   // we'd introduce *two* handler blocks.
909   switch (DtorType) {
910   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
911 
912   case Dtor_Complete:
913     // Enter the cleanup scopes for virtual bases.
914     EnterDtorCleanups(Dtor, Dtor_Complete);
915 
916     if (!isTryBody) {
917       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
918                             LoadCXXThis());
919       break;
920     }
921     // Fallthrough: act like we're in the base variant.
922 
923   case Dtor_Base:
924     // Enter the cleanup scopes for fields and non-virtual bases.
925     EnterDtorCleanups(Dtor, Dtor_Base);
926 
927     // Initialize the vtable pointers before entering the body.
928     if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
929         InitializeVTablePointers(Dtor->getParent());
930 
931     if (isTryBody)
932       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
933     else if (Body)
934       EmitStmt(Body);
935     else {
936       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
937       // nothing to do besides what's in the epilogue
938     }
939     // -fapple-kext must inline any call to this dtor into
940     // the caller's body.
941     if (getContext().getLangOpts().AppleKext)
942       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
943     break;
944   }
945 
946   // Jump out through the epilogue cleanups.
947   DtorEpilogue.ForceCleanup();
948 
949   // Exit the try if applicable.
950   if (isTryBody)
951     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
952 }
953 
954 namespace {
955   /// Call the operator delete associated with the current destructor.
956   struct CallDtorDelete : EHScopeStack::Cleanup {
957     CallDtorDelete() {}
958 
959     void Emit(CodeGenFunction &CGF, Flags flags) {
960       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
961       const CXXRecordDecl *ClassDecl = Dtor->getParent();
962       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
963                          CGF.getContext().getTagDeclType(ClassDecl));
964     }
965   };
966 
967   class DestroyField  : public EHScopeStack::Cleanup {
968     const FieldDecl *field;
969     CodeGenFunction::Destroyer *destroyer;
970     bool useEHCleanupForArray;
971 
972   public:
973     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
974                  bool useEHCleanupForArray)
975       : field(field), destroyer(destroyer),
976         useEHCleanupForArray(useEHCleanupForArray) {}
977 
978     void Emit(CodeGenFunction &CGF, Flags flags) {
979       // Find the address of the field.
980       llvm::Value *thisValue = CGF.LoadCXXThis();
981       LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
982       assert(LV.isSimple());
983 
984       CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
985                       flags.isForNormalCleanup() && useEHCleanupForArray);
986     }
987   };
988 }
989 
990 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
991 /// destructor. This is to call destructors on members and base classes
992 /// in reverse order of their construction.
993 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
994                                         CXXDtorType DtorType) {
995   assert(!DD->isTrivial() &&
996          "Should not emit dtor epilogue for trivial dtor!");
997 
998   // The deleting-destructor phase just needs to call the appropriate
999   // operator delete that Sema picked up.
1000   if (DtorType == Dtor_Deleting) {
1001     assert(DD->getOperatorDelete() &&
1002            "operator delete missing - EmitDtorEpilogue");
1003     EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1004     return;
1005   }
1006 
1007   const CXXRecordDecl *ClassDecl = DD->getParent();
1008 
1009   // Unions have no bases and do not call field destructors.
1010   if (ClassDecl->isUnion())
1011     return;
1012 
1013   // The complete-destructor phase just destructs all the virtual bases.
1014   if (DtorType == Dtor_Complete) {
1015 
1016     // We push them in the forward order so that they'll be popped in
1017     // the reverse order.
1018     for (CXXRecordDecl::base_class_const_iterator I =
1019            ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
1020               I != E; ++I) {
1021       const CXXBaseSpecifier &Base = *I;
1022       CXXRecordDecl *BaseClassDecl
1023         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1024 
1025       // Ignore trivial destructors.
1026       if (BaseClassDecl->hasTrivialDestructor())
1027         continue;
1028 
1029       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1030                                         BaseClassDecl,
1031                                         /*BaseIsVirtual*/ true);
1032     }
1033 
1034     return;
1035   }
1036 
1037   assert(DtorType == Dtor_Base);
1038 
1039   // Destroy non-virtual bases.
1040   for (CXXRecordDecl::base_class_const_iterator I =
1041         ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1042     const CXXBaseSpecifier &Base = *I;
1043 
1044     // Ignore virtual bases.
1045     if (Base.isVirtual())
1046       continue;
1047 
1048     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1049 
1050     // Ignore trivial destructors.
1051     if (BaseClassDecl->hasTrivialDestructor())
1052       continue;
1053 
1054     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1055                                       BaseClassDecl,
1056                                       /*BaseIsVirtual*/ false);
1057   }
1058 
1059   // Destroy direct fields.
1060   SmallVector<const FieldDecl *, 16> FieldDecls;
1061   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1062        E = ClassDecl->field_end(); I != E; ++I) {
1063     const FieldDecl *field = *I;
1064     QualType type = field->getType();
1065     QualType::DestructionKind dtorKind = type.isDestructedType();
1066     if (!dtorKind) continue;
1067 
1068     // Anonymous union members do not have their destructors called.
1069     const RecordType *RT = type->getAsUnionType();
1070     if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1071 
1072     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1073     EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1074                                       getDestroyer(dtorKind),
1075                                       cleanupKind & EHCleanup);
1076   }
1077 }
1078 
1079 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1080 /// constructor for each of several members of an array.
1081 ///
1082 /// \param ctor the constructor to call for each element
1083 /// \param argBegin,argEnd the arguments to evaluate and pass to the
1084 ///   constructor
1085 /// \param arrayType the type of the array to initialize
1086 /// \param arrayBegin an arrayType*
1087 /// \param zeroInitialize true if each element should be
1088 ///   zero-initialized before it is constructed
1089 void
1090 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1091                                             const ConstantArrayType *arrayType,
1092                                             llvm::Value *arrayBegin,
1093                                           CallExpr::const_arg_iterator argBegin,
1094                                             CallExpr::const_arg_iterator argEnd,
1095                                             bool zeroInitialize) {
1096   QualType elementType;
1097   llvm::Value *numElements =
1098     emitArrayLength(arrayType, elementType, arrayBegin);
1099 
1100   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1101                              argBegin, argEnd, zeroInitialize);
1102 }
1103 
1104 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1105 /// constructor for each of several members of an array.
1106 ///
1107 /// \param ctor the constructor to call for each element
1108 /// \param numElements the number of elements in the array;
1109 ///   may be zero
1110 /// \param argBegin,argEnd the arguments to evaluate and pass to the
1111 ///   constructor
1112 /// \param arrayBegin a T*, where T is the type constructed by ctor
1113 /// \param zeroInitialize true if each element should be
1114 ///   zero-initialized before it is constructed
1115 void
1116 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1117                                             llvm::Value *numElements,
1118                                             llvm::Value *arrayBegin,
1119                                          CallExpr::const_arg_iterator argBegin,
1120                                            CallExpr::const_arg_iterator argEnd,
1121                                             bool zeroInitialize) {
1122 
1123   // It's legal for numElements to be zero.  This can happen both
1124   // dynamically, because x can be zero in 'new A[x]', and statically,
1125   // because of GCC extensions that permit zero-length arrays.  There
1126   // are probably legitimate places where we could assume that this
1127   // doesn't happen, but it's not clear that it's worth it.
1128   llvm::BranchInst *zeroCheckBranch = 0;
1129 
1130   // Optimize for a constant count.
1131   llvm::ConstantInt *constantCount
1132     = dyn_cast<llvm::ConstantInt>(numElements);
1133   if (constantCount) {
1134     // Just skip out if the constant count is zero.
1135     if (constantCount->isZero()) return;
1136 
1137   // Otherwise, emit the check.
1138   } else {
1139     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1140     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1141     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1142     EmitBlock(loopBB);
1143   }
1144 
1145   // Find the end of the array.
1146   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1147                                                     "arrayctor.end");
1148 
1149   // Enter the loop, setting up a phi for the current location to initialize.
1150   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1151   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1152   EmitBlock(loopBB);
1153   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1154                                          "arrayctor.cur");
1155   cur->addIncoming(arrayBegin, entryBB);
1156 
1157   // Inside the loop body, emit the constructor call on the array element.
1158 
1159   QualType type = getContext().getTypeDeclType(ctor->getParent());
1160 
1161   // Zero initialize the storage, if requested.
1162   if (zeroInitialize)
1163     EmitNullInitialization(cur, type);
1164 
1165   // C++ [class.temporary]p4:
1166   // There are two contexts in which temporaries are destroyed at a different
1167   // point than the end of the full-expression. The first context is when a
1168   // default constructor is called to initialize an element of an array.
1169   // If the constructor has one or more default arguments, the destruction of
1170   // every temporary created in a default argument expression is sequenced
1171   // before the construction of the next array element, if any.
1172 
1173   {
1174     RunCleanupsScope Scope(*this);
1175 
1176     // Evaluate the constructor and its arguments in a regular
1177     // partial-destroy cleanup.
1178     if (getLangOpts().Exceptions &&
1179         !ctor->getParent()->hasTrivialDestructor()) {
1180       Destroyer *destroyer = destroyCXXObject;
1181       pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1182     }
1183 
1184     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1185                            cur, argBegin, argEnd);
1186   }
1187 
1188   // Go to the next element.
1189   llvm::Value *next =
1190     Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1191                               "arrayctor.next");
1192   cur->addIncoming(next, Builder.GetInsertBlock());
1193 
1194   // Check whether that's the end of the loop.
1195   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1196   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1197   Builder.CreateCondBr(done, contBB, loopBB);
1198 
1199   // Patch the earlier check to skip over the loop.
1200   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1201 
1202   EmitBlock(contBB);
1203 }
1204 
1205 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1206                                        llvm::Value *addr,
1207                                        QualType type) {
1208   const RecordType *rtype = type->castAs<RecordType>();
1209   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1210   const CXXDestructorDecl *dtor = record->getDestructor();
1211   assert(!dtor->isTrivial());
1212   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1213                             addr);
1214 }
1215 
1216 void
1217 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1218                                         CXXCtorType Type, bool ForVirtualBase,
1219                                         llvm::Value *This,
1220                                         CallExpr::const_arg_iterator ArgBeg,
1221                                         CallExpr::const_arg_iterator ArgEnd) {
1222 
1223   CGDebugInfo *DI = getDebugInfo();
1224   if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1225     // If debug info for this class has not been emitted then this is the
1226     // right time to do so.
1227     const CXXRecordDecl *Parent = D->getParent();
1228     DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1229                               Parent->getLocation());
1230   }
1231 
1232   if (D->isTrivial()) {
1233     if (ArgBeg == ArgEnd) {
1234       // Trivial default constructor, no codegen required.
1235       assert(D->isDefaultConstructor() &&
1236              "trivial 0-arg ctor not a default ctor");
1237       return;
1238     }
1239 
1240     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1241     assert(D->isCopyOrMoveConstructor() &&
1242            "trivial 1-arg ctor not a copy/move ctor");
1243 
1244     const Expr *E = (*ArgBeg);
1245     QualType Ty = E->getType();
1246     llvm::Value *Src = EmitLValue(E).getAddress();
1247     EmitAggregateCopy(This, Src, Ty);
1248     return;
1249   }
1250 
1251   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
1252   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1253 
1254   EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
1255 }
1256 
1257 void
1258 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1259                                         llvm::Value *This, llvm::Value *Src,
1260                                         CallExpr::const_arg_iterator ArgBeg,
1261                                         CallExpr::const_arg_iterator ArgEnd) {
1262   if (D->isTrivial()) {
1263     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1264     assert(D->isCopyOrMoveConstructor() &&
1265            "trivial 1-arg ctor not a copy/move ctor");
1266     EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1267     return;
1268   }
1269   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1270                                                     clang::Ctor_Complete);
1271   assert(D->isInstance() &&
1272          "Trying to emit a member call expr on a static method!");
1273 
1274   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1275 
1276   CallArgList Args;
1277 
1278   // Push the this ptr.
1279   Args.add(RValue::get(This), D->getThisType(getContext()));
1280 
1281 
1282   // Push the src ptr.
1283   QualType QT = *(FPT->arg_type_begin());
1284   llvm::Type *t = CGM.getTypes().ConvertType(QT);
1285   Src = Builder.CreateBitCast(Src, t);
1286   Args.add(RValue::get(Src), QT);
1287 
1288   // Skip over first argument (Src).
1289   ++ArgBeg;
1290   CallExpr::const_arg_iterator Arg = ArgBeg;
1291   for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1292        E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1293     assert(Arg != ArgEnd && "Running over edge of argument list!");
1294     EmitCallArg(Args, *Arg, *I);
1295   }
1296   // Either we've emitted all the call args, or we have a call to a
1297   // variadic function.
1298   assert((Arg == ArgEnd || FPT->isVariadic()) &&
1299          "Extra arguments in non-variadic function!");
1300   // If we still have any arguments, emit them using the type of the argument.
1301   for (; Arg != ArgEnd; ++Arg) {
1302     QualType ArgType = Arg->getType();
1303     EmitCallArg(Args, *Arg, ArgType);
1304   }
1305 
1306   EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
1307            ReturnValueSlot(), Args, D);
1308 }
1309 
1310 void
1311 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1312                                                 CXXCtorType CtorType,
1313                                                 const FunctionArgList &Args) {
1314   CallArgList DelegateArgs;
1315 
1316   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1317   assert(I != E && "no parameters to constructor");
1318 
1319   // this
1320   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1321   ++I;
1322 
1323   // vtt
1324   if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1325                                          /*ForVirtualBase=*/false)) {
1326     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1327     DelegateArgs.add(RValue::get(VTT), VoidPP);
1328 
1329     if (CodeGenVTables::needsVTTParameter(CurGD)) {
1330       assert(I != E && "cannot skip vtt parameter, already done with args");
1331       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1332       ++I;
1333     }
1334   }
1335 
1336   // Explicit arguments.
1337   for (; I != E; ++I) {
1338     const VarDecl *param = *I;
1339     EmitDelegateCallArg(DelegateArgs, param);
1340   }
1341 
1342   EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
1343            CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1344            ReturnValueSlot(), DelegateArgs, Ctor);
1345 }
1346 
1347 namespace {
1348   struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1349     const CXXDestructorDecl *Dtor;
1350     llvm::Value *Addr;
1351     CXXDtorType Type;
1352 
1353     CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1354                            CXXDtorType Type)
1355       : Dtor(D), Addr(Addr), Type(Type) {}
1356 
1357     void Emit(CodeGenFunction &CGF, Flags flags) {
1358       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1359                                 Addr);
1360     }
1361   };
1362 }
1363 
1364 void
1365 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1366                                                   const FunctionArgList &Args) {
1367   assert(Ctor->isDelegatingConstructor());
1368 
1369   llvm::Value *ThisPtr = LoadCXXThis();
1370 
1371   QualType Ty = getContext().getTagDeclType(Ctor->getParent());
1372   CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1373   AggValueSlot AggSlot =
1374     AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
1375                           AggValueSlot::IsDestructed,
1376                           AggValueSlot::DoesNotNeedGCBarriers,
1377                           AggValueSlot::IsNotAliased);
1378 
1379   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1380 
1381   const CXXRecordDecl *ClassDecl = Ctor->getParent();
1382   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1383     CXXDtorType Type =
1384       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1385 
1386     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1387                                                 ClassDecl->getDestructor(),
1388                                                 ThisPtr, Type);
1389   }
1390 }
1391 
1392 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1393                                             CXXDtorType Type,
1394                                             bool ForVirtualBase,
1395                                             llvm::Value *This) {
1396   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1397                                      ForVirtualBase);
1398   llvm::Value *Callee = 0;
1399   if (getContext().getLangOpts().AppleKext)
1400     Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1401                                                  DD->getParent());
1402 
1403   if (!Callee)
1404     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1405 
1406   EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
1407 }
1408 
1409 namespace {
1410   struct CallLocalDtor : EHScopeStack::Cleanup {
1411     const CXXDestructorDecl *Dtor;
1412     llvm::Value *Addr;
1413 
1414     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1415       : Dtor(D), Addr(Addr) {}
1416 
1417     void Emit(CodeGenFunction &CGF, Flags flags) {
1418       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1419                                 /*ForVirtualBase=*/false, Addr);
1420     }
1421   };
1422 }
1423 
1424 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1425                                             llvm::Value *Addr) {
1426   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1427 }
1428 
1429 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1430   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1431   if (!ClassDecl) return;
1432   if (ClassDecl->hasTrivialDestructor()) return;
1433 
1434   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1435   assert(D && D->isUsed() && "destructor not marked as used!");
1436   PushDestructorCleanup(D, Addr);
1437 }
1438 
1439 llvm::Value *
1440 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1441                                            const CXXRecordDecl *ClassDecl,
1442                                            const CXXRecordDecl *BaseClassDecl) {
1443   llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
1444   CharUnits VBaseOffsetOffset =
1445     CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
1446 
1447   llvm::Value *VBaseOffsetPtr =
1448     Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1449                                "vbase.offset.ptr");
1450   llvm::Type *PtrDiffTy =
1451     ConvertType(getContext().getPointerDiffType());
1452 
1453   VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1454                                          PtrDiffTy->getPointerTo());
1455 
1456   llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1457 
1458   return VBaseOffset;
1459 }
1460 
1461 void
1462 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1463                                          const CXXRecordDecl *NearestVBase,
1464                                          CharUnits OffsetFromNearestVBase,
1465                                          llvm::Constant *VTable,
1466                                          const CXXRecordDecl *VTableClass) {
1467   const CXXRecordDecl *RD = Base.getBase();
1468 
1469   // Compute the address point.
1470   llvm::Value *VTableAddressPoint;
1471 
1472   // Check if we need to use a vtable from the VTT.
1473   if (CodeGenVTables::needsVTTParameter(CurGD) &&
1474       (RD->getNumVBases() || NearestVBase)) {
1475     // Get the secondary vpointer index.
1476     uint64_t VirtualPointerIndex =
1477      CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1478 
1479     /// Load the VTT.
1480     llvm::Value *VTT = LoadCXXVTT();
1481     if (VirtualPointerIndex)
1482       VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1483 
1484     // And load the address point from the VTT.
1485     VTableAddressPoint = Builder.CreateLoad(VTT);
1486   } else {
1487     uint64_t AddressPoint =
1488       CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
1489     VTableAddressPoint =
1490       Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1491   }
1492 
1493   // Compute where to store the address point.
1494   llvm::Value *VirtualOffset = 0;
1495   CharUnits NonVirtualOffset = CharUnits::Zero();
1496 
1497   if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1498     // We need to use the virtual base offset offset because the virtual base
1499     // might have a different offset in the most derived class.
1500     VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1501                                               NearestVBase);
1502     NonVirtualOffset = OffsetFromNearestVBase;
1503   } else {
1504     // We can just use the base offset in the complete class.
1505     NonVirtualOffset = Base.getBaseOffset();
1506   }
1507 
1508   // Apply the offsets.
1509   llvm::Value *VTableField = LoadCXXThis();
1510 
1511   if (!NonVirtualOffset.isZero() || VirtualOffset)
1512     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1513                                                   NonVirtualOffset,
1514                                                   VirtualOffset);
1515 
1516   // Finally, store the address point.
1517   llvm::Type *AddressPointPtrTy =
1518     VTableAddressPoint->getType()->getPointerTo();
1519   VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1520   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1521   CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
1522 }
1523 
1524 void
1525 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
1526                                           const CXXRecordDecl *NearestVBase,
1527                                           CharUnits OffsetFromNearestVBase,
1528                                           bool BaseIsNonVirtualPrimaryBase,
1529                                           llvm::Constant *VTable,
1530                                           const CXXRecordDecl *VTableClass,
1531                                           VisitedVirtualBasesSetTy& VBases) {
1532   // If this base is a non-virtual primary base the address point has already
1533   // been set.
1534   if (!BaseIsNonVirtualPrimaryBase) {
1535     // Initialize the vtable pointer for this base.
1536     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1537                             VTable, VTableClass);
1538   }
1539 
1540   const CXXRecordDecl *RD = Base.getBase();
1541 
1542   // Traverse bases.
1543   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1544        E = RD->bases_end(); I != E; ++I) {
1545     CXXRecordDecl *BaseDecl
1546       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1547 
1548     // Ignore classes without a vtable.
1549     if (!BaseDecl->isDynamicClass())
1550       continue;
1551 
1552     CharUnits BaseOffset;
1553     CharUnits BaseOffsetFromNearestVBase;
1554     bool BaseDeclIsNonVirtualPrimaryBase;
1555 
1556     if (I->isVirtual()) {
1557       // Check if we've visited this virtual base before.
1558       if (!VBases.insert(BaseDecl))
1559         continue;
1560 
1561       const ASTRecordLayout &Layout =
1562         getContext().getASTRecordLayout(VTableClass);
1563 
1564       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1565       BaseOffsetFromNearestVBase = CharUnits::Zero();
1566       BaseDeclIsNonVirtualPrimaryBase = false;
1567     } else {
1568       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1569 
1570       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
1571       BaseOffsetFromNearestVBase =
1572         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
1573       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
1574     }
1575 
1576     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
1577                              I->isVirtual() ? BaseDecl : NearestVBase,
1578                              BaseOffsetFromNearestVBase,
1579                              BaseDeclIsNonVirtualPrimaryBase,
1580                              VTable, VTableClass, VBases);
1581   }
1582 }
1583 
1584 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1585   // Ignore classes without a vtable.
1586   if (!RD->isDynamicClass())
1587     return;
1588 
1589   // Get the VTable.
1590   llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
1591 
1592   // Initialize the vtable pointers for this class and all of its bases.
1593   VisitedVirtualBasesSetTy VBases;
1594   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1595                            /*NearestVBase=*/0,
1596                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
1597                            /*BaseIsNonVirtualPrimaryBase=*/false,
1598                            VTable, RD, VBases);
1599 }
1600 
1601 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1602                                            llvm::Type *Ty) {
1603   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1604   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1605   CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1606   return VTable;
1607 }
1608 
1609 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1610   const Expr *E = Base;
1611 
1612   while (true) {
1613     E = E->IgnoreParens();
1614     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1615       if (CE->getCastKind() == CK_DerivedToBase ||
1616           CE->getCastKind() == CK_UncheckedDerivedToBase ||
1617           CE->getCastKind() == CK_NoOp) {
1618         E = CE->getSubExpr();
1619         continue;
1620       }
1621     }
1622 
1623     break;
1624   }
1625 
1626   QualType DerivedType = E->getType();
1627   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1628     DerivedType = PTy->getPointeeType();
1629 
1630   return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1631 }
1632 
1633 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1634 // quite what we want.
1635 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1636   while (true) {
1637     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1638       E = PE->getSubExpr();
1639       continue;
1640     }
1641 
1642     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1643       if (CE->getCastKind() == CK_NoOp) {
1644         E = CE->getSubExpr();
1645         continue;
1646       }
1647     }
1648     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1649       if (UO->getOpcode() == UO_Extension) {
1650         E = UO->getSubExpr();
1651         continue;
1652       }
1653     }
1654     return E;
1655   }
1656 }
1657 
1658 /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1659 /// function call on the given expr can be devirtualized.
1660 static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1661                                               const CXXMethodDecl *MD) {
1662   // If the most derived class is marked final, we know that no subclass can
1663   // override this member function and so we can devirtualize it. For example:
1664   //
1665   // struct A { virtual void f(); }
1666   // struct B final : A { };
1667   //
1668   // void f(B *b) {
1669   //   b->f();
1670   // }
1671   //
1672   const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1673   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1674     return true;
1675 
1676   // If the member function is marked 'final', we know that it can't be
1677   // overridden and can therefore devirtualize it.
1678   if (MD->hasAttr<FinalAttr>())
1679     return true;
1680 
1681   // Similarly, if the class itself is marked 'final' it can't be overridden
1682   // and we can therefore devirtualize the member function call.
1683   if (MD->getParent()->hasAttr<FinalAttr>())
1684     return true;
1685 
1686   Base = skipNoOpCastsAndParens(Base);
1687   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1688     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1689       // This is a record decl. We know the type and can devirtualize it.
1690       return VD->getType()->isRecordType();
1691     }
1692 
1693     return false;
1694   }
1695 
1696   // We can always devirtualize calls on temporary object expressions.
1697   if (isa<CXXConstructExpr>(Base))
1698     return true;
1699 
1700   // And calls on bound temporaries.
1701   if (isa<CXXBindTemporaryExpr>(Base))
1702     return true;
1703 
1704   // Check if this is a call expr that returns a record type.
1705   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1706     return CE->getCallReturnType()->isRecordType();
1707 
1708   // We can't devirtualize the call.
1709   return false;
1710 }
1711 
1712 static bool UseVirtualCall(ASTContext &Context,
1713                            const CXXOperatorCallExpr *CE,
1714                            const CXXMethodDecl *MD) {
1715   if (!MD->isVirtual())
1716     return false;
1717 
1718   // When building with -fapple-kext, all calls must go through the vtable since
1719   // the kernel linker can do runtime patching of vtables.
1720   if (Context.getLangOpts().AppleKext)
1721     return true;
1722 
1723   return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1724 }
1725 
1726 llvm::Value *
1727 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1728                                              const CXXMethodDecl *MD,
1729                                              llvm::Value *This) {
1730   llvm::FunctionType *fnType =
1731     CGM.getTypes().GetFunctionType(
1732                              CGM.getTypes().arrangeCXXMethodDeclaration(MD));
1733 
1734   if (UseVirtualCall(getContext(), E, MD))
1735     return BuildVirtualCall(MD, This, fnType);
1736 
1737   return CGM.GetAddrOfFunction(MD, fnType);
1738 }
1739 
1740 void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
1741                                                  CallArgList &CallArgs) {
1742   // Lookup the call operator
1743   DeclarationName Name
1744     = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
1745   DeclContext::lookup_const_result Calls = Lambda->lookup(Name);
1746   CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++);
1747   const FunctionProtoType *FPT =
1748       CallOperator->getType()->getAs<FunctionProtoType>();
1749   QualType ResultType = FPT->getResultType();
1750 
1751   // Get the address of the call operator.
1752   GlobalDecl GD(CallOperator);
1753   const CGFunctionInfo &CalleeFnInfo =
1754     CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(),
1755                                        RequiredArgs::forPrototypePlus(FPT, 1));
1756   llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo);
1757   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
1758 
1759   // Determine whether we have a return value slot to use.
1760   ReturnValueSlot Slot;
1761   if (!ResultType->isVoidType() &&
1762       CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
1763       hasAggregateLLVMType(CurFnInfo->getReturnType()))
1764     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
1765 
1766   // Now emit our call.
1767   RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator);
1768 
1769   // Forward the returned value
1770   if (!ResultType->isVoidType() && Slot.isNull())
1771     EmitReturnOfRValue(RV, ResultType);
1772 }
1773 
1774 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
1775   const BlockDecl *BD = BlockInfo->getBlockDecl();
1776   const VarDecl *variable = BD->capture_begin()->getVariable();
1777   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
1778 
1779   // Start building arguments for forwarding call
1780   CallArgList CallArgs;
1781 
1782   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1783   llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
1784   CallArgs.add(RValue::get(ThisPtr), ThisType);
1785 
1786   // Add the rest of the parameters.
1787   for (BlockDecl::param_const_iterator I = BD->param_begin(),
1788        E = BD->param_end(); I != E; ++I) {
1789     ParmVarDecl *param = *I;
1790     EmitDelegateCallArg(CallArgs, param);
1791   }
1792 
1793   EmitForwardingCallToLambda(Lambda, CallArgs);
1794 }
1795 
1796 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1797   if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
1798     // FIXME: Making this work correctly is nasty because it requires either
1799     // cloning the body of the call operator or making the call operator forward.
1800     CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
1801     return;
1802   }
1803 
1804   EmitFunctionBody(Args);
1805 }
1806 
1807 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1808   const CXXRecordDecl *Lambda = MD->getParent();
1809 
1810   // Start building arguments for forwarding call
1811   CallArgList CallArgs;
1812 
1813   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1814   llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1815   CallArgs.add(RValue::get(ThisPtr), ThisType);
1816 
1817   // Add the rest of the parameters.
1818   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1819        E = MD->param_end(); I != E; ++I) {
1820     ParmVarDecl *param = *I;
1821     EmitDelegateCallArg(CallArgs, param);
1822   }
1823 
1824   EmitForwardingCallToLambda(Lambda, CallArgs);
1825 }
1826 
1827 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1828   if (MD->isVariadic()) {
1829     // FIXME: Making this work correctly is nasty because it requires either
1830     // cloning the body of the call operator or making the call operator forward.
1831     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
1832     return;
1833   }
1834 
1835   EmitLambdaDelegatingInvokeBody(MD);
1836 }
1837