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